Skip to content

armgit / dub

Public Imported from GitHub
0

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

Big filtering refactor + implementation

Tim Wilson0bdae097dcc1
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/analytics/analytics-chart.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/analytics/analytics-chart.tsx
index da8a181421..37fe5c7d9d 100644
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/analytics/analytics-chart.tsx
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/analytics/analytics-chart.tsx
@@ -1,6 +1,5 @@
-import { DUB_PARTNERS_ANALYTICS_INTERVAL } from "@/lib/analytics/constants";
import { formatDateTooltip } from "@/lib/analytics/format-date-tooltip";
-import useWorkspace from "@/lib/swr/use-workspace";
+import { editQueryString } from "@/lib/analytics/utils";
import { Combobox, useRouterStuff } from "@dub/ui";
import {
Areas,
@@ -24,12 +23,13 @@ const chartOptions = [
];
export function AnalyticsChart() {
- const { id: workspaceId, defaultProgramId } = useWorkspace();
const id = useId();
const { queryParams } = useRouterStuff();
- const { start, end, interval, event } = useContext(ProgramAnalyticsContext);
+ const { start, end, interval, event, queryString } = useContext(
+ ProgramAnalyticsContext,
+ );
const { data, error } = useSWR<
{
@@ -40,17 +40,9 @@ export function AnalyticsChart() {
saleAmount: number;
}[]
>(
- `/api/analytics?${new URLSearchParams({
- workspaceId: workspaceId!,
- programId: defaultProgramId!,
+ `/api/analytics?${editQueryString(queryString ?? "", {
event: "composite",
groupBy: "timeseries",
- ...(start && end
- ? {
- start: new Date(start).toISOString(),
- end: new Date(end).toISOString(),
- }
- : { interval: interval ?? DUB_PARTNERS_ANALYTICS_INTERVAL }),
})}`,
fetcher,
);
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/analytics/page-client.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/analytics/page-client.tsx
index 7e92540aa4..22de4cdec6 100644
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/analytics/page-client.tsx
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/analytics/page-client.tsx
@@ -2,8 +2,13 @@
import { DUB_PARTNERS_ANALYTICS_INTERVAL } from "@/lib/analytics/constants";
import { IntervalOptions } from "@/lib/analytics/types";
+import { editQueryString } from "@/lib/analytics/utils";
+import useWorkspace from "@/lib/swr/use-workspace";
+import { useAnalyticsFilters } from "@/ui/analytics/use-analytics-filters";
+import { useAnalyticsQuery } from "@/ui/analytics/use-analytics-query";
import SimpleDateRangePicker from "@/ui/shared/simple-date-range-picker";
-import { useRouterStuff } from "@dub/ui";
+import { Filter, useRouterStuff } from "@dub/ui";
+import { cn } from "@dub/utils";
import { createContext } from "react";
import { AnalyticsChart } from "./analytics-chart";
@@ -12,12 +17,14 @@ type ProgramAnalyticsContextType = {
end?: string;
interval?: IntervalOptions;
event: "sales" | "leads" | "clicks";
+ queryString?: string;
};
export const ProgramAnalyticsContext =
createContext<ProgramAnalyticsContextType>({ event: "sales" });
export function ProgramAnalyticsPageClient() {
+ const { defaultProgramId } = useWorkspace();
const { searchParamsObj } = useRouterStuff();
const {
@@ -27,15 +34,70 @@ export function ProgramAnalyticsPageClient() {
event = "sales",
} = searchParamsObj as Partial<ProgramAnalyticsContextType>;
+ const queryString = editQueryString(
+ useAnalyticsQuery({
+ defaultInterval: DUB_PARTNERS_ANALYTICS_INTERVAL,
+ }).queryString,
+ {
+ programId: defaultProgramId!,
+ },
+ );
+
+ const {
+ filters,
+ activeFilters,
+ setSearch,
+ setSelectedFilter,
+ onSelect,
+ onRemove,
+ onRemoveAll,
+ onOpenFilter,
+ streaming,
+ activeFiltersWithStreaming,
+ } = useAnalyticsFilters({
+ context: {
+ baseApiPath: "/api/analytics",
+ queryString,
+ selectedTab: event,
+ },
+ });
+
return (
<div className="flex flex-col gap-6">
- <div className="flex items-center gap-2">
- <SimpleDateRangePicker align="start" className="w-fit" />
+ <div>
+ <div className="flex items-center gap-2">
+ <Filter.Select
+ className="w-full md:w-fit"
+ filters={filters}
+ activeFilters={activeFilters}
+ onSearchChange={setSearch}
+ onSelectedFilterChange={setSelectedFilter}
+ onSelect={onSelect}
+ onRemove={onRemove}
+ onOpenFilter={onOpenFilter}
+ askAI
+ />
+ <SimpleDateRangePicker align="start" className="w-fit" />
+ </div>
+ <div>
+ <div
+ className={cn(
+ "transition-[height] duration-[300ms]",
+ streaming || activeFilters.length ? "h-3" : "h-0",
+ )}
+ />
+ <Filter.List
+ filters={filters}
+ activeFilters={activeFiltersWithStreaming}
+ onRemove={onRemove}
+ onRemoveAll={onRemoveAll}
+ />
+ </div>
</div>
<div className="border-border-subtle rounded-2xl border">
<div className="p-6">
<ProgramAnalyticsContext.Provider
- value={{ start, end, interval, event }}
+ value={{ start, end, interval, event, queryString }}
>
<AnalyticsChart />
</ProgramAnalyticsContext.Provider>
diff --git a/apps/web/ui/analytics/analytics-provider.tsx b/apps/web/ui/analytics/analytics-provider.tsx
index 5d3d8e8d72..a608ad6352 100644
--- a/apps/web/ui/analytics/analytics-provider.tsx
+++ b/apps/web/ui/analytics/analytics-provider.tsx
@@ -5,8 +5,6 @@ import {
ANALYTICS_VIEWS,
DUB_LINKS_ANALYTICS_INTERVAL,
DUB_PARTNERS_ANALYTICS_INTERVAL,
- EVENT_TYPES,
- VALID_ANALYTICS_FILTERS,
} from "@/lib/analytics/constants";
import {
AnalyticsResponseOptions,
@@ -15,13 +13,11 @@ import {
EventType,
} from "@/lib/analytics/types";
import { editQueryString } from "@/lib/analytics/utils";
-import { combineTagIds } from "@/lib/api/tags/combine-tag-ids";
import usePartnerProfile from "@/lib/swr/use-partner-profile";
import useWorkspace from "@/lib/swr/use-workspace";
import { PlanProps } from "@/lib/types";
import { useLocalStorage } from "@dub/ui";
import { fetcher } from "@dub/utils";
-import { endOfDay, startOfDay, subDays } from "date-fns";
import { useParams, usePathname, useSearchParams } from "next/navigation";
import {
createContext,
@@ -34,6 +30,7 @@ import { toast } from "sonner";
import useSWR from "swr";
import { defaultConfig } from "swr/_internal";
import { UpgradeRequiredToast } from "../shared/upgrade-required-toast";
+import { useAnalyticsQuery } from "./use-analytics-query";
export interface AnalyticsDashboardProps {
domain: string;
@@ -94,7 +91,7 @@ export default function AnalyticsProvider({
}>) {
const searchParams = useSearchParams();
const pathname = usePathname();
- const { id: workspaceId, slug, domains } = useWorkspace();
+ const { slug, domains } = useWorkspace();
const [requiresUpgrade, setRequiresUpgrade] = useState(false);
@@ -107,53 +104,11 @@ export default function AnalyticsProvider({
const partnerPage = partner?.id && programSlug ? true : false;
const domainSlug = searchParams?.get("domain");
- // key can be a query param (stats pages in app) or passed as a staticKey (shared analytics dashboards)
- const key = searchParams?.get("key") || dashboardProps?.key;
// Show conversion tabs/data for all dashboards except shared (unless explicitly set)
const showConversions =
!dashboardProps || dashboardProps?.showConversions ? true : false;
- const tagIds = combineTagIds({
- tagId: searchParams?.get("tagId"),
- tagIds: searchParams?.get("tagIds")?.split(","),
- })?.join(",");
-
- const folderId = searchParams?.get("folderId") ?? undefined;
-
- const customerId = searchParams?.get("customerId") ?? undefined;
-
- // Default to last 24 hours
- const { start, end } = useMemo(() => {
- const hasRange = searchParams?.has("start") && searchParams?.has("end");
-
- return {
- start: hasRange
- ? startOfDay(
- new Date(searchParams?.get("start") || subDays(new Date(), 1)),
- )
- : undefined,
-
- end: hasRange
- ? endOfDay(new Date(searchParams?.get("end") || new Date()))
- : undefined,
- };
- }, [searchParams?.get("start"), searchParams?.get("end")]);
-
- const defaultInterval = partnerPage
- ? DUB_PARTNERS_ANALYTICS_INTERVAL
- : DUB_LINKS_ANALYTICS_INTERVAL;
-
- // Only set interval if start and end are not provided
- const interval =
- start || end ? undefined : searchParams?.get("interval") ?? defaultInterval;
-
- const selectedTab: EventType = useMemo(() => {
- const event = searchParams.get("event");
-
- return EVENT_TYPES.find((t) => t === event) ?? "clicks";
- }, [searchParams.get("event")]);
-
const [persistedSaleUnit, setPersistedSaleUnit] =
useLocalStorage<AnalyticsSaleUnit>(`analytics-sale-unit`, "saleAmount");
@@ -217,7 +172,7 @@ export default function AnalyticsProvider({
return {
basePath: "",
baseApiPath: "",
- domain: "",
+ domain: "", // TODO [refactor]
};
}
}, [
@@ -229,68 +184,33 @@ export default function AnalyticsProvider({
partner?.id,
programSlug,
domainSlug,
- key,
- selectedTab,
]);
- /*
- If explicitly set, use the value
- If not set:
- - Show root domain links if:
+ const { queryString, key, start, end, interval, tagIds, selectedTab } =
+ useAnalyticsQuery({
+ domain: domain ?? undefined,
+ defaultKey: dashboardProps?.key,
+ defaultInterval: partnerPage
+ ? DUB_PARTNERS_ANALYTICS_INTERVAL
+ : DUB_LINKS_ANALYTICS_INTERVAL,
+
+ /*
+ If not explicitly set, show root domain links if:
- it's filtered by a link, or
- the workspace has more than 50 domains
- is admin page
- is filtered by a folder or tag
- - Otherwise, hide root domain links
- */
- const root = searchParams.get("root")
- ? searchParams.get("root") === "true"
- : (domain && key) ||
+ Otherwise, hide root domain links
+ */
+ defaultRoot: ({ key, folderId, tagIds }) =>
+ (domain && key) ||
(domains && domains.length > 50) ||
adminPage ||
folderId ||
tagIds
- ? undefined
- : "false";
-
- const queryString = useMemo(() => {
- const availableFilterParams = VALID_ANALYTICS_FILTERS.reduce(
- (acc, filter) => ({
- ...acc,
- ...(searchParams?.get(filter) && {
- [filter]: searchParams.get(filter),
- }),
- }),
- {},
- );
- return new URLSearchParams({
- ...availableFilterParams,
- ...(workspaceId && { workspaceId }),
- ...(domain && { domain }),
- ...(key && { key }),
- ...(start &&
- end && { start: start.toISOString(), end: end.toISOString() }),
- ...(interval && { interval }),
- ...(tagIds && { tagIds }),
- ...(root && { root: root.toString() }),
- event: selectedTab,
- ...(folderId && { folderId }),
- ...(customerId && { customerId }),
- timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
- }).toString();
- }, [
- workspaceId,
- domain,
- key,
- searchParams,
- start,
- end,
- tagIds,
- root,
- selectedTab,
- folderId,
- customerId,
- ]);
+ ? true
+ : false,
+ });
// Reset requiresUpgrade when query changes
useEffect(() => setRequiresUpgrade(false), [queryString]);
diff --git a/apps/web/ui/analytics/toggle.tsx b/apps/web/ui/analytics/toggle.tsx
index d84e1cece1..1641e9b7f5 100644
--- a/apps/web/ui/analytics/toggle.tsx
+++ b/apps/web/ui/analytics/toggle.tsx
@@ -1,30 +1,10 @@
-import { generateFilters } from "@/lib/ai/generate-filters";
import {
DUB_LINKS_ANALYTICS_INTERVAL,
INTERVAL_DISPLAYS,
- TRIGGER_DISPLAY,
- VALID_ANALYTICS_FILTERS,
} from "@/lib/analytics/constants";
import { validDateRangeForPlan } from "@/lib/analytics/utils";
import { getStartEndDates } from "@/lib/analytics/utils/get-start-end-dates";
-import { getPlanCapabilities } from "@/lib/plan-capabilities";
-import useCustomer from "@/lib/swr/use-customer";
-import useCustomers from "@/lib/swr/use-customers";
-import useCustomersCount from "@/lib/swr/use-customers-count";
-import useDomains from "@/lib/swr/use-domains";
-import useDomainsCount from "@/lib/swr/use-domains-count";
-import useFolder from "@/lib/swr/use-folder";
-import useFolders from "@/lib/swr/use-folders";
-import useFoldersCount from "@/lib/swr/use-folders-count";
-import usePartnerCustomer from "@/lib/swr/use-partner-customer";
-import useTags from "@/lib/swr/use-tags";
-import useTagsCount from "@/lib/swr/use-tags-count";
import useWorkspace from "@/lib/swr/use-workspace";
-import { LinkProps } from "@/lib/types";
-import { CUSTOMERS_MAX_PAGE_SIZE } from "@/lib/zod/schemas/customers";
-import { DOMAINS_MAX_PAGE_SIZE } from "@/lib/zod/schemas/domains";
-import { FOLDERS_MAX_PAGE_SIZE } from "@/lib/zod/schemas/folders";
-import { TAGS_MAX_PAGE_SIZE } from "@/lib/zod/schemas/tags";
import {
BlurImage,
Button,
@@ -32,73 +12,30 @@ import {
DateRangePicker,
ExpandingArrow,
Filter,
- LinkLogo,
- Sliders,
SquareLayoutGrid6,
TooltipContent,
useMediaQuery,
useRouterStuff,
useScroll,
- UTM_PARAMETERS,
} from "@dub/ui";
-import {
- Cube,
- CursorRays,
- FlagWavy,
- Folder,
- Globe2,
- Hyperlink,
- LinkBroken,
- LocationPin,
- Magic,
- MapPosition,
- MobilePhone,
- OfficeBuilding,
- QRCode,
- ReferredVia,
- Tag,
- User,
- Window,
-} from "@dub/ui/icons";
import {
APP_DOMAIN,
- capitalize,
cn,
- CONTINENTS,
- COUNTRIES,
DUB_DEMO_LINKS,
DUB_LOGO,
getApexDomain,
getNextPlan,
GOOGLE_FAVICON_URL,
linkConstructor,
- nFormatter,
- OG_AVATAR_URL,
- REGIONS,
} from "@dub/utils";
-import { readStreamableValue } from "ai/rsc";
import Link from "next/link";
import { useParams } from "next/navigation";
-import posthog from "posthog-js";
-import {
- ComponentProps,
- useCallback,
- useContext,
- useMemo,
- useState,
-} from "react";
-import { useDebounce } from "use-debounce";
-import { FolderIcon } from "../folders/folder-icon";
-import { LinkIcon } from "../links/link-icon";
-import TagBadge from "../links/tag-badge";
+import { useContext } from "react";
import AnalyticsOptions from "./analytics-options";
import { AnalyticsContext } from "./analytics-provider";
-import ContinentIcon from "./continent-icon";
-import DeviceIcon from "./device-icon";
import EventsOptions from "./events/events-options";
-import RefererIcon from "./referer-icon";
import { ShareButton } from "./share-button";
-import { useAnalyticsFilterOption } from "./utils";
+import { useAnalyticsFilters } from "./use-analytics-filters";
export default function Toggle({
page = "analytics",
@@ -108,10 +45,9 @@ export default function Toggle({
const { slug, programSlug } = useParams();
const { plan, createdAt } = useWorkspace();
- const { queryParams, searchParamsObj, getQueryString } = useRouterStuff();
+ const { queryParams, getQueryString } = useRouterStuff();
const {
- selectedTab,
domain,
key,
url,
@@ -125,681 +61,20 @@ export default function Toggle({
const scrolled = useScroll(120);
- // Determine whether filters should be fetched async
- const { data: tagsCount } = useTagsCount();
- const { data: domainsCount } = useDomainsCount({ ignoreParams: true });
- const { data: foldersCount } = useFoldersCount();
- const { data: customersCount } = useCustomersCount();
- const tagsAsync = Boolean(tagsCount && tagsCount > TAGS_MAX_PAGE_SIZE);
- const domainsAsync = domainsCount && domainsCount > DOMAINS_MAX_PAGE_SIZE;
- const foldersAsync = foldersCount && foldersCount > FOLDERS_MAX_PAGE_SIZE;
- const customersAsync =
- customersCount && customersCount > CUSTOMERS_MAX_PAGE_SIZE;
-
- const [selectedFilter, setSelectedFilter] = useState<string | null>(null);
- const [search, setSearch] = useState("");
- const [debouncedSearch] = useDebounce(search, 500);
-
- const { tags, loading: loadingTags } = useTags({
- query: {
- search: tagsAsync && selectedFilter === "tagIds" ? debouncedSearch : "",
- },
- });
- const { folders, loading: loadingFolders } = useFolders({
- query: {
- search:
- foldersAsync && selectedFilter === "folderId" ? debouncedSearch : "",
- },
- });
- const { customers } = useCustomers({
- query: {
- search:
- customersAsync && selectedFilter === "customerId"
- ? debouncedSearch
- : "",
- },
- });
- const { canManageCustomers } = getPlanCapabilities(plan);
+ const { isMobile } = useMediaQuery();
const {
- allDomains: domains,
- primaryDomain,
- loading: loadingDomains,
- } = useDomains({
- ignoreParams: true,
- opts: {
- search:
- domainsAsync && selectedFilter === "domain" ? debouncedSearch : "",
- },
- });
-
- const selectedTagIds = useMemo(
- () => searchParamsObj.tagIds?.split(",")?.filter(Boolean) ?? [],
- [searchParamsObj.tagIds],
- );
-
- const { tags: selectedTags } = useTags({
- query: { ids: selectedTagIds },
- enabled: tagsAsync,
- });
-
- const selectedFolderId = searchParamsObj.folderId;
-
- const { folder: selectedFolder } = useFolder({
- folderId: selectedFolderId,
- });
-
- const selectedCustomerId = searchParamsObj.customerId;
-
- const { data: selectedCustomerWorkspace } = useCustomer({
- customerId: selectedCustomerId,
- });
- const { data: selectedCustomerPartner } = usePartnerCustomer({
- customerId: selectedCustomerId,
- });
-
- const selectedCustomer = selectedCustomerPartner || selectedCustomerWorkspace;
-
- const [requestedFilters, setRequestedFilters] = useState<string[]>([]);
-
- const activeFilters = useMemo(() => {
- const { domain, key, root, folderId, ...params } = searchParamsObj;
-
- // Handle special cases first
- const filters = [
- // Handle domain/key special case
- ...(domain && !key ? [{ key: "domain", value: domain }] : []),
- ...(domain && key
- ? [
- {
- key: "link",
- value: linkConstructor({ domain, key, pretty: true }),
- },
- ]
- : []),
- // Handle tagIds special case
- ...(selectedTagIds.length > 0
- ? [{ key: "tagIds", value: selectedTagIds }]
- : []),
- // Handle root special case - convert string to boolean
- ...(root ? [{ key: "root", value: root === "true" }] : []),
- // Handle folderId special case
- ...(folderId ? [{ key: "folderId", value: folderId }] : []),
- // Handle customerId special case
- ...(selectedCustomer
- ? [
- {
- key: "customerId",
- value:
- selectedCustomer.email ||
- selectedCustomer["name"] ||
- selectedCustomer["externalId"],
- },
- ]
- : []),
- ];
-
- // Handle all other filters dynamically
- VALID_ANALYTICS_FILTERS.forEach((filter) => {
- // Skip special cases we handled above
- if (
- ["domain", "key", "tagId", "tagIds", "root", "customerId"].includes(
- filter,
- )
- )
- return;
- // also skip date range filters and qr
- if (["interval", "start", "end", "qr"].includes(filter)) return;
-
- const value = params[filter];
- if (value) {
- filters.push({ key: filter, value });
- }
- });
-
- return filters;
- }, [
- searchParamsObj,
- selectedTagIds,
- partnerPage,
- selectedCustomerId,
- selectedCustomer,
- ]);
-
- const isRequested = useCallback(
- (key: string) =>
- requestedFilters.includes(key) ||
- activeFilters.some((af) => af.key === key),
- [requestedFilters, activeFilters],
- );
-
- const { data: links } = useAnalyticsFilterOption("top_links", {
- cacheOnly: !isRequested("link"),
- });
- const { data: countries } = useAnalyticsFilterOption("countries", {
- cacheOnly: !isRequested("country"),
- });
- const { data: regions } = useAnalyticsFilterOption("regions", {
- cacheOnly: !isRequested("region"),
- });
- const { data: cities } = useAnalyticsFilterOption("cities", {
- cacheOnly: !isRequested("city"),
- });
- const { data: continents } = useAnalyticsFilterOption("continents", {
- cacheOnly: !isRequested("continent"),
- });
- const { data: devices } = useAnalyticsFilterOption("devices", {
- cacheOnly: !isRequested("device"),
- });
- const { data: browsers } = useAnalyticsFilterOption("browsers", {
- cacheOnly: !isRequested("browser"),
- });
- const { data: os } = useAnalyticsFilterOption("os", {
- cacheOnly: !isRequested("os"),
- });
- const { data: triggers } = useAnalyticsFilterOption("triggers", {
- cacheOnly: !isRequested("trigger"),
- });
- const { data: referers } = useAnalyticsFilterOption("referers", {
- cacheOnly: !isRequested("referer"),
- });
- const { data: refererUrls } = useAnalyticsFilterOption("referer_urls", {
- cacheOnly: !isRequested("refererUrl"),
- });
- const { data: urls } = useAnalyticsFilterOption("top_urls", {
- cacheOnly: !isRequested("url"),
- });
- const { data: utmSources } = useAnalyticsFilterOption("utm_sources", {
- cacheOnly: !isRequested("utm_source"),
- });
- const { data: utmMediums } = useAnalyticsFilterOption("utm_mediums", {
- cacheOnly: !isRequested("utm_medium"),
- });
- const { data: utmCampaigns } = useAnalyticsFilterOption("utm_campaigns", {
- cacheOnly: !isRequested("utm_campaign"),
- });
- const { data: utmTerms } = useAnalyticsFilterOption("utm_terms", {
- cacheOnly: !isRequested("utm_term"),
- });
- const { data: utmContents } = useAnalyticsFilterOption("utm_contents", {
- cacheOnly: !isRequested("utm_content"),
- });
- const utmData = {
- utm_source: utmSources,
- utm_medium: utmMediums,
- utm_campaign: utmCampaigns,
- utm_term: utmTerms,
- utm_content: utmContents,
- };
-
- // Some suggestions will only appear if previously requested (see isRequested above)
- const aiFilterSuggestions = useMemo(
- () => [
- ...(dashboardProps || partnerPage
- ? []
- : [
- {
- value: `Clicks on ${primaryDomain} domain this year`,
- icon: Globe2,
- },
- ]),
- {
- value: "Mobile users, US only",
- icon: MobilePhone,
- },
- {
- value: "Tokyo, Chrome users",
- icon: OfficeBuilding,
- },
- {
- value: "Safari, Singapore, last month",
- icon: FlagWavy,
- },
- {
- value: "QR scans last quarter",
- icon: QRCode,
- },
- ],
- [primaryDomain, dashboardProps, partnerPage],
- );
-
- const [streaming, setStreaming] = useState<boolean>(false);
-
- const LinkFilterItem = {
- key: "link",
- icon: Hyperlink,
- label: "Link",
- getOptionIcon: (value, props) => {
- const url = props.option?.data?.url;
- const [domain, key] = value.split("/");
-
- return <LinkIcon url={url} domain={domain} linkKey={key} />;
- },
- options:
- links?.map(
- ({ domain, key, url, count }: LinkProps & { count?: number }) => ({
- value: linkConstructor({ domain, key, pretty: true }),
- label: linkConstructor({ domain, key, pretty: true }),
- right: nFormatter(count, { full: true }),
- data: { url },
- permalink:
- slug && !partnerPage
- ? `/${slug}/links/${linkConstructor({ domain, key, pretty: true })}`
- : undefined,
- }),
- ) ?? null,
- };
-
- const CustomerFilterItem = {
- key: "customerId",
- icon: User,
- label: "Customer",
- hideInFilterDropdown: partnerPage,
- shouldFilter: !customersAsync,
- getOptionIcon: () => {
- return selectedCustomer ? (
- <img
- src={
- selectedCustomer["avatar"] ||
- `${OG_AVATAR_URL}${selectedCustomer.id}`
- }
- alt={`${selectedCustomer.email} avatar`}
- className="size-4 rounded-full"
- />
- ) : null;
- },
- getOptionPermalink: () => {
- return programSlug
- ? `/programs/${programSlug}/customers/${selectedCustomerId}`
- : slug
- ? `/${slug}/customers/${selectedCustomerId}`
- : null;
- },
- options:
- customers?.map(({ id, email, name, avatar }) => {
- return {
- value: id,
- label: email ?? name,
- icon: (
- <img
- src={avatar || `${OG_AVATAR_URL}${id}`}
- alt={`${email} avatar`}
- className="size-4 rounded-full"
- />
- ),
- };
- }) ?? null,
- };
-
- const filters: ComponentProps<typeof Filter.Select>["filters"] = useMemo(
- () => [
- {
- key: "ai",
- icon: Magic,
- label: "Ask AI",
- separatorAfter: true,
- options:
- aiFilterSuggestions?.map(({ icon, value }) => ({
- value,
- label: value,
- icon,
- })) ?? null,
- },
- ...(dashboardProps
- ? []
- : partnerPage
- ? [LinkFilterItem, CustomerFilterItem]
- : [
- ...(canManageCustomers ? [CustomerFilterItem] : []),
- {
- key: "folderId",
- icon: Folder,
- label: "Folder",
- shouldFilter: !foldersAsync,
- getOptionIcon: (value, props) => {
- const folderName = props.option?.label;
- const folder = folders?.find(
- ({ name }) => name === folderName,
- );
-
- return folder ? (
- <FolderIcon
- folder={folder}
- shape="square"
- iconClassName="size-3"
- />
- ) : null;
- },
- options: loadingFolders
- ? null
- : [
- ...(folders || []),
- // Add currently filtered folder if not already in the list
- ...(selectedFolder &&
- !folders?.find((f) => f.id === selectedFolder.id)
- ? [selectedFolder]
- : []),
- ].map((folder) => ({
- value: folder.id,
- icon: (
- <FolderIcon
- folder={folder}
- shape="square"
- iconClassName="size-3"
- />
- ),
- label: folder.name,
- })),
- },
- {
- key: "tagIds",
- icon: Tag,
- label: "Tag",
- multiple: true,
- shouldFilter: !tagsAsync,
- getOptionIcon: (value, props) => {
- const tagColor =
- props.option?.data?.color ??
- tags?.find(({ id }) => id === value)?.color;
- return tagColor ? (
- <TagBadge color={tagColor} withIcon className="sm:p-1" />
- ) : null;
- },
- options: loadingTags
- ? null
- : [
- ...(tags || []),
- // Add currently filtered tags if not already in the list
- ...(selectedTags || []).filter(
- ({ id }) => !tags?.some((t) => t.id === id),
- ),
- ].map(({ id, name, color }) => ({
- value: id,
- icon: (
- <TagBadge color={color} withIcon className="sm:p-1" />
- ),
- label: name,
- data: { color },
- })),
- },
- {
- key: "domain",
- icon: Globe2,
- label: "Domain",
- shouldFilter: !domainsAsync,
- getOptionIcon: (value) => (
- <BlurImage
- src={`${GOOGLE_FAVICON_URL}${value}`}
- alt={value}
- className="h-4 w-4 rounded-full"
- width={16}
- height={16}
- />
- ),
- options: loadingDomains
- ? null
- : [
- ...domains.map((domain) => ({
- value: domain.slug,
- label: domain.slug,
- })),
- // Add currently filtered domain if not already in the list
- ...(!searchParamsObj.domain ||
- domains.some((d) => d.slug === searchParamsObj.domain)
- ? []
- : [
- {
- value: searchParamsObj.domain,
- label: searchParamsObj.domain,
- hideDuringSearch: true,
- },
- ]),
- ],
- },
- LinkFilterItem,
- {
- key: "root",
- icon: Sliders,
- label: "Link type",
- separatorAfter: true,
- options: [
- {
- value: true,
- icon: Globe2,
- label: "Root domain link",
- },
- {
- value: false,
- icon: Hyperlink,
- label: "Regular short link",
- },
- ],
- },
- ]),
- {
- key: "country",
- icon: FlagWavy,
- label: "Country",
- getOptionIcon: (value) => (
- <img
- alt={value}
- src={`https://hatscripts.github.io/circle-flags/flags/${value.toLowerCase()}.svg`}
- className="h-2.5 w-4"
- />
- ),
- getOptionLabel: (value) => COUNTRIES[value],
- options:
- countries?.map(({ country, count }) => ({
- value: country,
- label: COUNTRIES[country],
- right: nFormatter(count, { full: true }),
- })) ?? null,
- },
- {
- key: "city",
- icon: OfficeBuilding,
- label: "City",
- options:
- cities?.map(({ city, country, count }) => ({
- value: city,
- label: city,
- icon: (
- <img
- alt={country}
- src={`https://flag.vercel.app/m/${country}.svg`}
- className="h-2.5 w-4"
- />
- ),
- right: nFormatter(count, { full: true }),
- })) ?? null,
- },
- {
- key: "region",
- icon: LocationPin,
- label: "Region",
- options:
- regions?.map(({ region, country, count }) => ({
- value: region,
- label: REGIONS[region] || region.split("-")[1],
- icon: (
- <img
- alt={country}
- src={`https://flag.vercel.app/m/${country}.svg`}
- className="h-2.5 w-4"
- />
- ),
- right: nFormatter(count, { full: true }),
- })) ?? null,
- },
- {
- key: "continent",
- icon: MapPosition,
- label: "Continent",
- getOptionIcon: (value) => (
- <ContinentIcon display={value} className="size-2.5" />
- ),
- getOptionLabel: (value) => CONTINENTS[value],
- options:
- continents?.map(({ continent, count }) => ({
- value: continent,
- label: CONTINENTS[continent],
- right: nFormatter(count, { full: true }),
- })) ?? null,
- },
- {
- key: "device",
- icon: MobilePhone,
- label: "Device",
- getOptionIcon: (value) => (
- <DeviceIcon
- display={capitalize(value) ?? value}
- tab="devices"
- className="h-4 w-4"
- />
- ),
- options:
- devices?.map(({ device, count }) => ({
- value: device,
- label: device,
- right: nFormatter(count, { full: true }),
- })) ?? null,
- },
- {
- key: "browser",
- icon: Window,
- label: "Browser",
- getOptionIcon: (value) => (
- <DeviceIcon display={value} tab="browsers" className="h-4 w-4" />
- ),
- options:
- browsers?.map(({ browser, count }) => ({
- value: browser,
- label: browser,
- right: nFormatter(count, { full: true }),
- })) ?? null,
- },
- {
- key: "os",
- icon: Cube,
- label: "OS",
- getOptionIcon: (value) => (
- <DeviceIcon display={value} tab="os" className="h-4 w-4" />
- ),
- options:
- os?.map(({ os, count }) => ({
- value: os,
- label: os,
- right: nFormatter(count, { full: true }),
- })) ?? null,
- },
- {
- key: "trigger",
- icon: CursorRays,
- label: "Trigger",
- options:
- triggers?.map(({ trigger, count }) => ({
- value: trigger,
- label: TRIGGER_DISPLAY[trigger],
- icon: trigger === "qr" ? QRCode : CursorRays,
- right: nFormatter(count, { full: true }),
- })) ?? null,
- separatorAfter: true,
- },
- {
- key: "referer",
- icon: ReferredVia,
- label: "Referer",
- getOptionIcon: (value, props) => (
- <RefererIcon display={value} className="h-4 w-4" />
- ),
- options:
- referers?.map(({ referer, count }) => ({
- value: referer,
- label: referer,
- right: nFormatter(count, { full: true }),
- })) ?? null,
- },
- {
- key: "refererUrl",
- icon: ReferredVia,
- label: "Referrer URL",
- getOptionIcon: (value, props) => (
- <RefererIcon display={value} className="h-4 w-4" />
- ),
- options:
- refererUrls?.map(({ refererUrl, count }) => ({
- value: refererUrl,
- label: refererUrl,
- right: nFormatter(count, { full: true }),
- })) ?? null,
- },
- {
- key: "url",
- icon: LinkBroken,
- label: "Destination URL",
- getOptionIcon: (_, props) => (
- <LinkLogo
- apexDomain={getApexDomain(props.option?.value)}
- className="size-4 sm:size-4"
- />
- ),
- options:
- urls?.map(({ url, count }) => ({
- value: url,
- label: url.replace(/^https?:\/\//, "").replace(/\/$/, ""),
- right: nFormatter(count, { full: true }),
- })) ?? null,
- },
- ...UTM_PARAMETERS.filter(({ key }) => key !== "ref").map(
- ({ key, label, icon: Icon }) => ({
- key,
- icon: Icon,
- label: `UTM ${label}`,
- getOptionIcon: (value) => (
- <Icon display={value} className="h-4 w-4" />
- ),
- options:
- utmData[key]?.map((dt) => ({
- value: dt[key],
- label: dt[key],
- right: nFormatter(dt.count, { full: true }),
- })) ?? null,
- }),
- ),
- ],
- [
- selectedTab,
- dashboardProps,
- partnerPage,
- domains,
- links,
- tags,
- folders,
- selectedTags,
- selectedTagIds,
- selectedFolder,
- selectedCustomerId,
- countries,
- cities,
- devices,
- browsers,
- os,
- referers,
- refererUrls,
- urls,
- utmData,
- tagsAsync,
- domainsAsync,
- foldersAsync,
- loadingTags,
- loadingDomains,
- loadingFolders,
- searchParamsObj.tagIds,
- searchParamsObj.domain,
- ],
- );
-
- const { isMobile } = useMediaQuery();
+ filters,
+ activeFilters,
+ setSearch,
+ setSelectedFilter,
+ onSelect,
+ onRemove,
+ onRemoveAll,
+ onOpenFilter,
+ streaming,
+ activeFiltersWithStreaming,
+ } = useAnalyticsFilters({ partnerPage, dashboardProps });
const filterSelect = (
<Filter.Select
@@ -808,69 +83,9 @@ export default function Toggle({
activeFilters={activeFilters}
onSearchChange={setSearch}
onSelectedFilterChange={setSelectedFilter}
- onSelect={async (key, value) => {
- if (key === "ai") {
- setStreaming(true);
- const prompt = value.replace("Ask AI ", "");
- const { object } = await generateFilters(prompt);
- for await (const partialObject of readStreamableValue(object)) {
- if (partialObject) {
- queryParams({
- set: Object.fromEntries(
- Object.entries(partialObject).map(([key, value]) => [
- key,
- // Convert Dates to ISO strings
- value instanceof Date ? value.toISOString() : String(value),
- ]),
- ),
- });
- }
- }
- posthog.capture("ai_filters_generated", {
- prompt,
- filters: activeFilters,
- });
- setStreaming(false);
- } else {
- queryParams({
- set:
- key === "link"
- ? {
- domain: new URL(`https://${value}`).hostname,
- key:
- new URL(`https://${value}`).pathname.slice(1) || "_root",
- }
- : key === "tagIds"
- ? {
- tagIds: selectedTagIds.concat(value).join(","),
- }
- : {
- [key]: value,
- },
- del: "page",
- scroll: false,
- });
- }
- }}
- onRemove={(key, value) =>
- queryParams(
- key === "tagIds" &&
- !(selectedTagIds.length === 1 && selectedTagIds[0] === value)
- ? {
- set: {
- tagIds: selectedTagIds.filter((id) => id !== value).join(","),
- },
- scroll: false,
- }
- : {
- del: key === "link" ? ["domain", "key"] : key,
- scroll: false,
- },
- )
- }
- onOpenFilter={(key) =>
- setRequestedFilters((rf) => (rf.includes(key) ? rf : [...rf, key]))
- }
+ onSelect={onSelect}
+ onRemove={onRemove}
+ onOpenFilter={onOpenFilter}
askAI
/>
);
@@ -1074,42 +289,9 @@ export default function Toggle({
>
<Filter.List
filters={filters}
- activeFilters={[
- ...activeFilters,
- ...(streaming && !activeFilters.length
- ? Array.from({ length: 2 }, (_, i) => i).map((i) => ({
- key: "loader",
- value: i,
- }))
- : []),
- ]}
- onRemove={(key, value) =>
- queryParams(
- key === "tagIds" &&
- !(selectedTagIds.length === 1 && selectedTagIds[0] === value)
- ? {
- set: {
- tagIds: selectedTagIds
- .filter((id) => id !== value)
- .join(","),
- },
- scroll: false,
- }
- : {
- del: key === "link" ? ["domain", "key", "url"] : key,
- scroll: false,
- },
- )
- }
- onRemoveAll={() =>
- queryParams({
- // Reset all filters except for date range
- del: VALID_ANALYTICS_FILTERS.concat(["page"]).filter(
- (f) => !["interval", "start", "end"].includes(f),
- ),
- scroll: false,
- })
- }
+ activeFilters={activeFiltersWithStreaming}
+ onRemove={onRemove}
+ onRemoveAll={onRemoveAll}
/>
<div
className={cn(
diff --git a/apps/web/ui/analytics/use-analytics-filters.tsx b/apps/web/ui/analytics/use-analytics-filters.tsx
new file mode 100644
index 0000000000..0cf59fd66c
--- /dev/null
+++ b/apps/web/ui/analytics/use-analytics-filters.tsx
@@ -0,0 +1,901 @@
+import { generateFilters } from "@/lib/ai/generate-filters";
+import {
+ TRIGGER_DISPLAY,
+ VALID_ANALYTICS_FILTERS,
+} from "@/lib/analytics/constants";
+import { getPlanCapabilities } from "@/lib/plan-capabilities";
+import useCustomer from "@/lib/swr/use-customer";
+import useCustomers from "@/lib/swr/use-customers";
+import useCustomersCount from "@/lib/swr/use-customers-count";
+import useDomains from "@/lib/swr/use-domains";
+import useDomainsCount from "@/lib/swr/use-domains-count";
+import useFolder from "@/lib/swr/use-folder";
+import useFolders from "@/lib/swr/use-folders";
+import useFoldersCount from "@/lib/swr/use-folders-count";
+import usePartnerCustomer from "@/lib/swr/use-partner-customer";
+import useTags from "@/lib/swr/use-tags";
+import useTagsCount from "@/lib/swr/use-tags-count";
+import useWorkspace from "@/lib/swr/use-workspace";
+import { LinkProps } from "@/lib/types";
+import { CUSTOMERS_MAX_PAGE_SIZE } from "@/lib/zod/schemas/customers";
+import { DOMAINS_MAX_PAGE_SIZE } from "@/lib/zod/schemas/domains";
+import { FOLDERS_MAX_PAGE_SIZE } from "@/lib/zod/schemas/folders";
+import { TAGS_MAX_PAGE_SIZE } from "@/lib/zod/schemas/tags";
+import {
+ BlurImage,
+ Filter,
+ LinkLogo,
+ Sliders,
+ useRouterStuff,
+ UTM_PARAMETERS,
+} from "@dub/ui";
+import {
+ Cube,
+ CursorRays,
+ FlagWavy,
+ Folder,
+ Globe2,
+ Hyperlink,
+ LinkBroken,
+ LocationPin,
+ Magic,
+ MapPosition,
+ MobilePhone,
+ OfficeBuilding,
+ QRCode,
+ ReferredVia,
+ Tag,
+ User,
+ Window,
+} from "@dub/ui/icons";
+import {
+ capitalize,
+ CONTINENTS,
+ COUNTRIES,
+ getApexDomain,
+ GOOGLE_FAVICON_URL,
+ linkConstructor,
+ nFormatter,
+ OG_AVATAR_URL,
+ REGIONS,
+} from "@dub/utils";
+import { readStreamableValue } from "ai/rsc";
+import { useParams } from "next/navigation";
+import posthog from "posthog-js";
+import {
+ ComponentProps,
+ ContextType,
+ useCallback,
+ useMemo,
+ useState,
+} from "react";
+import { useDebounce } from "use-debounce";
+import { FolderIcon } from "../folders/folder-icon";
+import { LinkIcon } from "../links/link-icon";
+import TagBadge from "../links/tag-badge";
+import {
+ AnalyticsContext,
+ AnalyticsDashboardProps,
+} from "./analytics-provider";
+import ContinentIcon from "./continent-icon";
+import DeviceIcon from "./device-icon";
+import RefererIcon from "./referer-icon";
+import { useAnalyticsFilterOption } from "./utils";
+
+export function useAnalyticsFilters({
+ partnerPage,
+ dashboardProps,
+ context,
+}: {
+ partnerPage?: boolean;
+ dashboardProps?: AnalyticsDashboardProps;
+ context?: Pick<
+ ContextType<typeof AnalyticsContext>,
+ "baseApiPath" | "queryString" | "selectedTab" | "requiresUpgrade"
+ >;
+} = {}) {
+ const { slug, programSlug } = useParams();
+ const { plan } = useWorkspace();
+
+ const { queryParams, searchParamsObj } = useRouterStuff();
+
+ // Determine whether filters should be fetched async
+ const { data: tagsCount } = useTagsCount();
+ const { data: domainsCount } = useDomainsCount({ ignoreParams: true });
+ const { data: foldersCount } = useFoldersCount();
+ const { data: customersCount } = useCustomersCount();
+ const tagsAsync = Boolean(tagsCount && tagsCount > TAGS_MAX_PAGE_SIZE);
+ const domainsAsync = domainsCount && domainsCount > DOMAINS_MAX_PAGE_SIZE;
+ const foldersAsync = foldersCount && foldersCount > FOLDERS_MAX_PAGE_SIZE;
+ const customersAsync =
+ customersCount && customersCount > CUSTOMERS_MAX_PAGE_SIZE;
+
+ const [selectedFilter, setSelectedFilter] = useState<string | null>(null);
+ const [search, setSearch] = useState("");
+ const [debouncedSearch] = useDebounce(search, 500);
+
+ const { tags, loading: loadingTags } = useTags({
+ query: {
+ search: tagsAsync && selectedFilter === "tagIds" ? debouncedSearch : "",
+ },
+ });
+ const { folders, loading: loadingFolders } = useFolders({
+ query: {
+ search:
+ foldersAsync && selectedFilter === "folderId" ? debouncedSearch : "",
+ },
+ });
+ const { customers } = useCustomers({
+ query: {
+ search:
+ customersAsync && selectedFilter === "customerId"
+ ? debouncedSearch
+ : "",
+ },
+ });
+ const { canManageCustomers } = getPlanCapabilities(plan);
+
+ const {
+ allDomains: domains,
+ primaryDomain,
+ loading: loadingDomains,
+ } = useDomains({
+ ignoreParams: true,
+ opts: {
+ search:
+ domainsAsync && selectedFilter === "domain" ? debouncedSearch : "",
+ },
+ });
+
+ const selectedTagIds = useMemo(
+ () => searchParamsObj.tagIds?.split(",")?.filter(Boolean) ?? [],
+ [searchParamsObj.tagIds],
+ );
+
+ const { tags: selectedTags } = useTags({
+ query: { ids: selectedTagIds },
+ enabled: tagsAsync,
+ });
+
+ const selectedFolderId = searchParamsObj.folderId;
+
+ const { folder: selectedFolder } = useFolder({
+ folderId: selectedFolderId,
+ });
+
+ const selectedCustomerId = searchParamsObj.customerId;
+
+ const { data: selectedCustomerWorkspace } = useCustomer({
+ customerId: selectedCustomerId,
+ });
+ const { data: selectedCustomerPartner } = usePartnerCustomer({
+ customerId: selectedCustomerId,
+ });
+
+ const selectedCustomer = selectedCustomerPartner || selectedCustomerWorkspace;
+
+ const [requestedFilters, setRequestedFilters] = useState<string[]>([]);
+
+ const activeFilters = useMemo(() => {
+ const { domain, key, root, folderId, ...params } = searchParamsObj;
+
+ // Handle special cases first
+ const filters = [
+ // Handle domain/key special case
+ ...(domain && !key ? [{ key: "domain", value: domain }] : []),
+ ...(domain && key
+ ? [
+ {
+ key: "link",
+ value: linkConstructor({ domain, key, pretty: true }),
+ },
+ ]
+ : []),
+ // Handle tagIds special case
+ ...(selectedTagIds.length > 0
+ ? [{ key: "tagIds", value: selectedTagIds }]
+ : []),
+ // Handle root special case - convert string to boolean
+ ...(root ? [{ key: "root", value: root === "true" }] : []),
+ // Handle folderId special case
+ ...(folderId ? [{ key: "folderId", value: folderId }] : []),
+ // Handle customerId special case
+ ...(selectedCustomer
+ ? [
+ {
+ key: "customerId",
+ value:
+ selectedCustomer.email ||
+ selectedCustomer["name"] ||
+ selectedCustomer["externalId"],
+ },
+ ]
+ : []),
+ ];
+
+ // Handle all other filters dynamically
+ VALID_ANALYTICS_FILTERS.forEach((filter) => {
+ // Skip special cases we handled above
+ if (
+ ["domain", "key", "tagId", "tagIds", "root", "customerId"].includes(
+ filter,
+ )
+ )
+ return;
+ // also skip date range filters and qr
+ if (["interval", "start", "end", "qr"].includes(filter)) return;
+
+ const value = params[filter];
+ if (value) {
+ filters.push({ key: filter, value });
+ }
+ });
+
+ return filters;
+ }, [
+ searchParamsObj,
+ selectedTagIds,
+ partnerPage,
+ selectedCustomerId,
+ selectedCustomer,
+ ]);
+
+ const isRequested = useCallback(
+ (key: string) =>
+ requestedFilters.includes(key) ||
+ activeFilters.some((af) => af.key === key),
+ [requestedFilters, activeFilters],
+ );
+
+ const { data: links } = useAnalyticsFilterOption("top_links", {
+ cacheOnly: !isRequested("link"),
+ context,
+ });
+ const { data: countries } = useAnalyticsFilterOption("countries", {
+ cacheOnly: !isRequested("country"),
+ context,
+ });
+ const { data: regions } = useAnalyticsFilterOption("regions", {
+ cacheOnly: !isRequested("region"),
+ context,
+ });
+ const { data: cities } = useAnalyticsFilterOption("cities", {
+ cacheOnly: !isRequested("city"),
+ context,
+ });
+ const { data: continents } = useAnalyticsFilterOption("continents", {
+ cacheOnly: !isRequested("continent"),
+ context,
+ });
+ const { data: devices } = useAnalyticsFilterOption("devices", {
+ cacheOnly: !isRequested("device"),
+ context,
+ });
+ const { data: browsers } = useAnalyticsFilterOption("browsers", {
+ cacheOnly: !isRequested("browser"),
+ context,
+ });
+ const { data: os } = useAnalyticsFilterOption("os", {
+ cacheOnly: !isRequested("os"),
+ context,
+ });
+ const { data: triggers } = useAnalyticsFilterOption("triggers", {
+ cacheOnly: !isRequested("trigger"),
+ context,
+ });
+ const { data: referers } = useAnalyticsFilterOption("referers", {
+ cacheOnly: !isRequested("referer"),
+ context,
+ });
+ const { data: refererUrls } = useAnalyticsFilterOption("referer_urls", {
+ cacheOnly: !isRequested("refererUrl"),
+ context,
+ });
+ const { data: urls } = useAnalyticsFilterOption("top_urls", {
+ cacheOnly: !isRequested("url"),
+ context,
+ });
+ const { data: utmSources } = useAnalyticsFilterOption("utm_sources", {
+ cacheOnly: !isRequested("utm_source"),
+ context,
+ });
+ const { data: utmMediums } = useAnalyticsFilterOption("utm_mediums", {
+ cacheOnly: !isRequested("utm_medium"),
+ context,
+ });
+ const { data: utmCampaigns } = useAnalyticsFilterOption("utm_campaigns", {
+ cacheOnly: !isRequested("utm_campaign"),
+ context,
+ });
+ const { data: utmTerms } = useAnalyticsFilterOption("utm_terms", {
+ cacheOnly: !isRequested("utm_term"),
+ context,
+ });
+ const { data: utmContents } = useAnalyticsFilterOption("utm_contents", {
+ cacheOnly: !isRequested("utm_content"),
+ context,
+ });
+ const utmData = {
+ utm_source: utmSources,
+ utm_medium: utmMediums,
+ utm_campaign: utmCampaigns,
+ utm_term: utmTerms,
+ utm_content: utmContents,
+ };
+
+ // Some suggestions will only appear if previously requested (see isRequested above)
+ const aiFilterSuggestions = useMemo(
+ () => [
+ ...(dashboardProps || partnerPage
+ ? []
+ : [
+ {
+ value: `Clicks on ${primaryDomain} domain this year`,
+ icon: Globe2,
+ },
+ ]),
+ {
+ value: "Mobile users, US only",
+ icon: MobilePhone,
+ },
+ {
+ value: "Tokyo, Chrome users",
+ icon: OfficeBuilding,
+ },
+ {
+ value: "Safari, Singapore, last month",
+ icon: FlagWavy,
+ },
+ {
+ value: "QR scans last quarter",
+ icon: QRCode,
+ },
+ ],
+ [primaryDomain, dashboardProps, partnerPage],
+ );
+
+ const [streaming, setStreaming] = useState<boolean>(false);
+
+ const LinkFilterItem = {
+ key: "link",
+ icon: Hyperlink,
+ label: "Link",
+ getOptionIcon: (value, props) => {
+ const url = props.option?.data?.url;
+ const [domain, key] = value.split("/");
+
+ return <LinkIcon url={url} domain={domain} linkKey={key} />;
+ },
+ options:
+ links?.map(
+ ({ domain, key, url, count }: LinkProps & { count?: number }) => ({
+ value: linkConstructor({ domain, key, pretty: true }),
+ label: linkConstructor({ domain, key, pretty: true }),
+ right: nFormatter(count, { full: true }),
+ data: { url },
+ permalink:
+ slug && !partnerPage
+ ? `/${slug}/links/${linkConstructor({ domain, key, pretty: true })}`
+ : undefined,
+ }),
+ ) ?? null,
+ };
+
+ const CustomerFilterItem = {
+ key: "customerId",
+ icon: User,
+ label: "Customer",
+ hideInFilterDropdown: partnerPage,
+ shouldFilter: !customersAsync,
+ getOptionIcon: () => {
+ return selectedCustomer ? (
+ <img
+ src={
+ selectedCustomer["avatar"] ||
+ `${OG_AVATAR_URL}${selectedCustomer.id}`
+ }
+ alt={`${selectedCustomer.email} avatar`}
+ className="size-4 rounded-full"
+ />
+ ) : null;
+ },
+ getOptionPermalink: () => {
+ return programSlug
+ ? `/programs/${programSlug}/customers/${selectedCustomerId}`
+ : slug
+ ? `/${slug}/customers/${selectedCustomerId}`
+ : null;
+ },
+ options:
+ customers?.map(({ id, email, name, avatar }) => {
+ return {
+ value: id,
+ label: email ?? name,
+ icon: (
+ <img
+ src={avatar || `${OG_AVATAR_URL}${id}`}
+ alt={`${email} avatar`}
+ className="size-4 rounded-full"
+ />
+ ),
+ };
+ }) ?? null,
+ };
+
+ const filters: ComponentProps<typeof Filter.Select>["filters"] = useMemo(
+ () => [
+ {
+ key: "ai",
+ icon: Magic,
+ label: "Ask AI",
+ separatorAfter: true,
+ options:
+ aiFilterSuggestions?.map(({ icon, value }) => ({
+ value,
+ label: value,
+ icon,
+ })) ?? null,
+ },
+ ...(dashboardProps
+ ? []
+ : partnerPage
+ ? [LinkFilterItem, CustomerFilterItem]
+ : [
+ ...(canManageCustomers ? [CustomerFilterItem] : []),
+ {
+ key: "folderId",
+ icon: Folder,
+ label: "Folder",
+ shouldFilter: !foldersAsync,
+ getOptionIcon: (value, props) => {
+ const folderName = props.option?.label;
+ const folder = folders?.find(
+ ({ name }) => name === folderName,
+ );
+
+ return folder ? (
+ <FolderIcon
+ folder={folder}
+ shape="square"
+ iconClassName="size-3"
+ />
+ ) : null;
+ },
+ options: loadingFolders
+ ? null
+ : [
+ ...(folders || []),
+ // Add currently filtered folder if not already in the list
+ ...(selectedFolder &&
+ !folders?.find((f) => f.id === selectedFolder.id)
+ ? [selectedFolder]
+ : []),
+ ].map((folder) => ({
+ value: folder.id,
+ icon: (
+ <FolderIcon
+ folder={folder}
+ shape="square"
+ iconClassName="size-3"
+ />
+ ),
+ label: folder.name,
+ })),
+ },
+ {
+ key: "tagIds",
+ icon: Tag,
+ label: "Tag",
+ multiple: true,
+ shouldFilter: !tagsAsync,
+ getOptionIcon: (value, props) => {
+ const tagColor =
+ props.option?.data?.color ??
+ tags?.find(({ id }) => id === value)?.color;
+ return tagColor ? (
+ <TagBadge color={tagColor} withIcon className="sm:p-1" />
+ ) : null;
+ },
+ options: loadingTags
+ ? null
+ : [
+ ...(tags || []),
+ // Add currently filtered tags if not already in the list
+ ...(selectedTags || []).filter(
+ ({ id }) => !tags?.some((t) => t.id === id),
+ ),
+ ].map(({ id, name, color }) => ({
+ value: id,
+ icon: (
+ <TagBadge color={color} withIcon className="sm:p-1" />
+ ),
+ label: name,
+ data: { color },
+ })),
+ },
+ {
+ key: "domain",
+ icon: Globe2,
+ label: "Domain",
+ shouldFilter: !domainsAsync,
+ getOptionIcon: (value) => (
+ <BlurImage
+ src={`${GOOGLE_FAVICON_URL}${value}`}
+ alt={value}
+ className="h-4 w-4 rounded-full"
+ width={16}
+ height={16}
+ />
+ ),
+ options: loadingDomains
+ ? null
+ : [
+ ...domains.map((domain) => ({
+ value: domain.slug,
+ label: domain.slug,
+ })),
+ // Add currently filtered domain if not already in the list
+ ...(!searchParamsObj.domain ||
+ domains.some((d) => d.slug === searchParamsObj.domain)
+ ? []
+ : [
+ {
+ value: searchParamsObj.domain,
+ label: searchParamsObj.domain,
+ hideDuringSearch: true,
+ },
+ ]),
+ ],
+ },
+ LinkFilterItem,
+ {
+ key: "root",
+ icon: Sliders,
+ label: "Link type",
+ separatorAfter: true,
+ options: [
+ {
+ value: true,
+ icon: Globe2,
+ label: "Root domain link",
+ },
+ {
+ value: false,
+ icon: Hyperlink,
+ label: "Regular short link",
+ },
+ ],
+ },
+ ]),
+ {
+ key: "country",
+ icon: FlagWavy,
+ label: "Country",
+ getOptionIcon: (value) => (
+ <img
+ alt={value}
+ src={`https://hatscripts.github.io/circle-flags/flags/${value.toLowerCase()}.svg`}
+ className="h-2.5 w-4"
+ />
+ ),
+ getOptionLabel: (value) => COUNTRIES[value],
+ options:
+ countries?.map(({ country, count }) => ({
+ value: country,
+ label: COUNTRIES[country],
+ right: nFormatter(count, { full: true }),
+ })) ?? null,
+ },
+ {
+ key: "city",
+ icon: OfficeBuilding,
+ label: "City",
+ options:
+ cities?.map(({ city, country, count }) => ({
+ value: city,
+ label: city,
+ icon: (
+ <img
+ alt={country}
+ src={`https://flag.vercel.app/m/${country}.svg`}
+ className="h-2.5 w-4"
+ />
+ ),
+ right: nFormatter(count, { full: true }),
+ })) ?? null,
+ },
+ {
+ key: "region",
+ icon: LocationPin,
+ label: "Region",
+ options:
+ regions?.map(({ region, country, count }) => ({
+ value: region,
+ label: REGIONS[region] || region.split("-")[1],
+ icon: (
+ <img
+ alt={country}
+ src={`https://flag.vercel.app/m/${country}.svg`}
+ className="h-2.5 w-4"
+ />
+ ),
+ right: nFormatter(count, { full: true }),
+ })) ?? null,
+ },
+ {
+ key: "continent",
+ icon: MapPosition,
+ label: "Continent",
+ getOptionIcon: (value) => (
+ <ContinentIcon display={value} className="size-2.5" />
+ ),
+ getOptionLabel: (value) => CONTINENTS[value],
+ options:
+ continents?.map(({ continent, count }) => ({
+ value: continent,
+ label: CONTINENTS[continent],
+ right: nFormatter(count, { full: true }),
+ })) ?? null,
+ },
+ {
+ key: "device",
+ icon: MobilePhone,
+ label: "Device",
+ getOptionIcon: (value) => (
+ <DeviceIcon
+ display={capitalize(value) ?? value}
+ tab="devices"
+ className="h-4 w-4"
+ />
+ ),
+ options:
+ devices?.map(({ device, count }) => ({
+ value: device,
+ label: device,
+ right: nFormatter(count, { full: true }),
+ })) ?? null,
+ },
+ {
+ key: "browser",
+ icon: Window,
+ label: "Browser",
+ getOptionIcon: (value) => (
+ <DeviceIcon display={value} tab="browsers" className="h-4 w-4" />
+ ),
+ options:
+ browsers?.map(({ browser, count }) => ({
+ value: browser,
+ label: browser,
+ right: nFormatter(count, { full: true }),
+ })) ?? null,
+ },
+ {
+ key: "os",
+ icon: Cube,
+ label: "OS",
+ getOptionIcon: (value) => (
+ <DeviceIcon display={value} tab="os" className="h-4 w-4" />
+ ),
+ options:
+ os?.map(({ os, count }) => ({
+ value: os,
+ label: os,
+ right: nFormatter(count, { full: true }),
+ })) ?? null,
+ },
+ {
+ key: "trigger",
+ icon: CursorRays,
+ label: "Trigger",
+ options:
+ triggers?.map(({ trigger, count }) => ({
+ value: trigger,
+ label: TRIGGER_DISPLAY[trigger],
+ icon: trigger === "qr" ? QRCode : CursorRays,
+ right: nFormatter(count, { full: true }),
+ })) ?? null,
+ separatorAfter: true,
+ },
+ {
+ key: "referer",
+ icon: ReferredVia,
+ label: "Referer",
+ getOptionIcon: (value, props) => (
+ <RefererIcon display={value} className="h-4 w-4" />
+ ),
+ options:
+ referers?.map(({ referer, count }) => ({
+ value: referer,
+ label: referer,
+ right: nFormatter(count, { full: true }),
+ })) ?? null,
+ },
+ {
+ key: "refererUrl",
+ icon: ReferredVia,
+ label: "Referrer URL",
+ getOptionIcon: (value, props) => (
+ <RefererIcon display={value} className="h-4 w-4" />
+ ),
+ options:
+ refererUrls?.map(({ refererUrl, count }) => ({
+ value: refererUrl,
+ label: refererUrl,
+ right: nFormatter(count, { full: true }),
+ })) ?? null,
+ },
+ {
+ key: "url",
+ icon: LinkBroken,
+ label: "Destination URL",
+ getOptionIcon: (_, props) => (
+ <LinkLogo
+ apexDomain={getApexDomain(props.option?.value)}
+ className="size-4 sm:size-4"
+ />
+ ),
+ options:
+ urls?.map(({ url, count }) => ({
+ value: url,
+ label: url.replace(/^https?:\/\//, "").replace(/\/$/, ""),
+ right: nFormatter(count, { full: true }),
+ })) ?? null,
+ },
+ ...UTM_PARAMETERS.filter(({ key }) => key !== "ref").map(
+ ({ key, label, icon: Icon }) => ({
+ key,
+ icon: Icon,
+ label: `UTM ${label}`,
+ getOptionIcon: (value) => (
+ <Icon display={value} className="h-4 w-4" />
+ ),
+ options:
+ utmData[key]?.map((dt) => ({
+ value: dt[key],
+ label: dt[key],
+ right: nFormatter(dt.count, { full: true }),
+ })) ?? null,
+ }),
+ ),
+ ],
+ [
+ dashboardProps,
+ partnerPage,
+ domains,
+ links,
+ tags,
+ folders,
+ selectedTags,
+ selectedTagIds,
+ selectedFolder,
+ selectedCustomerId,
+ countries,
+ cities,
+ devices,
+ browsers,
+ os,
+ referers,
+ refererUrls,
+ urls,
+ utmData,
+ tagsAsync,
+ domainsAsync,
+ foldersAsync,
+ loadingTags,
+ loadingDomains,
+ loadingFolders,
+ searchParamsObj.tagIds,
+ searchParamsObj.domain,
+ ],
+ );
+
+ const onSelect = useCallback(
+ async (key, value) => {
+ if (key === "ai") {
+ setStreaming(true);
+ const prompt = value.replace("Ask AI ", "");
+ const { object } = await generateFilters(prompt);
+ for await (const partialObject of readStreamableValue(object)) {
+ if (partialObject) {
+ queryParams({
+ set: Object.fromEntries(
+ Object.entries(partialObject).map(([key, value]) => [
+ key,
+ // Convert Dates to ISO strings
+ value instanceof Date ? value.toISOString() : String(value),
+ ]),
+ ),
+ });
+ }
+ }
+ posthog.capture("ai_filters_generated", {
+ prompt,
+ filters: activeFilters,
+ });
+ setStreaming(false);
+ } else {
+ queryParams({
+ set:
+ key === "link"
+ ? {
+ domain: new URL(`https://${value}`).hostname,
+ key: new URL(`https://${value}`).pathname.slice(1) || "_root",
+ }
+ : key === "tagIds"
+ ? {
+ tagIds: selectedTagIds.concat(value).join(","),
+ }
+ : {
+ [key]: value,
+ },
+ del: "page",
+ scroll: false,
+ });
+ }
+ },
+ [queryParams, activeFilters, selectedTagIds],
+ );
+
+ const onRemove = useCallback(
+ (key, value) =>
+ queryParams(
+ key === "tagIds" &&
+ !(selectedTagIds.length === 1 && selectedTagIds[0] === value)
+ ? {
+ set: {
+ tagIds: selectedTagIds.filter((id) => id !== value).join(","),
+ },
+ scroll: false,
+ }
+ : {
+ del: key === "link" ? ["domain", "key", "url"] : key,
+ scroll: false,
+ },
+ ),
+ [queryParams, selectedTagIds],
+ );
+
+ const onRemoveAll = useCallback(
+ () =>
+ queryParams({
+ // Reset all filters except for date range
+ del: VALID_ANALYTICS_FILTERS.concat(["page"]).filter(
+ (f) => !["interval", "start", "end"].includes(f),
+ ),
+ scroll: false,
+ }),
+ [queryParams],
+ );
+
+ const onOpenFilter = useCallback(
+ (key) =>
+ setRequestedFilters((rf) => (rf.includes(key) ? rf : [...rf, key])),
+ [],
+ );
+
+ const activeFiltersWithStreaming = useMemo(
+ () => [
+ ...activeFilters,
+ ...(streaming && !activeFilters.length
+ ? Array.from({ length: 2 }, (_, i) => i).map((i) => ({
+ key: "loader",
+ value: i,
+ }))
+ : []),
+ ],
+ [activeFilters, streaming],
+ );
+
+ return {
+ filters,
+ activeFilters,
+ setSearch,
+ setSelectedFilter,
+ onSelect,
+ onRemove,
+ onRemoveAll,
+ onOpenFilter,
+ streaming,
+ activeFiltersWithStreaming,
+ };
+}
diff --git a/apps/web/ui/analytics/use-analytics-query.tsx b/apps/web/ui/analytics/use-analytics-query.tsx
new file mode 100644
index 0000000000..bc75f2eebd
--- /dev/null
+++ b/apps/web/ui/analytics/use-analytics-query.tsx
@@ -0,0 +1,132 @@
+import {
+ DUB_LINKS_ANALYTICS_INTERVAL,
+ EVENT_TYPES,
+ VALID_ANALYTICS_FILTERS,
+} from "@/lib/analytics/constants";
+import { EventType } from "@/lib/analytics/types";
+import { combineTagIds } from "@/lib/api/tags/combine-tag-ids";
+import useWorkspace from "@/lib/swr/use-workspace";
+import { endOfDay, startOfDay, subDays } from "date-fns";
+import { useSearchParams } from "next/navigation";
+import { useMemo } from "react";
+
+export function useAnalyticsQuery({
+ defaultEvent = "clicks",
+ domain: domainParam,
+ defaultKey,
+ defaultInterval = DUB_LINKS_ANALYTICS_INTERVAL,
+ defaultRoot,
+}: {
+ defaultEvent?: EventType;
+ domain?: string;
+ defaultKey?: string;
+ defaultInterval?: string;
+ defaultRoot?: (props: {
+ key?: string;
+ folderId?: string;
+ tagIds?: string;
+ }) => boolean | string | undefined;
+} = {}) {
+ const searchParams = useSearchParams();
+ const { id: workspaceId } = useWorkspace();
+
+ const domain = domainParam ?? searchParams?.get("domain");
+ // key can be a query param (stats pages in app) or passed as a staticKey (shared analytics dashboards)
+ const key = searchParams?.get("key") || defaultKey;
+
+ const tagIds = combineTagIds({
+ tagId: searchParams?.get("tagId"),
+ tagIds: searchParams?.get("tagIds")?.split(","),
+ })?.join(",");
+
+ const folderId = searchParams?.get("folderId") ?? undefined;
+
+ const customerId = searchParams?.get("customerId") ?? undefined;
+
+ // Default to last 24 hours
+ const { start, end } = useMemo(() => {
+ const hasRange = searchParams?.has("start") && searchParams?.has("end");
+
+ return {
+ start: hasRange
+ ? startOfDay(
+ new Date(searchParams?.get("start") || subDays(new Date(), 1)),
+ )
+ : undefined,
+
+ end: hasRange
+ ? endOfDay(new Date(searchParams?.get("end") || new Date()))
+ : undefined,
+ };
+ }, [searchParams?.get("start"), searchParams?.get("end")]);
+
+ // Only set interval if start and end are not provided
+ const interval =
+ start || end ? undefined : searchParams?.get("interval") ?? defaultInterval;
+
+ const root = searchParams.get("root")
+ ? searchParams.get("root") === "true"
+ : defaultRoot
+ ? defaultRoot({ key, folderId, tagIds })
+ : false;
+
+ const selectedTab: EventType = useMemo(() => {
+ const event = searchParams.get("event");
+
+ return EVENT_TYPES.find((t) => t === event) ?? defaultEvent;
+ }, [searchParams.get("event"), defaultEvent]);
+
+ const queryString = useMemo(() => {
+ const availableFilterParams = VALID_ANALYTICS_FILTERS.reduce(
+ (acc, filter) => ({
+ ...acc,
+ ...(searchParams?.get(filter) && {
+ [filter]: searchParams.get(filter),
+ }),
+ }),
+ {},
+ );
+ return new URLSearchParams({
+ ...availableFilterParams,
+ ...(workspaceId && { workspaceId }),
+ ...(domain && { domain }),
+ ...(key && { key }),
+ ...(start &&
+ end && { start: start.toISOString(), end: end.toISOString() }),
+ ...(interval && { interval }),
+ ...(tagIds && { tagIds }),
+ ...(root && { root: root.toString() }),
+ event: selectedTab,
+ ...(folderId && { folderId }),
+ ...(customerId && { customerId }),
+ timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
+ }).toString();
+ }, [
+ searchParams,
+ workspaceId,
+ domain,
+ key,
+ start,
+ end,
+ interval,
+ tagIds,
+ root,
+ selectedTab,
+ folderId,
+ customerId,
+ ]);
+
+ return {
+ queryString,
+ domain,
+ key,
+ start,
+ end,
+ interval,
+ tagIds,
+ root,
+ selectedTab,
+ folderId,
+ customerId,
+ };
+}
diff --git a/apps/web/ui/analytics/utils.ts b/apps/web/ui/analytics/utils.ts
index 19e08992d0..59e254ce69 100644
--- a/apps/web/ui/analytics/utils.ts
+++ b/apps/web/ui/analytics/utils.ts
@@ -1,7 +1,7 @@
import { AnalyticsGroupByOptions } from "@/lib/analytics/types";
import { editQueryString } from "@/lib/analytics/utils";
import { fetcher } from "@dub/utils";
-import { useContext } from "react";
+import { ContextType, useContext } from "react";
import useSWR, { useSWRConfig } from "swr";
import { AnalyticsContext } from "./analytics-provider";
@@ -20,12 +20,18 @@ export function useAnalyticsFilterOption(
groupByOrParams:
| AnalyticsGroupByOptions
| ({ groupBy: AnalyticsGroupByOptions } & Record<string, any>),
- options?: { cacheOnly?: boolean },
+ options?: {
+ cacheOnly?: boolean;
+ context?: Pick<
+ ContextType<typeof AnalyticsContext>,
+ "baseApiPath" | "queryString" | "selectedTab" | "requiresUpgrade"
+ >;
+ },
): AnalyticsFilterResult {
const { cache } = useSWRConfig();
const { baseApiPath, queryString, selectedTab, requiresUpgrade } =
- useContext(AnalyticsContext);
+ options?.context ?? useContext(AnalyticsContext);
const enabled =
!options?.cacheOnly ||