The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
initial structure
Pedro Ladeira206b4d6373ce
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/tracking/add-hostname-modal.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/tracking/add-hostname-modal.tsxindex 368394d80e..da4b4dfe10 100644--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/tracking/add-hostname-modal.tsx+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/tracking/add-hostname-modal.tsx@@ -1,74 +1,29 @@"use client";-import { clientAccessCheck } from "@/lib/client-access-check";-import useWorkspace from "@/lib/swr/use-workspace";import { X } from "@/ui/shared/icons";-import { Button, LoadingDots, Modal, useMediaQuery } from "@dub/ui";+import { Button, Modal, useMediaQuery } from "@dub/ui";import { cn, validDomainRegex } from "@dub/utils";import { useCallback, useMemo, useState } from "react";import { toast } from "sonner";+const isValidHostname = (hostname: string) => {+ return (+ validDomainRegex.test(hostname) ||+ hostname === "localhost" ||+ hostname.startsWith("*.")+ );+};+const AddHostnameForm = ({- onCreate,+ existingHostnames,+ onAdd,onCancel,}: {- onCreate: () => void;+ existingHostnames: string[];+ onAdd: (hostname: string) => void;onCancel?: () => void;}) => {const [hostname, setHostname] = useState("");- const [processing, setProcessing] = useState(false);- const { id, allowedHostnames, mutate, role } = useWorkspace();-- const { error: permissionsError } = clientAccessCheck({- action: "workspaces.write",- role,- customPermissionDescription: "add hostnames",- });-- const isValidHostname = (hostname: string) => {- return (- validDomainRegex.test(hostname) ||- hostname === "localhost" ||- hostname.startsWith("*.")- );- };-- const addHostname = async () => {- if (allowedHostnames?.includes(hostname)) {- toast.error("Hostname already exists.");- return;- }-- if (!isValidHostname(hostname)) {- toast.error("Enter a valid domain.");- return;- }-- setProcessing(true);-- const response = await fetch(`/api/workspaces/${id}`, {- method: "PATCH",- headers: {- "Content-Type": "application/json",- },- body: JSON.stringify({- allowedHostnames: [...(allowedHostnames || []), hostname],- }),- });-- if (response.ok) {- toast.success("Hostname added.");- onCreate();- } else {- const { error } = await response.json();- toast.error(error.message);- }-- mutate();- setProcessing(false);- setHostname("");- };-const { isMobile } = useMediaQuery();return (@@ -76,7 +31,20 @@ const AddHostnameForm = ({className="bg-neutral-50"onSubmit={(e) => {e.preventDefault();- addHostname();+ e.stopPropagation();++ if (existingHostnames.includes(hostname)) {+ toast.error("Hostname already exists.");+ return;+ }++ if (!isValidHostname(hostname)) {+ toast.error("Enter a valid domain.");+ return;+ }++ onAdd(hostname);+ setHostname("");}}><div className="relative flex-1 rounded-md px-6 py-5">@@ -94,25 +62,20 @@ const AddHostnameForm = ({/></div>- <div className="flex items-center justify-between gap-2 border-t border-neutral-200 px-6 py-5">- <div>{processing && <LoadingDots />}</div>- <div className="flex items-center gap-2">- <Button- onClick={() => onCancel?.()}- variant="secondary"- text="Cancel"- className="h-8 w-fit px-3"- />- <Button- type="submit"- variant="primary"- text="Add hostname"- className="h-8 w-fit px-3"- disabled={!isValidHostname(hostname)}- loading={processing}- disabledTooltip={permissionsError || undefined}- />- </div>+ <div className="flex items-center justify-end gap-2 border-t border-neutral-200 px-6 py-5">+ <Button+ onClick={() => onCancel?.()}+ variant="secondary"+ text="Cancel"+ className="h-8 w-fit px-3"+ />+ <Button+ type="submit"+ variant="primary"+ text="Add hostname"+ className="h-8 w-fit px-3"+ disabled={!isValidHostname(hostname)}+ /></div></form>);@@ -121,11 +84,15 @@ const AddHostnameForm = ({interface AddHostnameModalProps {showModal: boolean;setShowModal: (showModal: boolean) => void;+ existingHostnames: string[];+ onAdd: (hostname: string) => void;}const AddHostnameModal = ({showModal,setShowModal,+ existingHostnames,+ onAdd,}: AddHostnameModalProps) => {const close = () => setShowModal(false);return (@@ -142,13 +109,26 @@ const AddHostnameModal = ({</div><div className="bg-neutral-50">- <AddHostnameForm onCancel={close} onCreate={close} />+ <AddHostnameForm+ existingHostnames={existingHostnames}+ onCancel={close}+ onAdd={(hostname) => {+ onAdd(hostname);+ close();+ }}+ /></div></Modal>);};-export function useAddHostnameModal() {+export function useAddHostnameModal({+ existingHostnames,+ onAdd,+}: {+ existingHostnames: string[];+ onAdd: (hostname: string) => void;+}) {const [showAddHostnameModal, setShowAddHostnameModal] = useState(false);const AddHostnameModalCallback = useCallback(() => {@@ -156,15 +136,17 @@ export function useAddHostnameModal() {<AddHostnameModalshowModal={showAddHostnameModal}setShowModal={setShowAddHostnameModal}+ existingHostnames={existingHostnames}+ onAdd={onAdd}/>);- }, [showAddHostnameModal, setShowAddHostnameModal]);+ }, [showAddHostnameModal, existingHostnames, onAdd]);return useMemo(() => ({setShowAddHostnameModal,AddHostnameModal: AddHostnameModalCallback,}),- [setShowAddHostnameModal, AddHostnameModalCallback],+ [AddHostnameModalCallback],);}diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/tracking/add-sitemap-modal.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/tracking/add-sitemap-modal.tsxnew file mode 100644index 0000000000..16af622c7d--- /dev/null+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/tracking/add-sitemap-modal.tsx@@ -0,0 +1,142 @@+"use client";++import { X } from "@/ui/shared/icons";+import { Button, Modal, useMediaQuery } from "@dub/ui";+import { cn } from "@dub/utils";+import { useCallback, useMemo, useState } from "react";+import { toast } from "sonner";++const normalizeSitemapUrl = (value: string) => {+ const trimmed = value.trim();+ if (!trimmed) {+ return null;+ }++ const withProtocol =+ trimmed.startsWith("http://") || trimmed.startsWith("https://")+ ? trimmed+ : `https://${trimmed}`;++ try {+ return new URL(withProtocol).toString();+ } catch {+ return null;+ }+};++const AddSitemapForm = ({+ existingUrls,+ onAdd,+ onCancel,+}: {+ existingUrls: string[];+ onAdd: (url: string) => void;+ onCancel?: () => void;+}) => {+ const [url, setUrl] = useState("");+ const { isMobile } = useMediaQuery();+ const normalizedUrl = normalizeSitemapUrl(url);++ return (+ <form+ className="bg-neutral-50"+ onSubmit={(e) => {+ e.preventDefault();+ e.stopPropagation();++ if (!normalizedUrl) {+ toast.error("Enter a valid sitemap URL.");+ return;+ }++ if (existingUrls.includes(normalizedUrl)) {+ toast.error("Sitemap already exists.");+ return;+ }++ onAdd(normalizedUrl);+ setUrl("");+ }}+ >+ <div className="relative flex-1 rounded-md px-6 py-5">+ <input+ type="text"+ required+ value={url}+ onChange={(e) => setUrl(e.target.value)}+ autoComplete="off"+ autoFocus={!isMobile}+ placeholder="https://acme.com/sitemap.xml"+ className={cn(+ "block w-full rounded-md border-neutral-300 text-neutral-900 placeholder-neutral-400 focus:border-neutral-500 focus:outline-none focus:ring-neutral-500 sm:text-sm",+ )}+ />+ </div>++ <div className="flex items-center justify-end gap-2 border-t border-neutral-200 px-6 py-5">+ <Button+ onClick={() => onCancel?.()}+ variant="secondary"+ text="Cancel"+ className="h-8 w-fit px-3"+ />+ <Button+ type="submit"+ variant="primary"+ text="Add sitemap"+ className="h-8 w-fit px-3"+ disabled={!normalizedUrl}+ />+ </div>+ </form>+ );+};++export function useAddSitemapModal({+ existingUrls,+ onAdd,+}: {+ existingUrls: string[];+ onAdd: (url: string) => void;+}) {+ const [showAddSitemapModal, setShowAddSitemapModal] = useState(false);++ const AddSitemapModalCallback = useCallback(() => {+ return (+ <Modal+ showModal={showAddSitemapModal}+ setShowModal={setShowAddSitemapModal}+ >+ <div className="flex items-center justify-between border-b border-neutral-200 p-4">+ <h3 className="text-lg font-medium">Add sitemap</h3>+ <button+ type="button"+ onClick={() => setShowAddSitemapModal(false)}+ className="group rounded-full p-2 text-neutral-500 transition-all duration-75 hover:bg-neutral-100 focus:outline-none active:bg-neutral-200"+ >+ <X className="h-5 w-5" />+ </button>+ </div>++ <div className="bg-neutral-50">+ <AddSitemapForm+ existingUrls={existingUrls}+ onCancel={() => setShowAddSitemapModal(false)}+ onAdd={(sitemapUrl) => {+ onAdd(sitemapUrl);+ setShowAddSitemapModal(false);+ }}+ />+ </div>+ </Modal>+ );+ }, [showAddSitemapModal, existingUrls, onAdd]);++ return useMemo(+ () => ({+ setShowAddSitemapModal,+ AddSitemapModal: AddSitemapModalCallback,+ }),+ [AddSitemapModalCallback],+ );+}diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/tracking/base-script-section.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/tracking/base-script-section.tsxdeleted file mode 100644index ffd510d66b..0000000000--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/tracking/base-script-section.tsx+++ /dev/null@@ -1,54 +0,0 @@-"use client";--import { LockSmall, Switch } from "@dub/ui";-import { useId } from "react";-import { HostnameSection } from "./hostname-section";--export function BaseScriptSection() {- const id = useId();-- return (- <div className="flex flex-1 flex-col rounded-lg border border-neutral-200 bg-neutral-50">- <div className="flex items-center justify-between gap-4 p-3">- <div className="flex min-w-0 items-center gap-4">- <div className="overflow-hidden">- <label- htmlFor={`${id}-switch`}- className="text-content-emphasis block text-sm font-semibold"- >- Base script- </label>- <p className="text-content-subtle text-sm font-medium">- For basic cookie-management and{" "}- <a- href="https://dub.co/docs/sdks/client-side/features/click-tracking"- target="_blank"- rel="noopener noreferrer"- className="cursor-help text-neutral-800 underline decoration-dotted underline-offset-2"- >- client-side click tracking- </a>- .- </p>- </div>- </div>-- <Switch- disabledTooltip="Required for all Dub tracking"- disabled- checked={true}- trackDimensions="radix-state-checked:bg-black focus-visible:ring-black/20 w-7 h-4"- thumbDimensions="size-3"- thumbTranslate="translate-x-3"- thumbIcon={- <div className="flex size-full items-center justify-center">- <LockSmall className="size-[8px] text-black" />- </div>- }- />- </div>-- <HostnameSection className="border-t border-neutral-200" />- </div>- );-}diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/tracking/complete-step-button.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/tracking/complete-step-button.tsxdeleted file mode 100644index 927418e9bc..0000000000--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/tracking/complete-step-button.tsx+++ /dev/null@@ -1,13 +0,0 @@-import { Button } from "@dub/ui";--export const CompleteStepButton = ({- onClick,- loading,-}: {- onClick: () => void;- loading?: boolean;-}) => {- return (- <Button text="Mark step as complete" loading={loading} onClick={onClick} />- );-};diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/tracking/configure-tracking-section.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/tracking/configure-tracking-section.tsxnew file mode 100644index 0000000000..7142f4e2f1--- /dev/null+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/tracking/configure-tracking-section.tsx@@ -0,0 +1,362 @@+"use client";++import { clientAccessCheck } from "@/lib/client-access-check";+import useWorkspace from "@/lib/swr/use-workspace";+import { useWorkspaceStore } from "@/lib/swr/use-workspace-store";+import { guides, stackItems } from "@/ui/guides/integrations";+import { Button } from "@dub/ui";+import { useEffect, useMemo } from "react";+import { Controller, useForm } from "react-hook-form";+import { toast } from "sonner";+import { HostnameField } from "./hostname-field";+import { OutboundDomainTrackingField } from "./outbound-domain-tracking-field";+import { PublishableKeyField } from "./publishable-key-field";+import { SectionCard } from "./section-card";+import { SiteVisitTrackingField } from "./site-visit-tracking-field";+import { StackPicker, StackSelectionStatus } from "./stack-picker";+import { emptyTrackingFormValues, TrackingFormData } from "./tracking-form";+import { TrackingSettingsRow } from "./tracking-settings-row";++const STACK_DESCRIPTION =+ "Select all items that apply to your stack. [Learn more](https://dub.co/docs/conversions/quickstart)";+const HOSTNAMES_DESCRIPTION =+ "Allowlist domains that you want to allow client-side click tracking on. [Learn more](https://dub.co/docs/sdks/client-side/features/click-tracking)";+const PUBLISHABLE_KEY_DESCRIPTION =+ "Required for authenticating request when tracking conversion events on the client-side. [Learn more](https://dub.co/docs/api-reference/publishable-keys)";+const SITE_VISIT_DESCRIPTION =+ "For tracking site visits (organic visits from Google/SEO/AEO). [Learn more](https://dub.co/docs/concepts/attribution)";+const OUTBOUND_DESCRIPTION =+ "Track outbound clicks to your other domains. [Learn more](https://dub.co/docs/sdks/client-side/features/cross-domain-tracking#cross-domain-tracking)";++export function ConfigureTrackingSection() {+ const workspace = useWorkspace();+ const {+ id,+ role,+ flags,+ mutate,+ loading: workspaceLoading,+ allowedHostnames,+ publishableKey,+ siteVisitTrackingSettings,+ } = workspace;++ const permissionsError = clientAccessCheck({+ action: "workspaces.write",+ role,+ customPermissionDescription: "manage tracking settings",+ }).error;+ const disabledTooltip =+ typeof permissionsError === "string" ? permissionsError : undefined;++ const [savedStack, setSavedStack, { loading: stackLoading }] =+ useWorkspaceStore<string[]>("analyticsSettingsSelectedStack");+ const [siteVisitEnabled, setSiteVisitEnabled] = useWorkspaceStore<boolean>(+ "analyticsSettingsSiteVisitTrackingEnabled",+ );+ const [outboundEnabled, setOutboundEnabled] = useWorkspaceStore<boolean>(+ "analyticsSettingsOutboundDomainTrackingEnabled",+ );+ const [, setConversionEnabled] = useWorkspaceStore<boolean>(+ "analyticsSettingsConversionTrackingEnabled",+ );+ const [, setConnectionComplete] = useWorkspaceStore<boolean>(+ "analyticsSettingsConnectionSetupComplete",+ );+ const [, setLeadComplete] = useWorkspaceStore<boolean>(+ "analyticsSettingsLeadTrackingSetupComplete",+ );+ const [, setSaleComplete] = useWorkspaceStore<boolean>(+ "analyticsSettingsSaleTrackingSetupComplete",+ );++ const persistedSitemaps = useMemo(+ () =>+ (siteVisitTrackingSettings?.trackedSitemaps ?? [])+ .filter((sitemap) => sitemap?.url)+ .map((sitemap) => ({+ url: sitemap.url,+ ...(sitemap.lastCrawledAt+ ? { lastCrawledAt: sitemap.lastCrawledAt }+ : {}),+ ...(typeof sitemap.lastUrlCount === "number"+ ? { lastUrlCount: sitemap.lastUrlCount }+ : {}),+ })),+ [siteVisitTrackingSettings],+ );++ const defaultValues = useMemo<TrackingFormData>(+ () => ({+ stack: savedStack ?? [],+ allowedHostnames: allowedHostnames ?? [],+ publishableKey: publishableKey ?? null,+ siteVisitTrackingEnabled: Boolean(siteVisitEnabled),+ siteDomainSlug: siteVisitTrackingSettings?.siteDomainSlug ?? "",+ trackedSitemaps: persistedSitemaps,+ outboundDomainTrackingEnabled: Boolean(outboundEnabled),+ }),+ [+ savedStack,+ allowedHostnames,+ publishableKey,+ siteVisitEnabled,+ siteVisitTrackingSettings?.siteDomainSlug,+ persistedSitemaps,+ outboundEnabled,+ ],+ );++ const {+ control,+ handleSubmit,+ reset,+ watch,+ setValue,+ formState: { isDirty, isSubmitting },+ } = useForm<TrackingFormData>({+ defaultValues: emptyTrackingFormValues,+ });++ const loading = Boolean(workspaceLoading || stackLoading);++ useEffect(() => {+ if (loading || isDirty) {+ return;+ }++ reset(defaultValues);+ }, [loading, isDirty, defaultValues, reset]);++ const persistedSitemapUrls = persistedSitemaps.map((sitemap) => sitemap.url);+ const disabled = Boolean(permissionsError) || loading;+ const selectedStack = watch("stack") ?? [];++ const onSubmit = async (data: TrackingFormData) => {+ if (!id) {+ toast.error("Workspace is still loading. Please try again.");+ return;+ }++ try {+ const response = await fetch(`/api/workspaces/${id}`, {+ method: "PATCH",+ headers: {+ "Content-Type": "application/json",+ },+ body: JSON.stringify({+ allowedHostnames: data.allowedHostnames,+ publishableKey: data.publishableKey,+ ...(flags?.analyticsSettingsSiteVisitTracking+ ? {+ siteVisitTrackingSettings: {+ trackedSitemaps: data.trackedSitemaps,+ siteDomainSlug: data.siteDomainSlug || null,+ },+ }+ : {}),+ }),+ });++ if (!response.ok) {+ const { error } = await response.json();+ toast.error(error?.message || "Failed to save settings.");+ return;+ }++ await setSavedStack(data.stack);+ await setSiteVisitEnabled(data.siteVisitTrackingEnabled);+ await setOutboundEnabled(data.outboundDomainTrackingEnabled);++ if (data.publishableKey) {+ await setConversionEnabled(true);+ }++ if (data.allowedHostnames.length > 0 && data.stack.length > 0) {+ await setConnectionComplete(true);++ const selectedGuideTypes = new Set(+ data.stack.flatMap(+ (stackId) =>+ stackItems.find((item) => item.id === stackId)?.guideKeys ?? [],+ )+ .map((key) => guides.find((guide) => guide.key === key)?.type)+ .filter(Boolean),+ );++ if (selectedGuideTypes.has("track-lead")) {+ await setLeadComplete(true);+ }++ if (selectedGuideTypes.has("track-sale")) {+ await setSaleComplete(true);+ }+ }++ const existingUrls = new Set(persistedSitemapUrls);+ const newSitemaps = data.trackedSitemaps.filter(+ (sitemap) => !existingUrls.has(sitemap.url),+ );++ for (const sitemap of newSitemaps) {+ const importResponse = await fetch(+ `/api/workspaces/${id}/sitemaps/import`,+ {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ },+ body: JSON.stringify({+ sitemapUrl: sitemap.url,+ }),+ },+ );++ if (!importResponse.ok) {+ try {+ const { error } = await importResponse.json();+ toast.error(error?.message || "Sitemap added, but crawl failed.");+ } catch {+ toast.error("Sitemap added, but crawl failed.");+ }+ }+ }++ await mutate();+ reset(data);+ toast.success("Tracking settings saved.");+ } catch {+ toast.error("Network error, please try again.");+ }+ };++ return (+ <SectionCard number={1} title="Configure tracking">+ <form onSubmit={handleSubmit(onSubmit)}>+ <div className="divide-y divide-neutral-200">+ <TrackingSettingsRow+ heading="Stack"+ description={STACK_DESCRIPTION}+ leftExtra={+ selectedStack.length > 0 ? (+ <StackSelectionStatus count={selectedStack.length} />+ ) : undefined+ }+ leftExtraAlign="end"+ >+ <Controller+ control={control}+ name="stack"+ render={({ field }) => (+ <StackPicker+ items={stackItems}+ value={field.value}+ onChange={field.onChange}+ disabled={disabled}+ />+ )}+ />+ </TrackingSettingsRow>++ <TrackingSettingsRow+ heading="Allowed hostnames"+ description={HOSTNAMES_DESCRIPTION}+ >+ <Controller+ control={control}+ name="allowedHostnames"+ render={({ field }) => (+ <HostnameField+ hostnames={field.value}+ onChange={field.onChange}+ disabled={disabled}+ disabledTooltip={disabledTooltip}+ />+ )}+ />+ </TrackingSettingsRow>++ <TrackingSettingsRow+ heading="Publishable key"+ description={PUBLISHABLE_KEY_DESCRIPTION}+ >+ <Controller+ control={control}+ name="publishableKey"+ render={({ field }) => (+ <PublishableKeyField+ publishableKey={field.value}+ onChange={field.onChange}+ disabled={disabled}+ disabledTooltip={disabledTooltip}+ />+ )}+ />+ </TrackingSettingsRow>++ {flags?.analyticsSettingsSiteVisitTracking && (+ <TrackingSettingsRow+ heading="Site visit tracking"+ description={SITE_VISIT_DESCRIPTION}+ align={+ watch("siteVisitTrackingEnabled") ? "start" : "center"+ }+ >+ <SiteVisitTrackingField+ enabled={watch("siteVisitTrackingEnabled")}+ onEnabledChange={(enabled) =>+ setValue("siteVisitTrackingEnabled", enabled, {+ shouldDirty: true,+ })+ }+ siteDomainSlug={watch("siteDomainSlug")}+ onSiteDomainSlugChange={(slug) =>+ setValue("siteDomainSlug", slug, { shouldDirty: true })+ }+ sitemaps={watch("trackedSitemaps")}+ onSitemapsChange={(sitemaps) =>+ setValue("trackedSitemaps", sitemaps, { shouldDirty: true })+ }+ persistedSitemapUrls={persistedSitemapUrls}+ workspaceId={id}+ onSitemapRefreshed={() => void mutate()}+ disabled={disabled}+ disabledTooltip={disabledTooltip}+ />+ </TrackingSettingsRow>+ )}++ <TrackingSettingsRow+ heading="Outbound domain tracking"+ description={OUTBOUND_DESCRIPTION}+ align="center"+ >+ <OutboundDomainTrackingField+ enabled={watch("outboundDomainTrackingEnabled")}+ onEnabledChange={(enabled) =>+ setValue("outboundDomainTrackingEnabled", enabled, {+ shouldDirty: true,+ })+ }+ disabled={disabled}+ disabledTooltip={disabledTooltip}+ />+ </TrackingSettingsRow>+ </div>++ <div className="flex items-center justify-end border-t border-neutral-200 px-5 py-4">+ <Button+ text="Save changes"+ className="h-8 w-fit px-3"+ loading={isSubmitting}+ disabled={!isDirty || loading}+ disabledTooltip={+ disabledTooltip ||+ (!isDirty ? "No unsaved changes" : undefined)+ }+ />+ </div>+ </form>+ </SectionCard>+ );+}diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/tracking/connection-instructions.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/tracking/connection-instructions.tsxdeleted file mode 100644index c7c623de78..0000000000--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/tracking/connection-instructions.tsx+++ /dev/null@@ -1,64 +0,0 @@-"use client";--import { GuideActionButton } from "@/ui/guides/guide-action-button";-import { GuideSelector } from "@/ui/guides/guide-selector";-import { guides as allGuides } from "@/ui/guides/integrations";-import { GuidesMarkdown } from "@/ui/guides/markdown";-import { useDynamicGuide } from "./use-dynamic-guide";-import { useSelectedGuide } from "./use-selected-guide";--export function ConnectionInstructions() {- const guides = allGuides.filter((guide) => guide.type === "client-sdk");- const { selectedGuide, setSelectedGuide } = useSelectedGuide({ guides });-- const { loading, guideMarkdown } = useDynamicGuide({- guide: selectedGuide.key,- });-- let button: React.ReactNode;- let content: React.ReactNode;-- if (loading) {- content = (- <div className="space-y-4">- <div className="h-6 w-1/2 animate-pulse rounded bg-neutral-200" />- <div className="h-4 w-full animate-pulse rounded bg-neutral-100" />- <div className="h-4 w-5/6 animate-pulse rounded bg-neutral-100" />- <div className="h-4 w-2/3 animate-pulse rounded bg-neutral-100" />- </div>- );- button = (- <div className="h-8 w-24 animate-pulse rounded-md bg-neutral-200" />- );- } else if (guideMarkdown) {- content = <GuidesMarkdown>{guideMarkdown}</GuidesMarkdown>;- button = (- <GuideActionButton guide={selectedGuide} markdown={guideMarkdown} />- );- } else {- content = (- <div className="text-content-subtle flex size-full items-center justify-center text-sm">- Failed to load guide- </div>- );- }-- return (- <div className="overflow-hidden rounded-xl border border-neutral-200 bg-neutral-50">- <div className="flex items-center justify-between p-3">- <GuideSelector- value={selectedGuide}- onChange={setSelectedGuide}- guides={guides}- className="-my-1 -ml-1"- />-- {button}- </div>-- <div className="max-w-full rounded-t-xl border-t border-neutral-200 bg-white p-5">- <div className="mx-auto max-w-2xl">{content}</div>- </div>- </div>- );-}diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/tracking/conversion-tracking-section.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/tracking/conversion-tracking-section.tsxdeleted file mode 100644index c5333ce15a..0000000000--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/tracking/conversion-tracking-section.tsx+++ /dev/null@@ -1,96 +0,0 @@-"use client";--import { clientAccessCheck } from "@/lib/client-access-check";-import useWorkspace from "@/lib/swr/use-workspace";-import { useWorkspaceStore } from "@/lib/swr/use-workspace-store";-import { LockSmall, Switch } from "@dub/ui";-import { motion } from "motion/react";-import { useEffect, useId } from "react";-import { PublishableKeyForm } from "./publishable-key-form";--export function ConversionTrackingSection() {- const id = useId();-- const { role, publishableKey } = useWorkspace();-- const permissionsError = clientAccessCheck({- action: "workspaces.write",- role,- customPermissionDescription: "manage conversion tracking settings",- }).error;-- const [enabled, setEnabled, { loading }] = useWorkspaceStore<boolean>(- "analyticsSettingsConversionTrackingEnabled",- {- mutateOnSet: true,- },- );-- // Default to enabled if the workspace already has a publishable key- useEffect(() => {- if (publishableKey && enabled === undefined) setEnabled(true);- }, [publishableKey, enabled]);-- return (- <div className="flex flex-1 flex-col rounded-lg border border-neutral-200 bg-neutral-50">- <div className="flex items-center justify-between gap-4 p-3">- <div className="flex min-w-0 items-center gap-4">- <div className="overflow-hidden">- <label- htmlFor={`${id}-switch`}- className="text-content-emphasis block text-sm font-semibold"- >- Conversion tracking- </label>- <p className="text-content-subtle text-sm font-medium">- For client-side conversion tracking.{" "}- <a- href="https://dub.co/docs/conversions/quickstart"- target="_blank"- rel="noopener noreferrer"- className="cursor-help text-neutral-800 underline decoration-dotted underline-offset-2"- >- Learn more- </a>- .- </p>- </div>- </div>-- <Switch- disabled={loading}- checked={enabled || false}- trackDimensions="radix-state-checked:bg-black focus-visible:ring-black/20 w-7 h-4"- thumbDimensions="size-3"- thumbTranslate="translate-x-3"- fn={setEnabled}- {...(publishableKey || permissionsError- ? {- disabledTooltip:- permissionsError ||- "You need to revoke your current publishable key first before disabling conversion tracking.",- thumbIcon: (- <div className="flex size-full items-center justify-center">- <LockSmall className="size-[8px] text-black" />- </div>- ),- }- : {})}- />- </div>-- <motion.div- animate={{- height: enabled ? "auto" : 0,- overflow: "hidden",- }}- transition={{- duration: 0.15,- }}- initial={false}- >- <PublishableKeyForm className="border-t border-neutral-200" />- </motion.div>- </div>- );-}diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/tracking/enable-switch.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/tracking/enable-switch.tsxnew file mode 100644index 0000000000..04fc79b9a6--- /dev/null+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/tracking/enable-switch.tsx@@ -0,0 +1,27 @@+"use client";++import { Switch } from "@dub/ui";++export function EnableSwitch({+ checked,+ onChange,+ disabled,+ disabledTooltip,+}: {+ checked: boolean;+ onChange: (checked: boolean) => void;+ disabled?: boolean;+ disabledTooltip?: string;+}) {+ return (+ <label className="flex w-fit cursor-pointer items-center gap-2">+ <Switch+ checked={checked}+ fn={onChange}+ disabled={disabled}+ disabledTooltip={disabledTooltip}+ />+ <span className="text-content-default text-sm font-medium">Enable</span>+ </label>+ );+}diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/tracking/hostname-field.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/tracking/hostname-field.tsxnew file mode 100644index 0000000000..1b9a82dcd8--- /dev/null+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/tracking/hostname-field.tsx@@ -0,0 +1,117 @@+"use client";++import { useConfirmModal } from "@/ui/modals/confirm-modal";+import { Button, Globe } from "@dub/ui";+import { cn } from "@dub/utils";+import { useAddHostnameModal } from "./add-hostname-modal";+import HostnameMenu from "./hostname-menu";++export function HostnameField({+ hostnames,+ onChange,+ disabled,+ disabledTooltip,+}: {+ hostnames: string[];+ onChange: (hostnames: string[]) => void;+ disabled?: boolean;+ disabledTooltip?: string;+}) {+ const { AddHostnameModal, setShowAddHostnameModal } = useAddHostnameModal({+ existingHostnames: hostnames,+ onAdd: (hostname) => {+ onChange([...hostnames, hostname]);+ },+ });++ return (+ <>+ <div className="flex flex-col gap-2">+ {hostnames.length === 0 ? (+ <div className="flex items-center justify-between gap-3 rounded-xl border border-neutral-200 bg-neutral-100 px-3 py-2.5">+ <div className="flex min-w-0 items-center gap-2.5">+ <Globe className="size-4 shrink-0 text-neutral-600" />+ <span className="text-content-subtle text-sm font-medium">+ No hostnames added+ </span>+ </div>+ <Button+ text="Add hostname"+ variant="secondary"+ className="h-8 w-fit px-2.5"+ onClick={() => setShowAddHostnameModal(true)}+ disabled={disabled}+ disabledTooltip={disabledTooltip}+ />+ </div>+ ) : (+ <>+ <div className="flex flex-col gap-2">+ {hostnames.map((hostname) => (+ <HostnameRow+ key={hostname}+ hostname={hostname}+ disabled={disabled}+ onDelete={() =>+ onChange(hostnames.filter((item) => item !== hostname))+ }+ />+ ))}+ </div>+ <Button+ text="Add hostname"+ variant="secondary"+ className="h-8 w-fit px-2.5"+ onClick={() => setShowAddHostnameModal(true)}+ disabled={disabled}+ disabledTooltip={disabledTooltip}+ />+ </>+ )}+ </div>+ <AddHostnameModal />+ </>+ );+}++function HostnameRow({+ hostname,+ disabled,+ onDelete,+}: {+ hostname: string;+ disabled?: boolean;+ onDelete: () => void;+}) {+ const { setShowConfirmModal, confirmModal } = useConfirmModal({+ title: "Delete Hostname",+ description: `Are you sure you want to delete "${hostname}"? This action cannot be undone.`,+ confirmText: "Delete Hostname",+ onConfirm: onDelete,+ });++ return (+ <div+ className={cn(+ "flex items-center justify-between gap-3 rounded-xl border border-neutral-200 bg-white px-3 py-2.5",+ disabled && "opacity-50",+ )}+ >+ <div className="flex min-w-0 items-center gap-2.5">+ <div className="flex size-7 items-center justify-center rounded-md bg-neutral-100">+ <Globe className="size-4 text-neutral-800" />+ </div>+ <span className="min-w-0 truncate text-sm font-medium text-neutral-800">+ {hostname}+ </span>+ </div>+ {!disabled && (+ <HostnameMenu+ onDelete={() => setShowConfirmModal(true)}+ loading={false}+ />+ )}+ {confirmModal}+ </div>+ );+}diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/tracking/hostname-section.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/tracking/hostname-section.tsxdeleted file mode 100644index 84647ba1ee..0000000000--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/tracking/hostname-section.tsx+++ /dev/null@@ -1,143 +0,0 @@-"use client";--import { clientAccessCheck } from "@/lib/client-access-check";-import useWorkspace from "@/lib/swr/use-workspace";-import { useConfirmModal } from "@/ui/modals/confirm-modal";-import { Button, CardList, Globe, InfoTooltip } from "@dub/ui";-import { cn } from "@dub/utils";-import { useState } from "react";-import { toast } from "sonner";-import { useAddHostnameModal } from "./add-hostname-modal";-import HostnameMenu from "./hostname-menu";--export const HostnameSection = ({ className }: { className?: string }) => {- const { AddHostnameModal, setShowAddHostnameModal } = useAddHostnameModal();- const { role, allowedHostnames, loading } = useWorkspace();-- const permissionsError = clientAccessCheck({- action: "workspaces.write",- role,- customPermissionDescription: "manage allowed hostnames",- }).error;-- let content;-- if (allowedHostnames && allowedHostnames.length > 0) {- content = (- <div className="grid grid-cols-1 gap-2">- <CardList variant="compact" loading={loading}>- {allowedHostnames?.map((hostname) => (- <HostnameCard key={hostname} hostname={hostname} />- ))}- </CardList>- </div>- );- } else {- content = (- <div className="flex items-center justify-center rounded-xl border border-neutral-200 bg-neutral-100 p-3">- <p className="text-content-subtle text-sm font-medium">- No hostnames added- </p>- </div>- );- }-- return (- <>- <div className={cn("flex flex-col gap-2 p-3", className)}>- <div className="flex items-center justify-between">- <div className="flex items-center gap-1">- <h2 className="text-content-emphasis flex-1 text-sm font-semibold">- Allowed hostnames- </h2>- <InfoTooltip content="Allowlist domains that you want to allow client-side click tracking on." />- </div>-- <Button- text="Add hostname"- className="h-7 w-fit rounded-lg px-2.5 py-1 text-sm font-medium"- onClick={() => setShowAddHostnameModal(true)}- disabledTooltip={permissionsError || undefined}- />- </div>-- {content}- </div>-- <AddHostnameModal />- </>- );-};--const HostnameCard = ({ hostname }: { hostname: string }) => {- const { id, allowedHostnames, mutate, role } = useWorkspace();- const [processing, setProcessing] = useState(false);-- const { allowed: canWriteWorkspaces } = clientAccessCheck({- action: "workspaces.write",- role,- customPermissionDescription: "delete hostnames",- });-- const handleDeleteHostname = async () => {- setProcessing(true);-- const response = await fetch(`/api/workspaces/${id}`, {- method: "PATCH",- headers: {- "Content-Type": "application/json",- },- body: JSON.stringify({- allowedHostnames: allowedHostnames?.filter((h) => h !== hostname),- }),- });-- if (response.ok) {- toast.success("Hostname deleted.");- } else {- const { error } = await response.json();- toast.error(error.message);- }-- mutate();- setProcessing(false);- };-- const { setShowConfirmModal, confirmModal } = useConfirmModal({- title: "Delete Hostname",- description: `Are you sure you want to delete "${hostname}"? This action cannot be undone.`,- confirmText: "Delete Hostname",- onConfirm: handleDeleteHostname,- });-- return (- <CardList.Card- key={hostname}- innerClassName={cn(- "flex items-center justify-between gap-5 sm:gap-8 md:gap-12 text-sm transition-opacity",- processing && "opacity-50",- )}- hoverStateEnabled={false}- >- <div className="flex min-w-0 grow items-center gap-3">- <div className="flex size-[28px] items-center justify-center rounded-md bg-neutral-100">- <Globe className="size-4 text-neutral-800" />- </div>-- <span className="min-w-0 truncate whitespace-nowrap font-medium text-neutral-800">- {hostname}- </span>- </div>-- <div className="flex items-center gap-5 sm:gap-8 md:gap-12">- {canWriteWorkspaces && (- <HostnameMenu- onDelete={() => setShowConfirmModal(true)}- loading={processing}- />- )}- </div>- {confirmModal}- </CardList.Card>- );-};diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/tracking/installation-section.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/tracking/installation-section.tsxnew file mode 100644index 0000000000..687967a83b--- /dev/null+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/tracking/installation-section.tsx@@ -0,0 +1,45 @@+"use client";++import useWorkspace from "@/lib/swr/use-workspace";+import { useWorkspaceStore } from "@/lib/swr/use-workspace-store";+import { SectionCard } from "./section-card";+import {+ DeveloperGuides,+ isSetupInstructionsReady,+ SetupInstructions,+} from "./setup-instructions";+import { TrackingSettingsRow } from "./tracking-settings-row";+import { VerifyInstall } from "./verify-install";++export function InstallationSection() {+ const { allowedHostnames } = useWorkspace();+ const [savedStack] = useWorkspaceStore<string[]>(+ "analyticsSettingsSelectedStack",+ );++ const stack = savedStack ?? [];+ const hostnames = allowedHostnames ?? [];+ const ready = isSetupInstructionsReady(stack, hostnames.length > 0);++ return (+ <SectionCard number={2} title="Installation and verification">+ <div className="divide-y divide-neutral-200">+ <TrackingSettingsRow+ heading="Setup instructions"+ description="Use the prompts and instructions to install Dub."+ leftExtra={ready ? <DeveloperGuides /> : undefined}+ >+ <SetupInstructions stack={stack} hasHostname={hostnames.length > 0} />+ </TrackingSettingsRow>++ <TrackingSettingsRow+ heading="Verify installation"+ description="To make sure it's all working!"+ align="center"+ >+ <VerifyInstall hostnames={hostnames} />+ </TrackingSettingsRow>+ </div>+ </SectionCard>+ );+}diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/tracking/outbound-domain-tracking-field.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/tracking/outbound-domain-tracking-field.tsxnew file mode 100644index 0000000000..b82ca53581--- /dev/null+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/tracking/outbound-domain-tracking-field.tsx@@ -0,0 +1,24 @@+"use client";++import { EnableSwitch } from "./enable-switch";++export function OutboundDomainTrackingField({+ enabled,+ onEnabledChange,+ disabled,+ disabledTooltip,+}: {+ enabled: boolean;+ onEnabledChange: (enabled: boolean) => void;+ disabled?: boolean;+ disabledTooltip?: string;+}) {+ return (+ <EnableSwitch+ checked={enabled}+ onChange={onEnabledChange}+ disabled={disabled}+ disabledTooltip={disabledTooltip}+ />+ );+}diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/tracking/outbound-domain-tracking-section.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/tracking/outbound-domain-tracking-section.tsxdeleted file mode 100644index 0b4dc9fbf5..0000000000--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/tracking/outbound-domain-tracking-section.tsx+++ /dev/null@@ -1,72 +0,0 @@-"use client";--import { clientAccessCheck } from "@/lib/client-access-check";-import useWorkspace from "@/lib/swr/use-workspace";-import { useWorkspaceStore } from "@/lib/swr/use-workspace-store";-import { LockSmall, Switch } from "@dub/ui";-import { useId } from "react";--export function OutboundDomainTrackingSection() {- const id = useId();- const { role } = useWorkspace();-- const [enabled, setEnabled, { loading }] = useWorkspaceStore<boolean>(- "analyticsSettingsOutboundDomainTrackingEnabled",- {- mutateOnSet: true,- },- );-- const permissionsError = clientAccessCheck({- action: "workspaces.write",- role,- customPermissionDescription: "manage outbound domain tracking",- }).error;-- return (- <div className="flex flex-1 flex-col rounded-lg border border-neutral-200 bg-neutral-50">- <div className="flex items-center justify-between gap-4 p-3">- <div className="flex min-w-0 items-center gap-4">- <div className="overflow-hidden">- <label- htmlFor={`${id}-switch`}- className="text-content-emphasis block text-sm font-semibold"- >- Outbound domain tracking- </label>- <p className="text-content-subtle text-sm font-medium">- Track outbound clicks to your other domains.{" "}- <a- href="https://dub.co/docs/sdks/client-side/features/cross-domain-tracking#cross-domain-tracking"- target="_blank"- rel="noopener noreferrer"- className="cursor-help text-neutral-800 underline decoration-dotted underline-offset-2"- >- Learn more- </a>- </p>- </div>- </div>-- <Switch- disabled={loading}- {...(permissionsError- ? {- disabledTooltip: permissionsError,- thumbIcon: (- <div className="flex size-full items-center justify-center">- <LockSmall className="size-[8px] text-black" />- </div>- ),- }- : {})}- checked={enabled || false}- trackDimensions="radix-state-checked:bg-black focus-visible:ring-black/20 w-7 h-4"- thumbDimensions="size-3"- thumbTranslate="translate-x-3"- fn={setEnabled}- />- </div>- </div>- );-}diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/tracking/page-client.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/tracking/page-client.tsxindex b2107d56d6..8329218da8 100644--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/tracking/page-client.tsx+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/tracking/page-client.tsx@@ -1,190 +1,13 @@"use client";-import useWorkspace from "@/lib/swr/use-workspace";-import { useWorkspaceStore } from "@/lib/swr/use-workspace-store";-import { AnimatedSizeContainer, useRouterStuff } from "@dub/ui";-import { BaseScriptSection } from "./base-script-section";-import { CompleteStepButton } from "./complete-step-button";-import { ConnectionInstructions } from "./connection-instructions";-import { ConversionTrackingSection } from "./conversion-tracking-section";-import { OutboundDomainTrackingSection } from "./outbound-domain-tracking-section";-import { SiteVisitTrackingSection } from "./site-visit-tracking-section";-import Step, { BaseStepProps, type Step as StepType } from "./step";-import { TrackLeadsGuidesSection } from "./track-lead-guides-section";-import { TrackSalesGuidesSection } from "./track-sales-guides-section";--const ConnectStep = ({- expanded,- toggleExpanded,- onComplete,-}: BaseStepProps & { onComplete: () => void }) => {- const { flags } = useWorkspace();-- const { searchParams } = useRouterStuff();- const guide = searchParams.get("guide");-- const [complete, markComplete, { loading }] = useWorkspaceStore<boolean>(- "analyticsSettingsConnectionSetupComplete",- );-- return (- <Step- id="connect"- step={1}- title="Install the Dub client-side script"- subtitle="Generate and install the Dub client-side script to start tracking conversions."- expanded={expanded}- toggleExpanded={toggleExpanded}- complete={complete}- >- <AnimatedSizeContainer height>- {guide !== "shopify" && (- <div className="grid gap-3 pb-8">- <BaseScriptSection />-- <ConversionTrackingSection />-- {flags?.analyticsSettingsSiteVisitTracking && (- <SiteVisitTrackingSection />- )}-- <OutboundDomainTrackingSection />- </div>- )}- </AnimatedSizeContainer>-- <ConnectionInstructions />-- {!complete && (- <div className="mt-5">- <CompleteStepButton- onClick={() => {- markComplete(true);- onComplete();- }}- loading={loading}- />- </div>- )}- {/* <VerifyInstall /> */}- </Step>- );-};--const LeadEventsStep = ({- expanded,- toggleExpanded,- onComplete,-}: BaseStepProps & { onComplete: () => void }) => {- const [complete, markComplete, { loading }] = useWorkspaceStore<boolean>(- "analyticsSettingsLeadTrackingSetupComplete",- );-- return (- <Step- id="lead"- step={2}- title="Track lead events"- subtitle="For lead events from your server using our server side SDKs or the REST API"- expanded={expanded}- toggleExpanded={toggleExpanded}- complete={complete}- contentClassName="grid gap-5"- >- <TrackLeadsGuidesSection />-- {!complete && (- <CompleteStepButton- onClick={() => {- markComplete(true);- onComplete();- }}- loading={loading}- />- )}- </Step>- );-};--const SaleEventsStep = ({- expanded,- toggleExpanded,- onComplete,-}: BaseStepProps & { onComplete: () => void }) => {- const [complete, markComplete, { loading }] = useWorkspaceStore<boolean>(- "analyticsSettingsSaleTrackingSetupComplete",- );-- return (- <Step- id="sale"- step={3}- title="Track sale events"- subtitle="For tracking purchases using our Stripe integration or our server side SDKs"- expanded={expanded}- toggleExpanded={toggleExpanded}- complete={complete}- contentClassName="grid gap-5"- >- <TrackSalesGuidesSection />-- {!complete && (- <CompleteStepButton- onClick={() => {- markComplete(true);- onComplete();- }}- loading={loading}- />- )}- </Step>- );-};+import { ConfigureTrackingSection } from "./configure-tracking-section";+import { InstallationSection } from "./installation-section";export function WorkspaceTrackingSettingsPageClient() {- const { searchParams, queryParams } = useRouterStuff();- const expandedStep = (searchParams.get("step") as StepType) || "connect";-- const toggleStep = (step: StepType) => {- if (expandedStep === step) {- queryParams({- del: ["step", "guide"],- });- } else {- queryParams({- del: "guide",- set: {- step,- },- });- }- };-- const closeStep = (step: StepType) => {- if (expandedStep === step) {- queryParams({- del: ["step", "guide"],- });- }- };-return (<div className="flex flex-1 flex-col gap-8 overflow-hidden">- <ConnectStep- expanded={expandedStep === "connect"}- toggleExpanded={() => toggleStep("connect")}- onComplete={() => closeStep("connect")}- />- <LeadEventsStep- expanded={expandedStep === "lead"}- toggleExpanded={() => toggleStep("lead")}- onComplete={() => closeStep("lead")}- />- <SaleEventsStep- expanded={expandedStep === "sale"}- toggleExpanded={() => toggleStep("sale")}- onComplete={() => closeStep("sale")}- />+ <ConfigureTrackingSection />+ <InstallationSection /></div>);}diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/tracking/page.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/tracking/page.tsxindex e0673e6909..30c2a52d8d 100644--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/tracking/page.tsx+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/tracking/page.tsx@@ -15,7 +15,7 @@ export default function WorkspaceTrackingSettingsPage() {}}controls={<ConversionTrackingToggle />}>- <PageWidthWrapper className="max-w-[800px] pb-20">+ <PageWidthWrapper className="pb-20"><Suspense><WorkspaceTrackingSettingsPageClient /></Suspense>diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/tracking/publishable-key-field.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/tracking/publishable-key-field.tsxnew file mode 100644index 0000000000..6c08037719--- /dev/null+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/tracking/publishable-key-field.tsx@@ -0,0 +1,91 @@+"use client";++import { useConfirmModal } from "@/ui/modals/confirm-modal";+import { Button, CopyButton, Key } from "@dub/ui";+import { nanoid } from "@dub/utils";+import PublishableKeyMenu from "./publishable-key-menu";++export function PublishableKeyField({+ publishableKey,+ onChange,+ disabled,+ disabledTooltip,+}: {+ publishableKey: string | null;+ onChange: (publishableKey: string | null) => void;+ disabled?: boolean;+ disabledTooltip?: string;+}) {+ const generateKey = () => `dub_pk_${nanoid(24)}`;++ const {+ setShowConfirmModal: setShowGenerateModal,+ confirmModal: generateModal,+ } = useConfirmModal({+ title: "Generate New Publishable Key",+ description: publishableKey+ ? "Are you sure you want to generate a new publishable key? This will invalidate the existing key after you save."+ : "This key will provide access to your workspace's conversion tracking endpoints.",+ confirmText: "Generate Key",+ onConfirm: () => onChange(generateKey()),+ });++ const { setShowConfirmModal: setShowRevokeModal, confirmModal: revokeModal } =+ useConfirmModal({+ title: "Revoke Publishable Key",+ description:+ "Are you sure you want to revoke the publishable key? This action cannot be undone after you save.",+ confirmText: "Revoke Key",+ onConfirm: () => onChange(null),+ });++ return (+ <>+ {publishableKey ? (+ <div className="flex flex-col gap-3 rounded-xl border border-neutral-200 bg-white p-3 sm:flex-row sm:items-center sm:justify-between sm:gap-2">+ <div className="flex min-w-0 items-center gap-2">+ <div className="flex size-7 shrink-0 items-center justify-center rounded-md bg-neutral-100">+ <Key className="size-4 text-neutral-800" />+ </div>+ <code className="min-w-0 truncate font-mono text-sm text-neutral-800">+ {publishableKey}+ </code>+ <CopyButton value={publishableKey} className="shrink-0" />+ </div>+ <div className="flex w-fit items-center gap-2 sm:shrink-0">+ <Button+ text="Regenerate"+ variant="secondary"+ onClick={() => setShowGenerateModal(true)}+ disabled={disabled}+ disabledTooltip={disabledTooltip}+ className="h-7 w-fit px-2 text-xs"+ />+ <PublishableKeyMenu+ onRevoke={() => setShowRevokeModal(true)}+ loading={false}+ />+ </div>+ </div>+ ) : (+ <div className="flex items-center justify-between gap-3 rounded-xl border border-neutral-200 bg-neutral-100 px-3 py-2.5">+ <div className="flex min-w-0 items-center gap-2.5">+ <Key className="size-4 shrink-0 text-neutral-600" />+ <span className="text-content-subtle text-sm font-medium">+ No publishable key generated+ </span>+ </div>+ <Button+ text="Generate key"+ className="h-8 w-fit px-2.5"+ onClick={() => setShowGenerateModal(true)}+ disabled={disabled}+ disabledTooltip={disabledTooltip}+ />+ </div>+ )}+ {generateModal}+ {revokeModal}+ </>+ );+}diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/tracking/publishable-key-form.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/tracking/publishable-key-form.tsxdeleted file mode 100644index e03c7d8f3b..0000000000--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/tracking/publishable-key-form.tsx+++ /dev/null@@ -1,151 +0,0 @@-"use client";--import { clientAccessCheck } from "@/lib/client-access-check";-import useWorkspace from "@/lib/swr/use-workspace";-import { useConfirmModal } from "@/ui/modals/confirm-modal";-import { Button, CopyButton, InfoTooltip, Key } from "@dub/ui";-import { cn, nanoid } from "@dub/utils";-import { useState } from "react";-import { toast } from "sonner";-import PublishableKeyMenu from "./publishable-key-menu";--export const PublishableKeyForm = ({ className }: { className?: string }) => {- const { id, publishableKey, mutate, role } = useWorkspace();- const [processing, setProcessing] = useState(false);-- const { error: permissionsError } = clientAccessCheck({- action: "workspaces.write",- role,- customPermissionDescription: "manage publishable keys",- });-- const handleGenerateKey = async () => {- setProcessing(true);-- const newPublishableKey = `dub_pk_${nanoid(24)}`;-- const response = await fetch(`/api/workspaces/${id}`, {- method: "PATCH",- headers: {- "Content-Type": "application/json",- },- body: JSON.stringify({- publishableKey: newPublishableKey,- }),- });-- if (response.ok) {- toast.success("Publishable key generated successfully.");- } else {- const { error } = await response.json();- toast.error(error.message);- }-- mutate();- setProcessing(false);- };-- const handleRevokeKey = async () => {- setProcessing(true);-- const response = await fetch(`/api/workspaces/${id}`, {- method: "PATCH",- headers: {- "Content-Type": "application/json",- },- body: JSON.stringify({- publishableKey: null,- }),- });-- if (response.ok) {- toast.success("Publishable key revoked successfully.");- } else {- const { error } = await response.json();- toast.error(error.message);- }-- mutate();- setProcessing(false);- };-- const {- setShowConfirmModal: setShowGenerateModal,- confirmModal: generateModal,- } = useConfirmModal({- title: "Generate New Publishable Key",- description: `Are you sure you want to generate a new publishable key? ${publishableKey ? "This will invalidate the existing key." : "This key will provide access to your workspace's conversion tracking endpoints."}`,- confirmText: "Generate Key",- onConfirm: handleGenerateKey,- });-- const { setShowConfirmModal: setShowRevokeModal, confirmModal: revokeModal } =- useConfirmModal({- title: "Revoke Publishable Key",- description:- "Are you sure you want to revoke the publishable key? This action cannot be undone.",- confirmText: "Revoke Key",- onConfirm: handleRevokeKey,- });-- return (- <div className={cn("flex flex-col gap-2 p-3", className)}>- <div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">- <div className="flex items-center gap-1">- <h2 className="text-content-emphasis flex-1 text-sm font-semibold">- Publishable key- </h2>- <InfoTooltip content="For authenticating requests when tracking conversion events on the client-side. [Learn more.](https://dub.co/docs/api-reference/publishable-keys)" />- </div>-- {!publishableKey && (- <Button- text="Generate"- className="h-7 w-fit rounded-lg px-2.5 py-1 text-sm font-medium"- onClick={() => setShowGenerateModal(true)}- loading={processing}- disabledTooltip={permissionsError || undefined}- />- )}- </div>-- {publishableKey ? (- <div className="flex flex-col gap-3 rounded-xl border border-neutral-200 bg-white p-3 sm:flex-row sm:items-center sm:justify-between sm:gap-2">- <div className="flex min-w-0 items-center gap-2">- <div className="flex min-w-0 items-center gap-4">- <div className="flex size-[28px] items-center justify-center rounded-md bg-neutral-100">- <Key className="size-4 text-neutral-800" />- </div>- <code className="min-w-0 flex-1 truncate font-mono text-sm text-neutral-800">- {publishableKey}- </code>- </div>- <CopyButton value={publishableKey} className="shrink-0" />- </div>- <div className="flex w-fit items-center gap-2 sm:shrink-0">- <Button- text="Regenerate"- variant="secondary"- onClick={() => setShowGenerateModal(true)}- loading={processing}- disabledTooltip={permissionsError || undefined}- className="h-7 w-fit flex-1 px-2 text-xs sm:flex-none"- />- <PublishableKeyMenu- onRevoke={() => setShowRevokeModal(true)}- loading={processing}- />- </div>- </div>- ) : (- <div className="flex items-center justify-center rounded-xl border border-neutral-200 bg-neutral-100 p-3">- <p className="text-content-subtle text-sm font-medium">- No publishable key created- </p>- </div>- )}- {generateModal}- {revokeModal}- </div>- );-};diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/tracking/section-card.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/tracking/section-card.tsxnew file mode 100644index 0000000000..e44732ec2d--- /dev/null+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/tracking/section-card.tsx@@ -0,0 +1,25 @@+import { PropsWithChildren, ReactNode } from "react";++export function SectionCard({+ number,+ title,+ children,+}: PropsWithChildren<{+ number: number;+ title: string;+ children?: ReactNode;+}>) {+ return (+ <div className="overflow-hidden rounded-xl border border-neutral-200 bg-white">+ <div className="flex items-center gap-3.5 px-5 py-5">+ <div className="text-content-emphasis flex size-[42px] shrink-0 items-center justify-center rounded-full bg-neutral-100 text-base font-semibold">+ {number}+ </div>+ <h2 className="text-content-emphasis text-base font-semibold">+ {title}+ </h2>+ </div>+ <div className="border-t border-neutral-200">{children}</div>+ </div>+ );+}diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/tracking/setup-instructions.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/tracking/setup-instructions.tsxnew file mode 100644index 0000000000..6aac3637d3--- /dev/null+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/tracking/setup-instructions.tsx@@ -0,0 +1,215 @@+"use client";++import { GuideActionButton } from "@/ui/guides/guide-action-button";+import {+ guides,+ IntegrationGuide,+ stackItems,+} from "@/ui/guides/integrations";+import { GuidesMarkdown } from "@/ui/guides/markdown";+import { Button, CircleDotted } from "@dub/ui";+import { cn } from "@dub/utils";+import { ArrowUpRight } from "lucide-react";+import Link from "next/link";+import { useMemo, useState } from "react";+import { useDynamicGuide } from "./use-dynamic-guide";++const DEVELOPER_GUIDES = [+ {+ title: "Client-side SDK install guide",+ href: "https://dub.co/docs/sdks/client-side",+ },+ {+ title: "Tracking lead events",+ href: "https://dub.co/docs/conversions/leads/introduction",+ },+ {+ title: "Tracking sale events",+ href: "https://dub.co/docs/conversions/sales/introduction",+ },+];++function extractFirstCodeBlock(markdown: string) {+ const match = markdown.match(/```(\w+)?\n([\s\S]*?)```/);+ if (!match) {+ return null;+ }++ return {+ language: match[1] ?? "text",+ code: match[2].trim(),+ };+}++function getSelectedStackItems(stackIds: string[]) {+ return stackItems.filter((item) => stackIds.includes(item.id));+}++function getPrimaryGuide(stackIds: string[]): IntegrationGuide | undefined {+ const selected = getSelectedStackItems(stackIds);+ const preferred =+ selected.find((item) => item.type === "client-sdk") ??+ selected.find((item) => item.type === "track-lead") ??+ selected.find((item) => item.type === "track-sale") ??+ selected[0];++ if (!preferred) {+ return undefined;+ }++ return guides.find((guide) => guide.key === preferred.guideKeys[0]);+}++export function isSetupInstructionsReady(+ stack: string[],+ hasHostname: boolean,+) {+ return stack.length > 0 && hasHostname;+}++export function DeveloperGuides() {+ return (+ <div className="mt-4 flex flex-col gap-2">+ <h4 className="text-content-emphasis text-sm font-semibold">+ Read developer guides+ </h4>+ <div className="flex flex-col">+ {DEVELOPER_GUIDES.map((guide) => (+ <Link+ key={guide.href}+ href={guide.href}+ target="_blank"+ rel="noopener noreferrer"+ className="text-content-default flex items-center justify-between gap-2 rounded-lg py-2 text-sm font-medium transition-colors duration-150 hover:bg-neutral-50"+ >+ {guide.title}+ <ArrowUpRight className="size-3.5 shrink-0 text-neutral-400" />+ </Link>+ ))}+ </div>+ </div>+ );+}++export function SetupInstructions({+ stack,+ hasHostname,+}: {+ stack: string[];+ hasHostname: boolean;+}) {+ const ready = isSetupInstructionsReady(stack, hasHostname);+ const primaryGuide = getPrimaryGuide(stack);+ const clientSdkItems = getSelectedStackItems(stack).filter(+ (item) => item.type === "client-sdk",+ );++ if (!ready) {+ return (+ <div className="flex flex-col items-center justify-center rounded-xl border border-dashed border-neutral-200 bg-neutral-50 px-6 py-16 text-center">+ <CircleDotted className="size-8 text-neutral-300" />+ <p className="text-content-subtle mt-3 max-w-sm text-sm font-medium">+ Select your stack, add at least one hostname to generate install+ instructions+ </p>+ </div>+ );+ }++ return (+ <div className="flex flex-col gap-5">+ {primaryGuide && <MainPromptCard guide={primaryGuide} />}++ {clientSdkItems.length > 0 && (+ <div className="flex flex-col gap-2">+ {clientSdkItems.map((item) => {+ const guide = guides.find((g) => g.key === item.guideKeys[0]);+ if (!guide) {+ return null;+ }++ const Icon = item.icon;++ return (+ <div+ key={item.id}+ className="flex items-center justify-between gap-3 rounded-xl border border-neutral-200 bg-white px-3 py-2.5"+ >+ <div className="flex min-w-0 items-center gap-2.5">+ <Icon className="size-5 shrink-0" />+ <span className="text-sm font-medium text-neutral-800">+ {item.title}+ </span>+ </div>+ <Button+ text="Read install guide"+ variant="secondary"+ className="h-8 w-fit px-2.5"+ onClick={() =>+ window.open(guide.url, "_blank", "noopener,noreferrer")+ }+ />+ </div>+ );+ })}+ </div>+ )}+ </div>+ );+}++function MainPromptCard({ guide }: { guide: IntegrationGuide }) {+ const { loading, guideMarkdown } = useDynamicGuide({ guide: guide.key });+ const [expanded, setExpanded] = useState(false);++ const snippet = useMemo(+ () => (guideMarkdown ? extractFirstCodeBlock(guideMarkdown) : null),+ [guideMarkdown],+ );++ return (+ <div className="overflow-hidden rounded-xl border border-neutral-200 bg-neutral-50">+ <div className="flex items-center justify-between gap-2 px-3 py-2.5">+ <h4 className="text-content-emphasis text-sm font-semibold">+ Main prompt+ </h4>+ {guideMarkdown && (+ <GuideActionButton guide={guide} markdown={guideMarkdown} />+ )}+ </div>++ <div className="rounded-t-xl border-t border-neutral-200 bg-white p-4">+ {loading ? (+ <div className="space-y-3">+ <div className="h-4 w-1/2 animate-pulse rounded bg-neutral-200" />+ <div className="h-4 w-full animate-pulse rounded bg-neutral-100" />+ <div className="h-4 w-5/6 animate-pulse rounded bg-neutral-100" />+ </div>+ ) : expanded && guideMarkdown ? (+ <GuidesMarkdown>{guideMarkdown}</GuidesMarkdown>+ ) : snippet ? (+ <pre+ className={cn(+ "overflow-x-auto font-mono text-[13px] leading-6 text-neutral-800",+ )}+ >+ <code>{snippet.code}</code>+ </pre>+ ) : (+ <p className="text-content-subtle text-sm">+ Failed to load install instructions.+ </p>+ )}++ {guideMarkdown && (+ <Button+ text={expanded ? "Show less" : "View all"}+ variant="secondary"+ className="mt-4 h-8 w-fit px-2.5"+ onClick={() => setExpanded((current) => !current)}+ />+ )}+ </div>+ </div>+ );+}diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/tracking/site-visit-tracking-field.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/tracking/site-visit-tracking-field.tsxnew file mode 100644index 0000000000..8198ca899a--- /dev/null+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/tracking/site-visit-tracking-field.tsx@@ -0,0 +1,290 @@+"use client";++import { MAX_TRACKED_SITEMAPS_PER_WORKSPACE } from "@/lib/zod/schemas/site-visit-tracking";+import { DomainSelector } from "@/ui/domains/domain-selector";+import { ThreeDots } from "@/ui/shared/icons";+import { Button, InfoTooltip, LoadingSpinner, Popover, Sitemap } from "@dub/ui";+import { Trash } from "@dub/ui/icons";+import { cn, formatDate } from "@dub/utils";+import { RefreshCw } from "lucide-react";+import { useState } from "react";+import { toast } from "sonner";+import { useAddSitemapModal } from "./add-sitemap-modal";+import { EnableSwitch } from "./enable-switch";+import { TrackedSitemapDraft } from "./tracking-form";++export function SiteVisitTrackingField({+ enabled,+ onEnabledChange,+ siteDomainSlug,+ onSiteDomainSlugChange,+ sitemaps,+ onSitemapsChange,+ persistedSitemapUrls,+ workspaceId,+ onSitemapRefreshed,+ disabled,+ disabledTooltip,+}: {+ enabled: boolean;+ onEnabledChange: (enabled: boolean) => void;+ siteDomainSlug: string;+ onSiteDomainSlugChange: (slug: string) => void;+ sitemaps: TrackedSitemapDraft[];+ onSitemapsChange: (sitemaps: TrackedSitemapDraft[]) => void;+ persistedSitemapUrls: string[];+ workspaceId?: string;+ onSitemapRefreshed?: () => void;+ disabled?: boolean;+ disabledTooltip?: string;+}) {+ const [refreshingSitemapUrl, setRefreshingSitemapUrl] = useState<+ string | null+ >(null);++ const addSitemap = (normalizedSitemapUrl: string) => {+ if (disabled) {+ return;+ }++ if (!siteDomainSlug) {+ toast.error("Choose a domain for sitemap imports before adding sources.");+ return;+ }++ if (sitemaps.some((sitemap) => sitemap.url === normalizedSitemapUrl)) {+ toast.error("Sitemap already exists.");+ return;+ }++ if (sitemaps.length >= MAX_TRACKED_SITEMAPS_PER_WORKSPACE) {+ toast.error(+ `You can track up to ${MAX_TRACKED_SITEMAPS_PER_WORKSPACE} sitemaps per workspace.`,+ );+ return;+ }++ onSitemapsChange([+ ...sitemaps,+ {+ url: normalizedSitemapUrl,+ },+ ]);+ };++ const { AddSitemapModal, setShowAddSitemapModal } = useAddSitemapModal({+ existingUrls: sitemaps.map((sitemap) => sitemap.url),+ onAdd: addSitemap,+ });++ const refreshSitemap = async (sitemapUrl: string) => {+ if (!workspaceId) {+ toast.error("Workspace is still loading. Please try again.");+ return;+ }++ setRefreshingSitemapUrl(sitemapUrl);++ try {+ const response = await fetch(+ `/api/workspaces/${workspaceId}/sitemaps/import`,+ {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ },+ body: JSON.stringify({+ sitemapUrl,+ }),+ },+ );++ if (response.ok) {+ toast.success("Sitemap refreshed.");+ onSitemapRefreshed?.();+ } else {+ const { error } = await response.json();+ toast.error(error?.message || "Failed to refresh sitemap.");+ }+ } catch {+ toast.error("Network error, please try again.");+ } finally {+ setRefreshingSitemapUrl(null);+ }+ };++ const addSitemapDisabledReason = disabledTooltip+ ? disabledTooltip+ : !siteDomainSlug+ ? "Choose a domain for imports first"+ : sitemaps.length >= MAX_TRACKED_SITEMAPS_PER_WORKSPACE+ ? `Maximum ${MAX_TRACKED_SITEMAPS_PER_WORKSPACE} sitemaps per workspace`+ : undefined;++ return (+ <>+ <div className="flex flex-col gap-4">+ <EnableSwitch+ checked={enabled}+ onChange={onEnabledChange}+ disabled={disabled}+ disabledTooltip={disabledTooltip}+ />++ {enabled && (+ <div className="flex flex-col gap-4">+ <div className="flex flex-col gap-2">+ <label className="text-content-emphasis text-sm font-semibold">+ Domain for sitemap imports+ </label>+ <DomainSelector+ selectedDomain={siteDomainSlug}+ setSelectedDomain={onSiteDomainSlugChange}+ disabled={disabled}+ disabledTooltip={disabledTooltip}+ />+ <p className="text-content-subtle text-xs font-medium">+ This domain will be used for links we create when importing+ pages from the sitemaps you add.+ </p>+ </div>++ <div className="flex flex-col gap-2">+ <h4 className="text-content-emphasis flex items-center gap-1 text-sm font-semibold">+ Sitemaps+ <InfoTooltip content="Add sitemap URLs we should crawl to create links for site visit tracking." />+ </h4>++ {sitemaps.length > 0 && (+ <div className="flex flex-col gap-2">+ {sitemaps.map((sitemap) => (+ <div+ key={sitemap.url}+ className="flex items-center justify-between gap-4 rounded-xl border border-neutral-200 bg-white p-3"+ >+ <div className="flex min-w-0 items-center gap-2">+ <div className="flex size-7 items-center justify-center rounded-md bg-neutral-100">+ <Sitemap className="size-4 text-neutral-800" />+ </div>+ <div className="flex min-w-0 flex-col">+ <span className="text-content-emphasis min-w-0 truncate text-sm font-semibold">+ {sitemap.url.replace(/^https?:\/\//, "")}+ </span>+ <span className="text-content-subtle text-xs font-medium">+ {sitemap.lastCrawledAt+ ? `Last crawled ${formatDate(sitemap.lastCrawledAt, { month: "short" })}`+ : "Not crawled yet"}+ {typeof sitemap.lastUrlCount === "number"+ ? ` • ${sitemap.lastUrlCount} URLs found`+ : ""}+ </span>+ </div>+ </div>+ {!disabled && (+ <SitemapRowMenu+ canRefresh={persistedSitemapUrls.includes(+ sitemap.url,+ )}+ onRefresh={() => refreshSitemap(sitemap.url)}+ onDelete={() =>+ onSitemapsChange(+ sitemaps.filter(+ (item) => item.url !== sitemap.url,+ ),+ )+ }+ loading={refreshingSitemapUrl === sitemap.url}+ />+ )}+ </div>+ ))}+ </div>+ )}++ <Button+ text="Add sitemap"+ variant="secondary"+ className="h-8 w-fit px-2.5"+ onClick={() => setShowAddSitemapModal(true)}+ disabled={disabled || Boolean(addSitemapDisabledReason)}+ disabledTooltip={addSitemapDisabledReason}+ />+ </div>+ </div>+ )}+ </div>+ <AddSitemapModal />+ </>+ );+}++function SitemapRowMenu({+ canRefresh,+ onRefresh,+ onDelete,+ loading,+}: {+ canRefresh: boolean;+ onRefresh: () => void;+ onDelete: () => void;+ loading: boolean;+}) {+ const [openPopover, setOpenPopover] = useState(false);++ return (+ <Popover+ content={+ <div className="w-full sm:w-48">+ {canRefresh && (+ <>+ <div className="grid gap-px p-2">+ <Button+ text="Refresh source"+ variant="outline"+ onClick={() => {+ setOpenPopover(false);+ onRefresh();+ }}+ icon={<RefreshCw className="h-4 w-4" />}+ className="h-9 justify-start px-2 font-medium"+ />+ </div>+ <div className="border-t border-neutral-200" />+ </>+ )}+ <div className="grid gap-px p-2">+ <Button+ text="Delete source"+ variant="danger-outline"+ onClick={() => {+ setOpenPopover(false);+ onDelete();+ }}+ icon={<Trash className="size-4" />}+ className="h-9 justify-start px-2 font-medium"+ />+ </div>+ </div>+ }+ align="end"+ openPopover={openPopover}+ setOpenPopover={setOpenPopover}+ >+ <Button+ variant="outline"+ className={cn(+ "h-8 w-fit px-1.5 outline-none transition-all duration-200",+ "border-transparent data-[state=open]:border-neutral-500",+ )}+ icon={+ loading ? (+ <LoadingSpinner className="size-4 shrink-0" />+ ) : (+ <ThreeDots className="size-5 shrink-0" />+ )+ }+ onClick={() => setOpenPopover(!openPopover)}+ />+ </Popover>+ );+}diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/tracking/site-visit-tracking-section.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/tracking/site-visit-tracking-section.tsxdeleted file mode 100644index 8165265ee1..0000000000--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/tracking/site-visit-tracking-section.tsx+++ /dev/null@@ -1,566 +0,0 @@-"use client";--import { clientAccessCheck } from "@/lib/client-access-check";-import useWorkspace from "@/lib/swr/use-workspace";-import { useWorkspaceStore } from "@/lib/swr/use-workspace-store";-import { MAX_TRACKED_SITEMAPS_PER_WORKSPACE } from "@/lib/zod/schemas/site-visit-tracking";-import { DomainSelector } from "@/ui/domains/domain-selector";-import { ThreeDots } from "@/ui/shared/icons";-import {- Button,- InfoTooltip,- LoadingSpinner,- LockSmall,- Popover,- Sitemap,- Switch,-} from "@dub/ui";-import { Trash } from "@dub/ui/icons";-import { cn, formatDate } from "@dub/utils";-import { RefreshCw } from "lucide-react";-import { motion } from "motion/react";-import { useId, useState } from "react";-import { toast } from "sonner";--export function SiteVisitTrackingSection() {- const switchId = useId();- const workspace = useWorkspace();- const { role, id, mutate } = workspace;- const siteVisitTrackingSettings = workspace.siteVisitTrackingSettings;- const trackedSitemaps = siteVisitTrackingSettings?.trackedSitemaps;- const siteDomainSlug = siteVisitTrackingSettings?.siteDomainSlug ?? "";- const [newSitemapUrl, setNewSitemapUrl] = useState("");- const [addingSitemap, setAddingSitemap] = useState(false);- const [refreshingSitemapUrl, setRefreshingSitemapUrl] = useState<- string | null- >(null);- const [deletingSitemapUrl, setDeletingSitemapUrl] = useState<string | null>(- null,- );-- const [enabled, setEnabled, { loading }] = useWorkspaceStore<boolean>(- "analyticsSettingsSiteVisitTrackingEnabled",- {- mutateOnSet: true,- },- );- const siteVisitTrackingEnabled = Boolean(enabled);-- const permissionsError = clientAccessCheck({- action: "workspaces.write",- role,- customPermissionDescription: "manage site visit tracking",- }).error;-- const trackedSitemapRows = Array.isArray(trackedSitemaps)- ? trackedSitemaps- .map((sitemap) => {- if (!sitemap?.url) {- return null;- }-- return {- url: sitemap.url,- lastCrawledAt: sitemap.lastCrawledAt- ? new Date(sitemap.lastCrawledAt)- : null,- lastUrlCount:- typeof sitemap.lastUrlCount === "number"- ? sitemap.lastUrlCount- : null,- };- })- .filter(- (- sitemap,- ): sitemap is {- url: string;- lastCrawledAt: Date | null;- lastUrlCount: number | null;- } => Boolean(sitemap),- )- : [];-- const sitemaps = siteVisitTrackingEnabled- ? trackedSitemapRows- : [- {- url: "dub.co/sitemap.xml",- lastCrawledAt: new Date(),- lastUrlCount: null,- },- ];-- const serializeSitemaps = (- input: {- url: string;- lastCrawledAt: Date | null;- lastUrlCount: number | null;- }[],- ) =>- input.map((sitemap) => ({- url: sitemap.url,- ...(sitemap.lastCrawledAt- ? { lastCrawledAt: sitemap.lastCrawledAt.toISOString() }- : {}),- ...(typeof sitemap.lastUrlCount === "number"- ? { lastUrlCount: sitemap.lastUrlCount }- : {}),- }));-- const normalizeSitemapUrl = (value: string) => {- const trimmed = value.trim();- if (!trimmed) {- return null;- }-- const withProtocol =- trimmed.startsWith("http://") || trimmed.startsWith("https://")- ? trimmed- : `https://${trimmed}`;-- try {- return new URL(withProtocol).toString();- } catch {- return null;- }- };-- const persistSiteVisitTrackingSettings = async (payload: {- trackedSitemaps: {- url: string;- lastCrawledAt?: string;- lastUrlCount?: number;- }[];- siteDomainSlug?: string | null;- }) => {- if (!id) {- toast.error("Workspace is still loading. Please try again.");- return false;- }-- const response = await fetch(`/api/workspaces/${id}`, {- method: "PATCH",- headers: {- "Content-Type": "application/json",- },- body: JSON.stringify({- siteVisitTrackingSettings: payload,- }),- });-- if (!response.ok) {- const { error } = await response.json();- toast.error(error?.message || "Failed to save settings.");- return false;- }-- await mutate();- return true;- };-- const setSiteDomainSlug = async (slug: string) => {- if (permissionsError) {- toast.error(permissionsError);- return;- }-- const ok = await persistSiteVisitTrackingSettings({- trackedSitemaps: serializeSitemaps(trackedSitemapRows),- siteDomainSlug: slug ? slug : null,- });-- if (ok) {- toast.success(slug ? "Domain saved." : "Domain cleared.");- }- };-- const addSitemap = async () => {- if (permissionsError) {- toast.error(permissionsError);- return;- }-- if (!id) {- toast.error("Workspace is still loading. Please try again.");- return;- }-- if (!siteDomainSlug) {- toast.error("Choose a domain for sitemap imports before adding sources.");- return;- }-- const normalizedSitemapUrl = normalizeSitemapUrl(newSitemapUrl);-- if (!normalizedSitemapUrl) {- toast.error("Enter a valid sitemap URL.");- return;- }-- const sitemapAlreadyExists = sitemaps.some(- (sitemap) => sitemap.url === normalizedSitemapUrl,- );-- if (sitemapAlreadyExists) {- toast.error("Sitemap already exists.");- return;- }-- if (sitemaps.length >= MAX_TRACKED_SITEMAPS_PER_WORKSPACE) {- toast.error(- `You can track up to ${MAX_TRACKED_SITEMAPS_PER_WORKSPACE} sitemaps per workspace.`,- );- return;- }-- setAddingSitemap(true);-- try {- const ok = await persistSiteVisitTrackingSettings({- trackedSitemaps: [- ...serializeSitemaps(sitemaps),- {- url: normalizedSitemapUrl,- },- ],- siteDomainSlug,- });-- if (ok) {- const importResponse = await fetch(- `/api/workspaces/${id}/sitemaps/import`,- {- method: "POST",- headers: {- "Content-Type": "application/json",- },- body: JSON.stringify({- sitemapUrl: normalizedSitemapUrl,- }),- },- );-- if (importResponse.ok) {- toast.success("Sitemap added and crawled.");- } else {- try {- const { error } = await importResponse.json();- toast.error(error?.message || "Sitemap added, but crawl failed.");- } catch {- toast.error("Sitemap added, but crawl failed.");- }- }-- setNewSitemapUrl("");- // Import updates crawl metadata on the server; revalidate so the row shows last crawled / URL count.- await mutate();- }- } catch {- toast.error("Network error, please try again or contact support.");- } finally {- setAddingSitemap(false);- }- };-- const refreshSitemap = async (sitemapUrl: string) => {- if (permissionsError) {- toast.error(permissionsError);- return;- }-- if (!id) {- toast.error("Workspace is still loading. Please try again.");- return;- }-- setRefreshingSitemapUrl(sitemapUrl);-- try {- const response = await fetch(`/api/workspaces/${id}/sitemaps/import`, {- method: "POST",- headers: {- "Content-Type": "application/json",- },- body: JSON.stringify({- sitemapUrl,- }),- });-- if (response.ok) {- toast.success("Sitemap refreshed.");- mutate();- } else {- const { error } = await response.json();- toast.error(error?.message || "Failed to refresh sitemap.");- }- } catch {- toast.error("Network error, please try again.");- } finally {- setRefreshingSitemapUrl(null);- }- };-- const deleteSitemap = async (sitemapUrl: string) => {- if (permissionsError) {- toast.error(permissionsError);- return;- }-- if (!id) {- toast.error("Workspace is still loading. Please try again.");- return;- }-- setDeletingSitemapUrl(sitemapUrl);-- const remainingSitemaps = sitemaps.filter(- (sitemap) => sitemap.url !== sitemapUrl,- );-- try {- const ok = await persistSiteVisitTrackingSettings({- trackedSitemaps: serializeSitemaps(remainingSitemaps),- });-- if (ok) {- toast.success("Sitemap deleted.");- }- } catch {- toast.error("Network error, please try again.");- } finally {- setDeletingSitemapUrl(null);- }- };-- return (- <div className="flex flex-1 flex-col rounded-lg border border-neutral-200 bg-neutral-50">- <div className="flex items-center justify-between gap-4 p-3">- <div className="flex min-w-0 items-center gap-4">- <div className="overflow-hidden">- <label- htmlFor={`${switchId}-switch`}- className="text-content-emphasis block text-sm font-semibold"- >- Site visit tracking- </label>- <p className="text-content-subtle text-sm font-medium">- For tracking site visits (organic visits from Google/SEO/AEO).- </p>- </div>- </div>-- <Switch- id={`${switchId}-switch`}- disabled={loading}- {...(permissionsError- ? {- disabledTooltip: permissionsError,- thumbIcon: (- <div className="flex size-full items-center justify-center">- <LockSmall className="size-[8px] text-black" />- </div>- ),- }- : {})}- checked={enabled || false}- trackDimensions="radix-state-checked:bg-black focus-visible:ring-black/20 w-7 h-4"- thumbDimensions="size-3"- thumbTranslate="translate-x-3"- fn={setEnabled}- />- </div>-- <motion.div- animate={{- height: enabled ? "auto" : 0,- overflow: "hidden",- }}- transition={{- duration: 0.15,- }}- initial={false}- >- <div className="flex flex-col gap-4 border-t border-neutral-200 p-3">- <div className="flex flex-col gap-2">- <div className="flex flex-col">- <label className="text-content-emphasis text-sm font-semibold">- Domain for sitemap imports- </label>- <p className="text-content-subtle text-xs font-medium">- This domain will be used for links we create when importing- pages from the sitemaps you add.- </p>- </div>-- <DomainSelector- selectedDomain={siteDomainSlug}- setSelectedDomain={(slug) => void setSiteDomainSlug(slug)}- disabled={Boolean(permissionsError)}- disabledTooltip={permissionsError || undefined}- />- </div>-- <div className="flex flex-col gap-2">- <div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">- <div className="flex items-center gap-1">- <h2 className="text-content-emphasis text-sm font-semibold">- Sitemaps- </h2>- <InfoTooltip content="Required for conversion tracking." />- </div>- <div className="flex w-full items-center gap-2 sm:w-auto">- {siteVisitTrackingEnabled && (- <input- type="text"- value={newSitemapUrl}- onChange={(e) => setNewSitemapUrl(e.target.value)}- placeholder="e.g. https://acme.com/sitemap.xml"- className="h-7 w-full rounded-lg border border-neutral-300 px-2.5 text-sm focus:border-neutral-500 focus:outline-none focus:ring-0 sm:w-[260px]"- />- )}- <Button- text="Add sitemap"- className="h-7 w-fit rounded-lg px-2.5 py-1 text-sm font-medium"- onClick={() =>- siteVisitTrackingEnabled- ? addSitemap()- : toast.info("Coming soon")- }- loading={addingSitemap}- disabled={- Boolean(permissionsError) ||- (siteVisitTrackingEnabled && !siteDomainSlug) ||- (siteVisitTrackingEnabled &&- trackedSitemapRows.length >=- MAX_TRACKED_SITEMAPS_PER_WORKSPACE)- }- disabledTooltip={- permissionsError ||- (siteVisitTrackingEnabled && !siteDomainSlug- ? "Choose a domain for imports first"- : undefined) ||- (siteVisitTrackingEnabled &&- trackedSitemapRows.length >=- MAX_TRACKED_SITEMAPS_PER_WORKSPACE- ? `Maximum ${MAX_TRACKED_SITEMAPS_PER_WORKSPACE} sitemaps per workspace`- : undefined)- }- />- </div>- </div>-- <div className="flex flex-col gap-2">- {siteVisitTrackingEnabled && sitemaps.length === 0 ? (- <div className="text-content-subtle rounded-xl border border-dashed border-neutral-300 bg-white p-3 text-sm">- No tracked sitemaps configured yet.- </div>- ) : (- sitemaps.map((sitemap) => (- <div- key={sitemap.url}- className="border-border-subtle flex items-center justify-between gap-4 rounded-xl border bg-white p-3"- >- <div className="flex min-w-0 items-center gap-2">- <div className="flex size-[28px] items-center justify-center rounded-md bg-neutral-100">- <Sitemap className="size-4 text-neutral-800" />- </div>- <div className="flex min-w-0 flex-col">- <span className="text-content-emphasis min-w-0 truncate text-sm font-semibold">- {sitemap.url}- </span>- <span className="text-content-subtle text-xs font-medium">- {sitemap.lastCrawledAt- ? `Last crawled ${formatDate(sitemap.lastCrawledAt)}`- : "Not crawled yet"}- {sitemap.lastUrlCount !== null- ? ` · ${sitemap.lastUrlCount} URLs found`- : ""}- </span>- </div>- </div>- {siteVisitTrackingEnabled && (- <SitemapRowMenu- onRefresh={() => refreshSitemap(sitemap.url)}- onDelete={() => deleteSitemap(sitemap.url)}- loading={- refreshingSitemapUrl === sitemap.url ||- deletingSitemapUrl === sitemap.url- }- />- )}- </div>- ))- )}- </div>- </div>- </div>- </motion.div>- </div>- );-}--function SitemapRowMenu({- onRefresh,- onDelete,- loading,-}: {- onRefresh: () => void;- onDelete: () => void;- loading: boolean;-}) {- const [openPopover, setOpenPopover] = useState(false);-- return (- <Popover- content={- <div className="w-full sm:w-48">- <div className="grid gap-px p-2">- <Button- text="Refresh source"- variant="outline"- onClick={() => {- setOpenPopover(false);- onRefresh();- }}- icon={<RefreshCw className="h-4 w-4" />}- className="h-9 justify-start px-2 font-medium"- />- </div>- <div className="border-t border-neutral-200" />- <div className="grid gap-px p-2">- <Button- text="Delete source"- variant="danger-outline"- onClick={() => {- setOpenPopover(false);- onDelete();- }}- icon={<Trash className="size-4" />}- className="h-9 justify-start px-2 font-medium"- />- </div>- </div>- }- align="end"- openPopover={openPopover}- setOpenPopover={setOpenPopover}- >- <Button- variant="outline"- className={cn(- "h-8 w-fit px-1.5 outline-none transition-all duration-200",- "border-transparent data-[state=open]:border-neutral-500 sm:group-hover/card:data-[state=closed]:border-neutral-200",- )}- icon={- loading ? (- <LoadingSpinner className="size-4 shrink-0" />- ) : (- <ThreeDots className="size-5 shrink-0" />- )- }- onClick={() => setOpenPopover(!openPopover)}- />- </Popover>- );-}diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/tracking/stack-picker.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/tracking/stack-picker.tsxnew file mode 100644index 0000000000..0fb29d3d68--- /dev/null+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/tracking/stack-picker.tsx@@ -0,0 +1,88 @@+"use client";++import { StackItem } from "@/ui/guides/integrations";+import { StackY3 } from "@dub/ui/icons";+import { cn } from "@dub/utils";++function StackItemIcon({+ icon: Icon,+ fullSize,+}: {+ icon: StackItem["icon"];+ fullSize?: boolean;+}) {+ if (fullSize) {+ return (+ <Icon+ className="size-5 shrink-0 overflow-hidden rounded"+ width="auto"+ height="100%"+ />+ );+ }++ return <Icon className="size-5 shrink-0" />;+}++export function StackSelectionStatus({ count }: { count: number }) {+ return (+ <p className="text-content-subtle flex items-center gap-1.5 text-xs font-medium">+ <StackY3 className="size-3.5 shrink-0" />+ {count} item{count === 1 ? "" : "s"} selected+ </p>+ );+}++export function StackPicker({+ items,+ value,+ onChange,+ disabled,+}: {+ items: StackItem[];+ value: string[];+ onChange: (value: string[]) => void;+ disabled?: boolean;+}) {+ const toggleItem = (id: string) => {+ if (disabled) {+ return;+ }++ onChange(+ value.includes(id) ? value.filter((item) => item !== id) : [...value, id],+ );+ };++ return (+ <div className="grid grid-cols-2 gap-2 sm:grid-cols-3">+ {items.map((item) => {+ const selected = value.includes(item.id);++ return (+ <button+ key={item.id}+ type="button"+ disabled={disabled}+ aria-pressed={selected}+ onClick={() => toggleItem(item.id)}+ className={cn(+ "relative flex items-center gap-2 rounded-lg border-2 bg-white px-3 py-2 text-left transition-[border-color,transform] duration-150 ease-out",+ "focus-visible:ring-2 focus-visible:ring-black/50 focus-visible:outline-none",+ "active:scale-[0.98]",+ selected ? "border-neutral-900" : "border-neutral-200",+ !disabled &&+ "[@media(hover:hover)_and_(pointer:fine)]:hover:border-neutral-900",+ disabled && "cursor-not-allowed opacity-50",+ )}+ >+ <StackItemIcon icon={item.icon} fullSize={item.iconProps?.fullSize} />+ <span className="min-w-0 flex-1 truncate text-sm font-medium text-neutral-800">+ {item.title}+ </span>+ </button>+ );+ })}+ </div>+ );+}diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/tracking/step.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/tracking/step.tsxdeleted file mode 100644index 50fbf87efa..0000000000--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/tracking/step.tsx+++ /dev/null@@ -1,120 +0,0 @@-"use client";--import { PropsWithChildren } from "react";--import { Button, Check2, ChevronRight } from "@dub/ui";-import { cn, isClickOnInteractiveChild } from "@dub/utils";-import { AnimatePresence, motion } from "motion/react";-import { ReactNode } from "react";--export type Step = "connect" | "lead" | "sale";--export type BaseStepProps = {- expanded?: boolean;- toggleExpanded: () => void;-};--export type StepProps = BaseStepProps & {- id: Step;- step: number;- title: string;- subtitle?: string;- complete?: boolean;- children?: ReactNode;- contentClassName?: string;-};--const Step = ({- step,- title,- subtitle,- complete,- expanded,- toggleExpanded,- children,- contentClassName,-}: PropsWithChildren<StepProps>) => {- return (- <div className="flex items-start gap-[22px] rounded-xl border border-neutral-200 bg-white p-5">- <StepNumber number={step} complete={complete} />-- <div className="flex min-w-0 grow flex-col">- <div- className="group/step-header flex cursor-pointer items-center justify-between gap-2"- onClick={(e) => {- if (!isClickOnInteractiveChild(e)) toggleExpanded();- }}- >- <div>- <div className="text-content-emphasis text-base font-semibold">- {title}- </div>- {subtitle && (- <div className="text-content-subtle text-sm font-medium">- {subtitle}- </div>- )}- </div>-- <Button- variant="plain"- className="hover:bg-bg-subtle group-hover/step-header:bg-bg-subtle group size-8 w-fit rounded-full border-none px-2"- data-state={expanded ? "open" : "closed"}- text={- <ChevronRight className="text-content-emphasis size-4 transition-transform duration-75 group-data-[state=open]:rotate-90" />- }- onClick={() => toggleExpanded()}- />- </div>-- <motion.div- initial={false}- animate={{ height: expanded ? "auto" : 0 }}- className="overflow-hidden"- >- <AnimatePresence initial={false}>- {expanded && (- <motion.div- className={cn(contentClassName, "pt-5")}- key="step-content"- initial={{ opacity: 0 }}- animate={{ opacity: 1 }}- exit={{ opacity: 0 }}- transition={{ duration: 0.2, ease: "easeInOut" }}- >- {children}- </motion.div>- )}- </AnimatePresence>- </motion.div>- </div>- </div>- );-};--const StepNumber = ({- number,- complete,-}: {- number: number;- complete?: boolean;-}) => {- return (- <div- className={cn(- "hidden size-[42px] shrink-0 items-center justify-center rounded-full sm:flex",- complete ? "bg-green-400" : "bg-neutral-100",- )}- >- {complete ? (- <Check2 className="size-4 text-green-800" />- ) : (- <span className="text-content-default text-base font-semibold">- {number}- </span>- )}- </div>- );-};--export default Step;diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/tracking/track-lead-guides-section.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/tracking/track-lead-guides-section.tsxdeleted file mode 100644index b25c5f8d1a..0000000000--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/tracking/track-lead-guides-section.tsx+++ /dev/null@@ -1,62 +0,0 @@-"use client";--import useGuide from "@/lib/swr/use-guide";-import { GuideActionButton } from "@/ui/guides/guide-action-button";-import { GuideSelector } from "@/ui/guides/guide-selector";-import { guides as allGuides } from "@/ui/guides/integrations";-import { GuidesMarkdown } from "@/ui/guides/markdown";-import { useSelectedGuide } from "./use-selected-guide";--export function TrackLeadsGuidesSection() {- const guides = allGuides.filter((guide) => guide.type === "track-lead");- const { selectedGuide, setSelectedGuide } = useSelectedGuide({ guides });-- const { loading, guideMarkdown } = useGuide(selectedGuide.key);-- let button: React.ReactNode;- let content: React.ReactNode;-- if (loading) {- content = (- <div className="space-y-4">- <div className="h-6 w-1/2 animate-pulse rounded bg-neutral-200" />- <div className="h-4 w-full animate-pulse rounded bg-neutral-100" />- <div className="h-4 w-5/6 animate-pulse rounded bg-neutral-100" />- <div className="h-4 w-2/3 animate-pulse rounded bg-neutral-100" />- </div>- );- button = (- <div className="h-8 w-24 animate-pulse rounded-md bg-neutral-200" />- );- } else if (guideMarkdown) {- content = <GuidesMarkdown>{guideMarkdown}</GuidesMarkdown>;- button = (- <GuideActionButton guide={selectedGuide} markdown={guideMarkdown} />- );- } else {- content = (- <div className="text-content-subtle flex size-full items-center justify-center text-sm">- Failed to load guide- </div>- );- }-- return (- <div className="overflow-hidden rounded-xl border border-neutral-200 bg-neutral-50">- <div className="flex items-center justify-between p-3">- <GuideSelector- value={selectedGuide}- onChange={setSelectedGuide}- guides={guides}- className="-my-1 -ml-1"- />-- {button}- </div>-- <div className="max-w-full rounded-t-xl border-t border-neutral-200 bg-white p-5">- <div className="mx-auto max-w-2xl">{content}</div>- </div>- </div>- );-}diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/tracking/track-sales-guides-section.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/tracking/track-sales-guides-section.tsxdeleted file mode 100644index a1dd8593cf..0000000000--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/tracking/track-sales-guides-section.tsx+++ /dev/null@@ -1,70 +0,0 @@-"use client";--import useGuide from "@/lib/swr/use-guide";-import { GuideActionButton } from "@/ui/guides/guide-action-button";-import { GuideSelector } from "@/ui/guides/guide-selector";-import { InstallStripeIntegrationButton } from "@/ui/guides/install-stripe-integration-button";-import { guides as allGuides } from "@/ui/guides/integrations";-import { GuidesMarkdown } from "@/ui/guides/markdown";-import { useSelectedGuide } from "./use-selected-guide";--export function TrackSalesGuidesSection() {- const guides = allGuides.filter((guide) => guide.type === "track-sale");- const { selectedGuide, setSelectedGuide } = useSelectedGuide({ guides });-- const { loading, guideMarkdown } = useGuide(selectedGuide.key);-- let button;- let content;-- if (loading) {- content = (- <div className="space-y-4">- <div className="h-6 w-1/2 animate-pulse rounded bg-neutral-200" />- <div className="h-4 w-full animate-pulse rounded bg-neutral-100" />- <div className="h-4 w-5/6 animate-pulse rounded bg-neutral-100" />- <div className="h-4 w-2/3 animate-pulse rounded bg-neutral-100" />- </div>- );- button = (- <div className="h-8 w-24 animate-pulse rounded-md bg-neutral-200" />- );- } else if (guideMarkdown) {- content = (- <div className="space-y-6">- {selectedGuide.key.startsWith("stripe") && (- <InstallStripeIntegrationButton />- )}- <GuidesMarkdown>{guideMarkdown}</GuidesMarkdown>- </div>- );- button = (- <GuideActionButton guide={selectedGuide} markdown={guideMarkdown} />- );- } else {- content = (- <div className="text-content-subtle flex size-full items-center justify-center text-sm">- Failed to load guide- </div>- );- }-- return (- <div className="overflow-hidden rounded-xl border border-neutral-200 bg-neutral-50">- <div className="flex items-center justify-between p-3">- <GuideSelector- value={selectedGuide}- onChange={setSelectedGuide}- guides={guides}- className="-my-1 -ml-1"- />-- {button}- </div>-- <div className="max-w-full rounded-t-xl border-t border-neutral-200 bg-white p-5">- <div className="mx-auto max-w-2xl">{content}</div>- </div>- </div>- );-}diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/tracking/tracking-form.ts b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/tracking/tracking-form.tsnew file mode 100644index 0000000000..cbdd0982ef--- /dev/null+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/tracking/tracking-form.ts@@ -0,0 +1,25 @@+export type TrackedSitemapDraft = {+ url: string;+ lastCrawledAt?: string;+ lastUrlCount?: number;+};++export type TrackingFormData = {+ stack: string[];+ allowedHostnames: string[];+ publishableKey: string | null;+ siteVisitTrackingEnabled: boolean;+ siteDomainSlug: string;+ trackedSitemaps: TrackedSitemapDraft[];+ outboundDomainTrackingEnabled: boolean;+};++export const emptyTrackingFormValues: TrackingFormData = {+ stack: [],+ allowedHostnames: [],+ publishableKey: null,+ siteVisitTrackingEnabled: false,+ siteDomainSlug: "",+ trackedSitemaps: [],+ outboundDomainTrackingEnabled: false,+};diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/tracking/tracking-settings-row.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/tracking/tracking-settings-row.tsxnew file mode 100644index 0000000000..20a8eb2c2c--- /dev/null+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/tracking/tracking-settings-row.tsx@@ -0,0 +1,45 @@+import { MarkdownDescription } from "@/ui/shared/markdown-description";+import { cn } from "@dub/utils";+import { PropsWithChildren, ReactNode } from "react";++export function TrackingSettingsRow({+ heading,+ description,+ leftExtra,+ leftExtraAlign = "start",+ align = "start",+ children,+ className,+}: PropsWithChildren<{+ heading: string;+ description: string;+ leftExtra?: ReactNode;+ leftExtraAlign?: "start" | "end";+ align?: "start" | "center";+ className?: string;+}>) {+ return (+ <div+ className={cn(+ "grid grid-cols-1 gap-4 px-5 py-6 sm:grid-cols-3 sm:gap-8",+ align === "center" && "sm:items-center",+ className,+ )}+ >+ <div className="flex h-full flex-col gap-1">+ <h3 className="text-content-emphasis text-sm font-semibold leading-none">+ {heading}+ </h3>+ <MarkdownDescription className="text-content-subtle text-sm">+ {description}+ </MarkdownDescription>+ {leftExtra && (+ <div className={cn(leftExtraAlign === "end" && "mt-auto pt-4")}>+ {leftExtra}+ </div>+ )}+ </div>+ <div className="min-w-0 sm:col-span-2">{children}</div>+ </div>+ );+}diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/tracking/use-selected-guide.ts b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/tracking/use-selected-guide.tsdeleted file mode 100644index ef541c3693..0000000000--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/tracking/use-selected-guide.ts+++ /dev/null@@ -1,30 +0,0 @@-import { IntegrationGuide } from "@/ui/guides/integrations";-import { useRouterStuff } from "@dub/ui";-import { useEffect, useState } from "react";--export function useSelectedGuide({ guides }: { guides: IntegrationGuide[] }) {- const { searchParams, queryParams } = useRouterStuff();- const paramGuide = searchParams.get("guide");-- if (guides.length === 0)- throw new Error("useSelectedGuide requires a non-empty guides array");-- const [selectedGuide, setSelectedGuide] = useState<IntegrationGuide>(- guides[0],- );-- useEffect(() => {- if (!paramGuide) return;-- const guide = guides.find((g) => g.key === paramGuide);- if (!guide) return;-- setSelectedGuide(guide);- }, [paramGuide, guides]);-- return {- selectedGuide,- setSelectedGuide: (guide: IntegrationGuide) =>- queryParams({ set: { guide: guide.key } }),- };-}diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/tracking/verify-install.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/tracking/verify-install.tsxindex e0311e32a7..73c24a3470 100644--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/tracking/verify-install.tsx+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/tracking/verify-install.tsx@@ -1,151 +1,75 @@+"use client";+import { verifyWorkspaceSetup } from "@/lib/actions/verify-workspace-setup";import useWorkspace from "@/lib/swr/use-workspace";-import { useWorkspaceStore } from "@/lib/swr/use-workspace-store";-import { Button, Plug2 } from "@dub/ui";-import { cn } from "@dub/utils";+import { Button, Combobox, Globe } from "@dub/ui";import { useAction } from "next-safe-action/hooks";-import Link from "next/link";-import { useMemo } from "react";+import { useMemo, useState } from "react";import { toast } from "sonner";-import { CompleteStepButton } from "./complete-step-button";--type VerifyStatus = "pending" | "success" | "error";--const VerifyInstallIcon = ({ status }: { status: VerifyStatus }) => {- return (- <div- className={cn(- "text-content-default flex size-10 items-center justify-center rounded-full",- status === "pending" && "border border-blue-200 bg-white",- status === "error" && "bg-red-400 text-red-900",- status === "success" && "bg-green-400 text-green-800",- )}- >- <Plug2 className="size-4" />- </div>- );-};-type VerificationResponse = {- verifiedAt: Date;- verifiedBy: { name: string; avatarUrl?: string };-};+const HOSTNAME_REQUIRED_MESSAGE =+ "A hostname is required in order to verify installation.";-const VerifyInstall = () => {+export function VerifyInstall({ hostnames }: { hostnames: string[] }) {const { id: workspaceId } = useWorkspace();+ const [selectedHostname, setSelectedHostname] = useState<string | null>(null);++ const hostnameOptions = useMemo(+ () =>+ hostnames.map((hostname) => ({+ value: hostname,+ label: hostname,+ icon: <Globe className="size-4 text-neutral-600" />,+ })),+ [hostnames],+ );- // const [verified, setVerified] = useState(false);-- const error: any | null = null;- const response: VerificationResponse | null = null;- // const response: VerificationResponse | null = {- // verifiedAt: new Date(),- // verifiedBy: { name: "Ian" },- // };+ const selectedOption =+ hostnameOptions.find((option) => option.value === selectedHostname) ?? null;const { executeAsync, isPending } = useAction(verifyWorkspaceSetup, {- async onSuccess(response) {- toast.success("Account created! Redirecting to dashboard...");-- // if (response?.ok) {- // } else {- // toast.error(- // "Failed to sign in with credentials. Please try again or contact support.",- // );- // }+ onSuccess() {+ toast.success("Installation verified.");},onError({ error }) {- toast.error(error.serverError);+ toast.error(error.serverError || "Failed to verify installation.");},});- const status: VerifyStatus = useMemo(() => {- if (error) return "error";- if (response) return "success";- return "pending";- }, [response, error]);-- const [complete, markComplete, { loading }] = useWorkspaceStore<boolean>(- "analyticsSettingsConnectionSetupComplete",- );-return (- <div- className={cn(- "flex flex-col gap-3 rounded-xl border px-8 py-6",- status === "pending" &&- "border-blue-200 bg-gradient-to-b from-blue-50 to-white",- status === "error" && "",- status === "success" && "",- )}- >- <form- onSubmit={(e) => {+ <div className="flex w-full flex-col gap-3">+ <Combobox+ options={hostnameOptions}+ selected={selectedOption}+ setSelected={(option) => setSelectedHostname(option?.value ?? null)}+ placeholder="Select hostname"+ searchPlaceholder="Search hostnames..."+ buttonProps={{+ className: "w-full",+ disabled: hostnames.length === 0,+ disabledTooltip:+ hostnames.length === 0 ? HOSTNAME_REQUIRED_MESSAGE : undefined,+ }}+ matchTriggerWidth+ />+ <Button+ text="Verify installation"+ className="h-9 w-full"+ loading={isPending}+ disabled={!workspaceId}+ onClick={() => {if (!workspaceId) {return;}- e.preventDefault();- executeAsync({ workspaceId });- }}- >- <div>- <div className="flex flex-col items-center">- <VerifyInstallIcon status={status} />-- <div className="text-content-emphasis mt-3 font-semibold">- {error- ? "Unable to connect"- : response- ? "Successfully connected!"- : "Verify your install"}- </div>-- <p className="text-content-emphasis text-sm font-medium">- {error ? (- <>- Try again. For more help, see our{" "}- <Link href={"/docs"} className="underline">- docs- </Link>{" "}- or{" "}- <Link href={"/contact"} className="underline">- contact support- </Link>- .- </>- ) : response ? (- "You’re connected and ready to track conversions"- ) : (- "Test your connection to Dub"- )}- </p>- </div>-- <div className="mt-4">- {status !== "success" && (- <Button- text={isPending ? "Verifying..." : "Verify"}- type="submit"- loading={isPending}- disabled={isPending}- variant={status === "pending" ? "success" : "primary"}- />- )}+ if (!selectedHostname) {+ toast.error(HOSTNAME_REQUIRED_MESSAGE);+ return;+ }- {status === "success" && !complete && (- <CompleteStepButton- onClick={() => {- markComplete(true);- }}- loading={loading}- />- )}- </div>- </div>- </form>+ void executeAsync({ workspaceId });+ }}+ /></div>);-};--export default VerifyInstall;+}diff --git a/apps/web/lib/zod/schemas/workspaces.ts b/apps/web/lib/zod/schemas/workspaces.tsindex f71e14f1c9..8d06af158f 100644--- a/apps/web/lib/zod/schemas/workspaces.ts+++ b/apps/web/lib/zod/schemas/workspaces.ts@@ -243,6 +243,7 @@ export const workspaceStoreKeys = z.enum(["analyticsSettingsConversionTrackingEnabled", // boolean"analyticsSettingsSiteVisitTrackingEnabled", // boolean"analyticsSettingsOutboundDomainTrackingEnabled", // boolean+ "analyticsSettingsSelectedStack", // string[]"analyticsSettingsConnectionSetupComplete", // boolean"analyticsSettingsLeadTrackingSetupComplete", // boolean"analyticsSettingsSaleTrackingSetupComplete", // booleandiff --git a/apps/web/ui/guides/integrations.ts b/apps/web/ui/guides/integrations.tsindex bad5247cd3..3307dc6cdd 100644--- a/apps/web/ui/guides/integrations.ts+++ b/apps/web/ui/guides/integrations.ts@@ -56,6 +56,142 @@ export const sections: {},];+export type StackItem = {+ id: string;+ title: string;+ icon: any;+ iconProps?: {+ fullSize?: boolean;+ };+ guideKeys: string[];+ type: IntegrationType;+};++export const stackItems: StackItem[] = [+ {+ id: "react",+ title: "React",+ icon: React,+ guideKeys: ["react"],+ type: "client-sdk",+ },+ {+ id: "gtm",+ title: "Google Tag Manager",+ icon: GoogleTagManager,+ guideKeys: ["gtm-client-sdk", "gtm-track-lead", "gtm-track-sale"],+ type: "client-sdk",+ },+ {+ id: "framer",+ title: "Framer",+ icon: Framer,+ guideKeys: ["framer"],+ type: "client-sdk",+ },+ {+ id: "wordpress",+ title: "WordPress",+ icon: Wordpress,+ guideKeys: ["wordpress"],+ type: "client-sdk",+ },+ {+ id: "webflow",+ title: "Webflow",+ icon: Webflow,+ guideKeys: ["webflow"],+ type: "client-sdk",+ },+ {+ id: "shopify",+ title: "Shopify",+ icon: Shopify,+ guideKeys: ["shopify"],+ type: "client-sdk",+ },+ {+ id: "stripe-checkout",+ title: "Stripe Checkout",+ icon: StripeIcon,+ iconProps: { fullSize: true },+ guideKeys: ["stripe-checkout"],+ type: "track-sale",+ },+ {+ id: "stripe-payment-links",+ title: "Stripe Payment Links",+ icon: StripeIcon,+ iconProps: { fullSize: true },+ guideKeys: ["stripe-payment-links"],+ type: "track-sale",+ },+ {+ id: "stripe-customers",+ title: "Stripe Customers",+ icon: StripeIcon,+ iconProps: { fullSize: true },+ guideKeys: ["stripe-customers"],+ type: "track-sale",+ },+ {+ id: "segment",+ title: "Segment",+ icon: Segment,+ guideKeys: ["segment-track-lead", "segment-track-sale"],+ type: "track-lead",+ },+ {+ id: "clerk",+ title: "Clerk",+ icon: Clerk,+ guideKeys: ["clerk"],+ type: "track-lead",+ },+ {+ id: "better-auth",+ title: "Better Auth",+ icon: BetterAuth,+ guideKeys: ["better-auth"],+ type: "track-lead",+ },+ {+ id: "next-auth",+ title: "NextAuth.js",+ icon: NextAuth,+ guideKeys: ["next-auth"],+ type: "track-lead",+ },+ {+ id: "supabase",+ title: "Supabase",+ icon: Supabase,+ guideKeys: ["supabase"],+ type: "track-lead",+ },+ {+ id: "auth0",+ title: "Auth0",+ icon: Auth0,+ guideKeys: ["auth0"],+ type: "track-lead",+ },+ {+ id: "appwrite",+ title: "Appwrite",+ icon: Appwrite,+ guideKeys: ["appwrite"],+ type: "track-lead",+ },+ {+ id: "custom",+ title: "Custom integration",+ icon: CodeEditor,+ guideKeys: ["manual-client-sdk", "manual-track-lead", "manual-track-sale"],+ type: "client-sdk",+ },+];+export const guides: IntegrationGuide[] = [// Client SDK{