The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
Add customer selector to customer pages
Steven Tey39b9f87d9d16
diff --git a/apps/web/app/(ee)/partners.dub.co/(dashboard)/programs/[programSlug]/(enrolled)/customers/[customerId]/page-client.tsx b/apps/web/app/(ee)/partners.dub.co/(dashboard)/programs/[programSlug]/(enrolled)/customers/[customerId]/page-client.tsxindex b351687c27..cf69cece0b 100644--- a/apps/web/app/(ee)/partners.dub.co/(dashboard)/programs/[programSlug]/(enrolled)/customers/[customerId]/page-client.tsx+++ b/apps/web/app/(ee)/partners.dub.co/(dashboard)/programs/[programSlug]/(enrolled)/customers/[customerId]/page-client.tsx@@ -7,6 +7,7 @@ import { PartnerEarningsResponse } from "@/lib/types";import { CustomerActivityList } from "@/ui/customers/customer-activity-list";import { CustomerDetailsColumn } from "@/ui/customers/customer-details-column";import { CustomerSalesTable } from "@/ui/customers/customer-sales-table";+import { PartnerCustomerSelector } from "@/ui/customers/partner-customer-selector";import { PageContent } from "@/ui/layout/page-content";import { PageWidthWrapper } from "@/ui/layout/page-width-wrapper";import { ProgramRewardList } from "@/ui/partners/program-reward-list";@@ -15,7 +16,13 @@ import { cn, fetcher, formatDate } from "@dub/utils";import { addMonths, isBefore } from "date-fns";import { AlertCircle } from "lucide-react";import Link from "next/link";-import { redirect, useParams } from "next/navigation";+import {+ redirect,+ useParams,+ usePathname,+ useRouter,+ useSearchParams,+} from "next/navigation";import { memo, useMemo } from "react";import useSWR from "swr";@@ -25,6 +32,9 @@ export function ProgramCustomerPageClient() {programSlug: string;customerId: string;}>();+ const router = useRouter();+ const pathname = usePathname();+ const searchParams = useSearchParams();const { data: customer, isLoading } = usePartnerCustomer({customerId,@@ -49,6 +59,12 @@ export function ProgramCustomerPageClient() {redirect(`/programs/${programSlug}`);}+ const switchToCustomer = (newCustomerId: string) => {+ if (customerId === newCustomerId) return;+ const url = `${pathname.replace(`/customers/${customerId}`, `/customers/${newCustomerId}`)}?${searchParams.toString()}`;+ router.push(url);+ };+return (<PageContenttitle={@@ -65,13 +81,11 @@ export function ProgramCustomerPageClient() {<User className="size-4" /></Link><ChevronRight className="text-content-muted size-2.5 shrink-0 [&_*]:stroke-2" />- <div>- {customer ? (- customer.name || customer.email- ) : (- <div className="h-6 w-32 animate-pulse rounded-md bg-neutral-200" />- )}- </div>+ <PartnerCustomerSelector+ variant="header"+ selectedCustomerId={customer?.id ?? null}+ setSelectedCustomerId={switchToCustomer}+ /></div>}>diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/customers/[customerId]/layout.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/customers/[customerId]/layout.tsxindex 903d08c1bc..0bf75b4174 100644--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/customers/[customerId]/layout.tsx+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/customers/[customerId]/layout.tsx@@ -5,6 +5,7 @@ import useWorkspace from "@/lib/swr/use-workspace";import { CustomerActivityResponse, CustomerEnriched } from "@/lib/types";import { CustomerActivityList } from "@/ui/customers/customer-activity-list";import { CustomerDetailsColumn } from "@/ui/customers/customer-details-column";+import { CustomerSelector } from "@/ui/customers/customer-selector";import { CustomerStats } from "@/ui/customers/customer-stats";import { CustomerTabs } from "@/ui/customers/customer-tabs";import { PageContent } from "@/ui/layout/page-content";@@ -13,13 +14,16 @@ import { Button } from "@dub/ui";import { ChevronRight, Users } from "@dub/ui/icons";import { fetcher } from "@dub/utils";import Link from "next/link";-import { redirect, useParams } from "next/navigation";+import { redirect, useParams, usePathname, useRouter, useSearchParams } from "next/navigation";import { ReactNode } from "react";import useSWR from "swr";export default function CustomerLayout({ children }: { children: ReactNode }) {const { id: workspaceId, slug: workspaceSlug } = useWorkspace();const { customerId } = useParams<{ customerId: string }>();+ const router = useRouter();+ const pathname = usePathname();+ const searchParams = useSearchParams();const { data: customer, error: customerError } =useCustomer<CustomerEnriched>({@@ -37,6 +41,12 @@ export default function CustomerLayout({ children }: { children: ReactNode }) {if (customerError && customerError.status === 404)redirect(`/${workspaceSlug}/customers`);+ const switchToCustomer = (newCustomerId: string) => {+ if (customerId === newCustomerId) return;+ const url = `${pathname.replace(`/customers/${customerId}`, `/customers/${newCustomerId}`)}?${searchParams.toString()}`;+ router.push(url);+ };+return (<PageContenttitle={@@ -50,13 +60,11 @@ export default function CustomerLayout({ children }: { children: ReactNode }) {<Users className="size-4" /></Link><ChevronRight className="text-content-muted size-2.5 shrink-0 [&_*]:stroke-2" />- <div>- {customer ? (- customer.name- ) : (- <div className="h-6 w-32 animate-pulse rounded-md bg-neutral-200" />- )}- </div>+ <CustomerSelector+ variant="header"+ selectedCustomerId={customer?.id ?? null}+ setSelectedCustomerId={switchToCustomer}+ /></div>}>diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/customers/[customerId]/layout.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/customers/[customerId]/layout.tsxindex 41c2eb1830..176e2b8345 100644--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/customers/[customerId]/layout.tsx+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/customers/[customerId]/layout.tsx@@ -6,6 +6,7 @@ import useWorkspace from "@/lib/swr/use-workspace";import { CustomerEnriched } from "@/lib/types";import { CustomerActivityList } from "@/ui/customers/customer-activity-list";import { CustomerDetailsColumn } from "@/ui/customers/customer-details-column";+import { CustomerSelector } from "@/ui/customers/customer-selector";import { CustomerStats } from "@/ui/customers/customer-stats";import { CustomerTabs } from "@/ui/customers/customer-tabs";import { PageContent } from "@/ui/layout/page-content";@@ -13,12 +14,25 @@ import { PageWidthWrapper } from "@/ui/layout/page-width-wrapper";import { Button } from "@dub/ui";import { ChevronRight, User } from "@dub/ui/icons";import Link from "next/link";-import { redirect, useParams } from "next/navigation";+import {+ redirect,+ useParams,+ usePathname,+ useRouter,+ useSearchParams,+} from "next/navigation";import { ReactNode } from "react";-export default function CustomerLayout({ children }: { children: ReactNode }) {+export default function ProgramCustomerLayout({+ children,+}: {+ children: ReactNode;+}) {const { slug: workspaceSlug } = useWorkspace();const { customerId } = useParams<{ customerId: string }>();+ const router = useRouter();+ const pathname = usePathname();+ const searchParams = useSearchParams();const { data: customer, error: customerError } =useCustomer<CustomerEnriched>({@@ -33,6 +47,12 @@ export default function CustomerLayout({ children }: { children: ReactNode }) {if (customerError && customerError.status === 404)redirect(`/${workspaceSlug}/program/customers`);+ const switchToCustomer = (newCustomerId: string) => {+ if (customerId === newCustomerId) return;+ const url = `${pathname.replace(`/customers/${customerId}`, `/customers/${newCustomerId}`)}?${searchParams.toString()}`;+ router.push(url);+ };+return (<PageContenttitle={@@ -46,13 +66,11 @@ export default function CustomerLayout({ children }: { children: ReactNode }) {<User className="size-4" /></Link><ChevronRight className="text-content-muted size-2.5 shrink-0 [&_*]:stroke-2" />- <div>- {customer ? (- customer.name- ) : (- <div className="h-6 w-32 animate-pulse rounded-md bg-neutral-200" />- )}- </div>+ <CustomerSelector+ variant="header"+ selectedCustomerId={customer?.id ?? null}+ setSelectedCustomerId={switchToCustomer}+ /></div>}>diff --git a/apps/web/ui/customers/customer-selector.tsx b/apps/web/ui/customers/customer-selector.tsxindex d12b5da19d..9603204261 100644--- a/apps/web/ui/customers/customer-selector.tsx+++ b/apps/web/ui/customers/customer-selector.tsx@@ -1,6 +1,6 @@import useCustomers from "@/lib/swr/use-customers";import { CUSTOMERS_MAX_PAGE_SIZE } from "@/lib/zod/schemas/customers";-import { Combobox } from "@dub/ui";+import { Combobox, ComboboxProps } from "@dub/ui";import { cn, OG_AVATAR_URL } from "@dub/utils";import { useEffect, useMemo, useState } from "react";import { useDebounce } from "use-debounce";@@ -9,14 +9,19 @@ import {type AddCustomerInitialData,} from "../modals/add-customer-modal";-interface CustomerSelectorProps {- selectedCustomerId: string;+type CustomerSelectorProps = {+ selectedCustomerId: string | null;setSelectedCustomerId: (customerId: string) => void;-}+ disabled?: boolean;+ variant?: "default" | "header";+} & Partial<ComboboxProps<false, any>>;export function CustomerSelector({selectedCustomerId,setSelectedCustomerId,+ disabled,+ variant = "default",+ ...rest}: CustomerSelectorProps) {const [search, setSearch] = useState("");const [useAsync, setUseAsync] = useState(false);@@ -114,42 +119,75 @@ export function CustomerSelector({<Comboboxoptions={loading ? undefined : customerOptions}setSelected={(option) => {+ if (!option) return;setSelectedCustomerId(option.value);}}selected={selectedOption}- icon={selectedCustomersLoading ? undefined : selectedOption?.icon}+ icon={+ variant === "header" && !selectedOption?.icon ? (+ <div className="size-5 flex-none animate-pulse rounded-full bg-neutral-200" />+ ) : (+ selectedOption?.icon+ )+ }caret={true}- placeholder={selectedCustomersLoading ? "" : "Select customer"}- searchPlaceholder="Search or create customer..."- onSearchChange={setSearch}- createLabel={(search) =>- `Create ${search ? `"${search}"` : "new customer"}`+ placeholder={variant === "header" ? "" : "Select customer"}+ searchPlaceholder={+ variant === "header" ? "Search customers..." : "Search or create customer..."}- onCreate={async (search) => {- const trimmed = search?.trim() ?? "";- setInitialData(- trimmed- ? trimmed.includes("@")- ? { email: trimmed }- : { name: trimmed }- : undefined,- );- setShowAddCustomerModal(true);- return true;- }}+ onSearchChange={setSearch}+ {...(variant !== "header" && {+ createLabel: (search: string) =>+ `Create ${search ? `"${search}"` : "new customer"}`,+ onCreate: async (search: string | undefined) => {+ const trimmed = search?.trim() ?? "";+ setInitialData(+ trimmed+ ? trimmed.includes("@")+ ? { email: trimmed }+ : { name: trimmed }+ : undefined,+ );+ setShowAddCustomerModal(true);+ return true;+ },+ })}shouldFilter={!useAsync}matchTriggerWidthopen={openPopover}onOpenChange={setOpenPopover}- buttonProps={{- className: cn(- "w-full justify-start border-neutral-300 px-3",- "data-[state=open]:ring-1 data-[state=open]:ring-neutral-500 data-[state=open]:border-neutral-500",- "focus:ring-1 focus:ring-neutral-500 focus:border-neutral-500 transition-none",- ),- }}+ {...(variant === "header"+ ? {+ popoverProps: {+ contentClassName: "min-w-[280px]",+ },+ labelProps: {+ className: "text-lg font-semibold leading-7 text-neutral-900",+ },+ iconProps: {+ className: "size-6",+ },+ buttonProps: {+ disabled,+ className:+ "w-full justify-start px-2 py-1 h-8 transition-none max-md:bg-bg-subtle hover:bg-bg-subtle md:hover:bg-subtle border-none rounded-lg",+ },+ }+ : {+ buttonProps: {+ disabled,+ className: cn(+ "w-full justify-start border-neutral-300 px-3",+ "data-[state=open]:ring-1 data-[state=open]:ring-neutral-500 data-[state=open]:border-neutral-500",+ "focus:ring-1 focus:ring-neutral-500 focus:border-neutral-500 transition-none",+ ),+ },+ })}+ {...rest}>- {selectedCustomersLoading ? (+ {variant === "header" && !selectedOption?.label ? (+ <div className="h-6 w-[120px] animate-pulse rounded bg-neutral-100" />+ ) : selectedCustomersLoading ? (<div className="my-0.5 h-5 w-1/3 animate-pulse rounded bg-neutral-200" />) : (selectedOption?.labeldiff --git a/apps/web/ui/customers/partner-customer-selector.tsx b/apps/web/ui/customers/partner-customer-selector.tsxnew file mode 100644index 0000000000..8895c86844--- /dev/null+++ b/apps/web/ui/customers/partner-customer-selector.tsx@@ -0,0 +1,133 @@+"use client";++import usePartnerCustomer from "@/lib/swr/use-partner-customer";+import { PartnerProfileCustomerProps } from "@/lib/types";+import { Combobox, ComboboxProps } from "@dub/ui";+import { fetcher, OG_AVATAR_URL } from "@dub/utils";+import { useParams } from "next/navigation";+import { useMemo, useState } from "react";+import { useDebounce } from "use-debounce";+import useSWR from "swr";++type PartnerCustomer = PartnerProfileCustomerProps & { name?: string | null };++type PartnerCustomerSelectorProps = {+ selectedCustomerId: string | null;+ setSelectedCustomerId: (customerId: string) => void;+ disabled?: boolean;+ variant?: "default" | "header";+} & Partial<ComboboxProps<false, any>>;++export function PartnerCustomerSelector({+ selectedCustomerId,+ setSelectedCustomerId,+ disabled,+ variant = "header",+ ...rest+}: PartnerCustomerSelectorProps) {+ const { programSlug } = useParams<{ programSlug: string }>();+ const [search, setSearch] = useState("");+ const [debouncedSearch] = useDebounce(search, 500);+ const [openPopover, setOpenPopover] = useState(false);++ const { data: customers, isLoading: loading } = useSWR<PartnerCustomer[]>(+ programSlug+ ? `/api/partner-profile/programs/${programSlug}/customers?pageSize=100${debouncedSearch ? `&search=${encodeURIComponent(debouncedSearch)}` : ""}`+ : null,+ fetcher,+ { keepPreviousData: true },+ );++ const { data: selectedCustomer, isLoading: selectedCustomerLoading } =+ usePartnerCustomer({+ customerId: selectedCustomerId ?? "",+ });++ const customerOptions = useMemo(() => {+ return customers?.map((customer) => ({+ value: customer.id,+ label: customer.name || customer.email ?? "",+ icon: (+ <img+ src={`${OG_AVATAR_URL}${customer.id}`}+ alt=""+ className="size-4 rounded-full"+ />+ ),+ }));+ }, [customers]);++ const selectedOption = useMemo(() => {+ if (!selectedCustomerId || !selectedCustomer) return null;+ return {+ value: selectedCustomer.id,+ label: selectedCustomer.name || selectedCustomer.email ?? "",+ icon: (+ <img+ src={`${OG_AVATAR_URL}${selectedCustomer.id}`}+ alt=""+ className="size-4 rounded-full"+ />+ ),+ };+ }, [selectedCustomerId, selectedCustomer]);++ return (+ <Combobox+ options={loading ? undefined : customerOptions}+ setSelected={(option) => {+ if (!option) return;+ setSelectedCustomerId(option.value);+ }}+ selected={selectedOption}+ icon={+ variant === "header" && !selectedOption?.icon ? (+ <div className="size-5 flex-none animate-pulse rounded-full bg-neutral-200" />+ ) : (+ selectedOption?.icon+ )+ }+ caret={true}+ placeholder={variant === "header" ? "" : "Select customer"}+ searchPlaceholder="Search customers..."+ onSearchChange={setSearch}+ shouldFilter={false}+ matchTriggerWidth+ open={openPopover}+ onOpenChange={setOpenPopover}+ {...(variant === "header"+ ? {+ popoverProps: {+ contentClassName: "min-w-[280px]",+ },+ labelProps: {+ className: "text-lg font-semibold leading-7 text-neutral-900",+ },+ iconProps: {+ className: "size-6",+ },+ buttonProps: {+ disabled,+ className:+ "w-full justify-start px-2 py-1 h-8 transition-none max-md:bg-bg-subtle hover:bg-bg-subtle md:hover:bg-subtle border-none rounded-lg",+ },+ }+ : {+ buttonProps: {+ disabled,+ className:+ "w-full justify-start border-neutral-300 px-3 rounded-lg",+ },+ })}+ {...rest}+ >+ {variant === "header" && !selectedOption?.label ? (+ <div className="h-6 w-[120px] animate-pulse rounded bg-neutral-100" />+ ) : selectedCustomerLoading && selectedCustomerId ? (+ <div className="h-6 w-[120px] animate-pulse rounded bg-neutral-100" />+ ) : (+ selectedOption?.label+ )}+ </Combobox>+ );+}