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.

Add AI filter suggestions

Tim Wilson2787f0745830
diff --git a/apps/web/ui/analytics/toggle.tsx b/apps/web/ui/analytics/toggle.tsx
index 94ed347f7d..89b0746806 100644
--- a/apps/web/ui/analytics/toggle.tsx
+++ b/apps/web/ui/analytics/toggle.tsx
@@ -38,6 +38,7 @@ import {
COUNTRIES,
DUB_LOGO,
GOOGLE_FAVICON_URL,
+ capitalize,
cn,
getApexDomain,
getNextPlan,
@@ -59,7 +60,7 @@ import { COLORS_LIST } from "../links/tag-badge";
import DeviceIcon from "./device-icon";
import ExportButton from "./export-button";
import SharePopover from "./share-popover";
-import { useAnalyticsFilterOption } from "./utils";
+import { useAIFilterSuggestions, useAnalyticsFilterOption } from "./utils";
export default function Toggle() {
const { plan } = useWorkspace();
@@ -95,7 +96,7 @@ export default function Toggle() {
];
}, [searchParamsObj]);
- const isEnabled = useCallback(
+ const isRequested = useCallback(
(key: string) =>
requestedFilters.includes(key) ||
activeFilters.some((af) => af.key === key),
@@ -103,22 +104,29 @@ export default function Toggle() {
);
const links = useAnalyticsFilterOption("top_links", {
- enabled: isEnabled("link"),
+ cacheOnly: !isRequested("link"),
});
const countries = useAnalyticsFilterOption("countries", {
- enabled: isEnabled("country"),
+ cacheOnly: !isRequested("country"),
});
const cities = useAnalyticsFilterOption("cities", {
- enabled: isEnabled("city"),
+ cacheOnly: !isRequested("city"),
});
const devices = useAnalyticsFilterOption("devices", {
- enabled: isEnabled("device"),
+ cacheOnly: !isRequested("device"),
});
const browsers = useAnalyticsFilterOption("browsers", {
- enabled: isEnabled("browser"),
+ cacheOnly: !isRequested("browser"),
});
const os = useAnalyticsFilterOption("os", {
- enabled: isEnabled("os"),
+ cacheOnly: !isRequested("os"),
+ });
+
+ // Some suggestions will only appear if previously requested (see isRequested above)
+ const aiFilterSuggestions = useAIFilterSuggestions({
+ domains,
+ countries,
+ devices,
});
const [streaming, setStreaming] = useState<boolean>(false);
@@ -133,18 +141,12 @@ export default function Toggle() {
icon: Magic,
label: "Ask AI",
separatorAfter: true,
- options: [
- {
- value: "QR code scans in the last 30 days, US only",
- label: "QR code scans in the last 30 days, US only",
- icon: <QRCode className="h-4 w-4" />,
- },
- {
- value: "Canadian Desktop users in the last 90 days",
- label: "Canadian Desktop users in the last 90 days",
- icon: <Window className="h-4 w-4" />,
- },
- ],
+ options:
+ aiFilterSuggestions?.map(({ icon, value }) => ({
+ value,
+ label: value,
+ icon,
+ })) ?? null,
},
{
key: "domain",
@@ -296,7 +298,11 @@ export default function Toggle() {
icon: MobilePhone,
label: "Device",
getOptionIcon: (value) => (
- <DeviceIcon display={value} tab="devices" className="h-4 w-4" />
+ <DeviceIcon
+ display={capitalize(value) ?? value}
+ tab="devices"
+ className="h-4 w-4"
+ />
),
options:
devices?.map(({ device, count }) => ({
@@ -337,6 +343,7 @@ export default function Toggle() {
[
isPublicStatsPage,
domains,
+ allLinks,
links,
tags,
countries,
diff --git a/apps/web/ui/analytics/utils.ts b/apps/web/ui/analytics/utils.ts
deleted file mode 100644
index fa63e88389..0000000000
--- a/apps/web/ui/analytics/utils.ts
+++ /dev/null
@@ -1,44 +0,0 @@
-import { AnalyticsGroupByOptions } from "@/lib/analytics/types";
-import { editQueryString } from "@/lib/analytics/utils";
-import { fetcher } from "@dub/utils";
-import { useContext } from "react";
-import useSWR from "swr";
-import { AnalyticsContext } from ".";
-
-/**
- * Fetches event counts grouped by the specified filter
- *
- * @param groupByOrParams Either a groupBy option or a query parameter object including groupBy
- * @param options Additional options
- */
-export function useAnalyticsFilterOption(
- groupByOrParams:
- | AnalyticsGroupByOptions
- | ({ groupBy: AnalyticsGroupByOptions } & Record<string, any>),
- options?: { enabled?: boolean },
-): ({ count?: number } & Record<string, any>)[] | null {
- const { baseApiPath, queryString, selectedTab, requiresUpgrade } =
- useContext(AnalyticsContext);
-
- const { data } = useSWR<Record<string, any>[]>(
- options?.enabled !== false
- ? `${baseApiPath}?${editQueryString(queryString, {
- ...(typeof groupByOrParams === "string"
- ? { groupBy: groupByOrParams }
- : groupByOrParams),
- })}`
- : null,
- fetcher,
- {
- shouldRetryOnError: !requiresUpgrade,
- },
- );
-
- return (
- data?.map((d) => ({
- ...d,
- count:
- ((d[selectedTab] ?? d["clicks"]) as number | undefined) ?? undefined,
- })) ?? null
- );
-}
diff --git a/apps/web/ui/analytics/utils.tsx b/apps/web/ui/analytics/utils.tsx
new file mode 100644
index 0000000000..80a12c6b2f
--- /dev/null
+++ b/apps/web/ui/analytics/utils.tsx
@@ -0,0 +1,153 @@
+import { AnalyticsGroupByOptions } from "@/lib/analytics/types";
+import { editQueryString } from "@/lib/analytics/utils";
+import { BlurImage } from "@dub/ui";
+import { GOOGLE_FAVICON_URL, fetcher } from "@dub/utils";
+import { QrCode } from "lucide-react";
+import { ComponentType, ReactNode, SVGProps, useContext, useMemo } from "react";
+import useSWR, { useSWRConfig } from "swr";
+import { AnalyticsContext } from ".";
+import DeviceIcon from "./device-icon";
+
+type AnalyticsFilterResult =
+ | ({ count?: number } & Record<string, any>)[]
+ | null;
+
+/**
+ * Fetches event counts grouped by the specified filter
+ *
+ * @param groupByOrParams Either a groupBy option or a query parameter object including groupBy
+ * @param options Additional options
+ */
+export function useAnalyticsFilterOption(
+ groupByOrParams:
+ | AnalyticsGroupByOptions
+ | ({ groupBy: AnalyticsGroupByOptions } & Record<string, any>),
+ options?: { cacheOnly?: boolean },
+): AnalyticsFilterResult {
+ const { cache } = useSWRConfig();
+
+ const { baseApiPath, queryString, selectedTab, requiresUpgrade } =
+ useContext(AnalyticsContext);
+
+ const enabled =
+ !options?.cacheOnly ||
+ [...cache.keys()].includes(
+ `${baseApiPath}?${editQueryString(queryString, {
+ ...(typeof groupByOrParams === "string"
+ ? { groupBy: groupByOrParams }
+ : groupByOrParams),
+ })}`,
+ );
+
+ const { data } = useSWR<Record<string, any>[]>(
+ enabled
+ ? `${baseApiPath}?${editQueryString(queryString, {
+ ...(typeof groupByOrParams === "string"
+ ? { groupBy: groupByOrParams }
+ : groupByOrParams),
+ })}`
+ : null,
+ fetcher,
+ {
+ shouldRetryOnError: !requiresUpgrade,
+ },
+ );
+
+ return (
+ data?.map((d) => ({
+ ...d,
+ count:
+ ((d[selectedTab] ?? d["clicks"]) as number | undefined) ?? undefined,
+ })) ?? null
+ );
+}
+
+/**
+ * Returns a random item from the first `n` items of the array
+ */
+function randomItem<T>(arr: T[] | null | undefined, n?: number) {
+ return arr && arr.length
+ ? arr[Math.floor(Math.random() * Math.min(arr.length, n || arr.length))]
+ : null;
+}
+
+export function useAIFilterSuggestions({
+ domains,
+ countries,
+ devices,
+}: {
+ domains?: { slug: string }[];
+ countries?: AnalyticsFilterResult;
+ devices?: AnalyticsFilterResult;
+}):
+ | {
+ value: string;
+ icon: ComponentType<SVGProps<SVGSVGElement>> | ReactNode;
+ }[]
+ | null {
+ const domainSuggestions = useMemo(() => {
+ const randomDomain = randomItem(
+ domains?.filter(({ slug }) => slug.length < 14),
+ );
+ return randomDomain
+ ? [
+ {
+ value: `Clicks on links from the ${randomDomain.slug} domain`,
+ icon: (
+ <BlurImage
+ src={`${GOOGLE_FAVICON_URL}${randomDomain.slug}`}
+ alt={randomDomain.slug}
+ className="h-4 w-4 rounded-full"
+ width={16}
+ height={16}
+ />
+ ),
+ },
+ ]
+ : [];
+ }, [domains]);
+
+ const countrySuggestions = useMemo(() => {
+ const randomCountry = randomItem(countries, 4);
+ return randomCountry
+ ? [
+ {
+ value: `QR code scans in the last 30 days, ${randomCountry.country} only`,
+ icon: QrCode,
+ },
+ ]
+ : [];
+ }, [countries]);
+
+ const deviceSuggestions = useMemo(() => {
+ const randomDevice = randomItem(devices, 2);
+ return randomDevice
+ ? [
+ {
+ value: `${randomDevice.device} clicks from the last 90 days`,
+ icon: (
+ <DeviceIcon
+ display={randomDevice.device}
+ tab="devices"
+ className="h-4 w-4"
+ />
+ ),
+ },
+ ]
+ : [];
+ }, [devices]);
+
+ const allSuggestions = useMemo(() => {
+ const all = [
+ ...countrySuggestions,
+ ...deviceSuggestions,
+ ...domainSuggestions,
+ ];
+
+ if (!all.length && !domains && !countries && !devices) return null;
+
+ return all;
+ }, [domainSuggestions, countrySuggestions, deviceSuggestions]);
+
+ return allSuggestions;
+}