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 funnel chart

Tim Wilson6e7f8ef64069
diff --git a/apps/web/lib/analytics/constants.ts b/apps/web/lib/analytics/constants.ts
index 0b38d96485..9356afaa2a 100644
--- a/apps/web/lib/analytics/constants.ts
+++ b/apps/web/lib/analytics/constants.ts
@@ -133,6 +133,8 @@ export const VALID_ANALYTICS_FILTERS = [
export const EVENT_TYPES = ["clicks", "leads", "sales"] as const;
+export const ANALYTICS_VIEWS = ["default", "funnel"] as const;
+
export const OLD_ANALYTICS_ENDPOINTS = [
"clicks",
"count",
diff --git a/apps/web/lib/analytics/types.ts b/apps/web/lib/analytics/types.ts
index 231314ec24..7d0cab80fd 100644
--- a/apps/web/lib/analytics/types.ts
+++ b/apps/web/lib/analytics/types.ts
@@ -3,7 +3,12 @@ import {
analyticsQuerySchema,
eventsQuerySchema,
} from "../zod/schemas/analytics";
-import { EVENT_TYPES, VALID_ANALYTICS_ENDPOINTS, intervals } from "./constants";
+import {
+ ANALYTICS_VIEWS,
+ EVENT_TYPES,
+ VALID_ANALYTICS_ENDPOINTS,
+ intervals,
+} from "./constants";
export type IntervalOptions = (typeof intervals)[number];
export type AnalyticsGroupByOptions =
@@ -16,6 +21,8 @@ export type CompositeAnalyticsResponseOptions =
export type EventType = (typeof EVENT_TYPES)[number];
+export type AnalyticsView = (typeof ANALYTICS_VIEWS)[number];
+
export type LocationTabs = "countries" | "cities";
export type TopLinksTabs = "link" | "url";
export type DeviceTabs = "devices" | "browsers" | "os";
diff --git a/apps/web/ui/analytics/analytics-funnel-chart.tsx b/apps/web/ui/analytics/analytics-funnel-chart.tsx
new file mode 100644
index 0000000000..8f10341146
--- /dev/null
+++ b/apps/web/ui/analytics/analytics-funnel-chart.tsx
@@ -0,0 +1,230 @@
+import { cn, nFormatter } from "@dub/utils";
+import { curveBasis } from "@visx/curve";
+import { ParentSize } from "@visx/responsive";
+import { scaleLinear } from "@visx/scale";
+import { Area } from "@visx/shape";
+import { Text } from "@visx/text";
+import { motion } from "framer-motion";
+import { Fragment, useCallback, useContext, useMemo, useState } from "react";
+import { AnalyticsLoadingSpinner } from "./analytics-loading-spinner";
+import { AnalyticsContext } from "./analytics-provider";
+
+const steps = [
+ {
+ id: "clicks",
+ label: "Clicks",
+ colorClassName: "text-blue-600",
+ },
+ {
+ id: "leads",
+ label: "Leads",
+ colorClassName: "text-violet-600",
+ },
+ {
+ id: "sales",
+ label: "Sales",
+ colorClassName: "text-teal-400",
+ },
+];
+
+const layers = [
+ {
+ opacity: 1,
+ padding: 0,
+ },
+ {
+ opacity: 0.3,
+ padding: 8,
+ },
+ {
+ opacity: 0.15,
+ padding: 16,
+ },
+];
+
+const maxLayerPadding = 16;
+const chartPadding = 40;
+
+export function AnalyticsFunnelChart() {
+ return (
+ // p-5 pt-10 sm:p-10
+ <div className="flex h-[444px] w-full items-center justify-center sm:h-[464px]">
+ <ParentSize className="relative">
+ {({ width, height }) =>
+ width && height ? (
+ <AnalyticsFunnelChartInner width={width} height={height} />
+ ) : null
+ }
+ </ParentSize>
+ </div>
+ );
+}
+
+export function AnalyticsFunnelChartInner({
+ width,
+ height,
+}: {
+ width: number;
+ height: number;
+}) {
+ const { totalEvents } = useContext(AnalyticsContext);
+
+ const [tooltip, setTooltip] = useState<string | null>(null);
+ const tooltipStep = steps.find(({ id }) => id === tooltip);
+
+ const stepValue = useCallback(
+ (step: string) => totalEvents?.[step] ?? 0,
+ [totalEvents],
+ );
+
+ const data = useMemo(() => {
+ return Object.fromEntries(
+ steps.map(({ id }, idx) => {
+ const current = stepValue(id);
+ const next = stepValue(
+ steps[idx + 1]?.id ?? steps[steps.length - 1].id,
+ );
+ return [id, interpolate(current, next)];
+ }),
+ );
+ }, [stepValue]);
+
+ const zeroData = useMemo(() => interpolate(0, 0), [steps]);
+
+ const maxValue = useMemo(
+ () => Math.max(...steps.map((step) => stepValue(step.id))),
+ [stepValue],
+ );
+
+ const xScale = scaleLinear({
+ domain: [0, steps.length],
+ range: [0, width],
+ });
+
+ const yScale = scaleLinear({
+ domain: [maxValue, -maxValue],
+ range: [
+ height - maxLayerPadding - chartPadding,
+ maxLayerPadding + chartPadding,
+ ],
+ });
+
+ return totalEvents ? (
+ <div className="relative">
+ <svg width={width} height={height}>
+ {steps.map(({ id, colorClassName }, idx) => (
+ <Fragment key={id}>
+ {/* Background */}
+ <rect
+ x={xScale(idx)}
+ y={0}
+ width={width / steps.length}
+ height={height}
+ className="fill-transparent transition-colors hover:fill-blue-600/5"
+ onPointerEnter={() => setTooltip(id)}
+ onPointerLeave={() => setTooltip(null)}
+ />
+ {/* Divider line */}
+ <line
+ x1={xScale(idx)}
+ y1={0}
+ x2={xScale(idx)}
+ y2={height}
+ className="stroke-black/10"
+ />
+
+ {/* Funnel */}
+ {layers.map(({ opacity, padding }) => (
+ <Area
+ data={data[id]}
+ curve={curveBasis}
+ x={(d) => xScale(idx + d.x)}
+ y0={(d) => yScale(-d.y) - padding}
+ y1={(d) => yScale(d.y) + padding}
+ >
+ {({ path }) => {
+ return (
+ <motion.path
+ initial={{ d: path(zeroData) || "", opacity: 0 }}
+ animate={{ d: path(data[id]) || "", opacity }}
+ className={cn(colorClassName, "pointer-events-none")}
+ fill="currentColor"
+ />
+ );
+ }}
+ </Area>
+ ))}
+
+ {/* Percentage */}
+ {totalEvents && (
+ <Text
+ x={(xScale(idx) + xScale(idx + 1)) / 2}
+ y={height / 2}
+ textAnchor="middle"
+ verticalAnchor="middle"
+ fill="white"
+ fontSize={16}
+ className="pointer-events-none"
+ >
+ {formatPercentage((totalEvents?.[id] / maxValue) * 100) + "%"}
+ </Text>
+ )}
+ </Fragment>
+ ))}
+ </svg>
+ {tooltipStep && (
+ <div
+ key={tooltipStep.id}
+ className="animate-slide-up-fade pointer-events-none absolute top-12 flex items-center justify-center pb-4"
+ style={{
+ left: xScale(steps.findIndex(({ id }) => id === tooltipStep.id)),
+ width: width / steps.length,
+ }}
+ >
+ <div
+ className={cn(
+ "rounded-lg border border-gray-200 bg-white text-base shadow-sm",
+ )}
+ >
+ <p className="border-b border-gray-200 px-4 py-3 text-sm text-gray-900">
+ {tooltipStep.label}
+ </p>
+ <div className="xs:grid-cols-2 grid grid-cols-1 gap-x-6 gap-y-2 px-4 py-3 text-sm">
+ <div className="flex items-center gap-2">
+ <div
+ className={cn(
+ tooltipStep.colorClassName,
+ "h-2 w-2 shrink-0 rounded-sm bg-current opacity-50 shadow-[inset_0_0_0_1px_#0003]",
+ )}
+ />
+ <p className="whitespace-nowrap capitalize text-gray-600">
+ {formatPercentage(
+ (stepValue(tooltipStep.id) / maxValue) * 100,
+ ) + "%"}
+ </p>
+ </div>
+ <p className="xs:text-right font-medium text-gray-900">
+ {nFormatter(stepValue(tooltipStep.id))}
+ </p>
+ </div>
+ </div>
+ </div>
+ )}
+ </div>
+ ) : (
+ <div className="flex h-full w-full items-center justify-center">
+ <AnalyticsLoadingSpinner />
+ </div>
+ );
+}
+
+const formatPercentage = (value: number) =>
+ value > 0 && value < 1 ? "< 1" : nFormatter(value, { digits: 2 });
+
+const interpolate = (from: number, to: number) => [
+ { x: 0, y: from },
+ { x: 0.3, y: from },
+ { x: 0.5, y: (from + to) / 2 },
+ { x: 0.7, y: to },
+ { x: 1, y: to },
+];
diff --git a/apps/web/ui/analytics/analytics-provider.tsx b/apps/web/ui/analytics/analytics-provider.tsx
index b0a9f9c852..0b8b307792 100644
--- a/apps/web/ui/analytics/analytics-provider.tsx
+++ b/apps/web/ui/analytics/analytics-provider.tsx
@@ -1,10 +1,12 @@
"use client";
import {
+ ANALYTICS_VIEWS,
EVENT_TYPES,
VALID_ANALYTICS_FILTERS,
} from "@/lib/analytics/constants";
import {
+ AnalyticsView,
CompositeAnalyticsResponseOptions,
EventType,
} from "@/lib/analytics/types";
@@ -29,6 +31,7 @@ export const AnalyticsContext = createContext<{
basePath: string;
baseApiPath: string;
selectedTab: EventType;
+ view: AnalyticsView;
domain?: string;
key?: string;
url?: string;
@@ -47,6 +50,7 @@ export const AnalyticsContext = createContext<{
basePath: "",
baseApiPath: "",
selectedTab: "clicks",
+ view: "default",
domain: "",
queryString: "",
start: new Date(),
@@ -113,6 +117,14 @@ export default function AnalyticsProvider({
return EVENT_TYPES.find((t) => t === tab) ?? "clicks";
}, [searchParams.get("tab")]);
+ const view: AnalyticsView = useMemo(() => {
+ if (!demoPage && !flags?.conversions) return "default";
+
+ const view = searchParams.get("view");
+
+ return ANALYTICS_VIEWS.find((v) => v === view) ?? "default";
+ }, [searchParams.get("view")]);
+
const root = searchParams.get("root")
? searchParams.get("root") === "true"
: undefined;
@@ -221,6 +233,7 @@ export default function AnalyticsProvider({
basePath, // basePath for the page (e.g. /stats/[key], /[slug]/analytics)
baseApiPath, // baseApiPath for analytics API endpoints (e.g. /api/analytics)
selectedTab, // selected tab (clicks, leads, sales)
+ view,
queryString,
domain: domain || undefined, // domain for the link (e.g. dub.sh, stey.me, etc.)
key: key ? decodeURIComponent(key) : undefined, // link key (e.g. github, weathergpt, etc.)
diff --git a/apps/web/ui/analytics/main.tsx b/apps/web/ui/analytics/main.tsx
index 811820d459..d5a2fc235a 100644
--- a/apps/web/ui/analytics/main.tsx
+++ b/apps/web/ui/analytics/main.tsx
@@ -4,14 +4,16 @@ import {
Button,
CountingNumbers,
NumberTooltip,
+ Tooltip,
useRouterStuff,
} from "@dub/ui";
-import { SquareLayoutGrid6 } from "@dub/ui/src/icons";
+import { ChartLine, Filter2, SquareLayoutGrid6 } from "@dub/ui/src/icons";
import { cn } from "@dub/utils";
import { ChevronRight, Lock } from "lucide-react";
import Link from "next/link";
import { useContext, useMemo } from "react";
import AnalyticsAreaChart from "./analytics-area-chart";
+import { AnalyticsFunnelChart } from "./analytics-funnel-chart";
import { AnalyticsContext } from "./analytics-provider";
type Tab = {
@@ -22,8 +24,14 @@ type Tab = {
export default function Main() {
const { flags, slug } = useWorkspace();
- const { basePath, totalEvents, requiresUpgrade, demoPage, selectedTab } =
- useContext(AnalyticsContext);
+ const {
+ basePath,
+ totalEvents,
+ requiresUpgrade,
+ demoPage,
+ selectedTab,
+ view,
+ } = useContext(AnalyticsContext);
const { router, queryParams, getQueryString } = useRouterStuff();
const isPublicStatsPage = basePath.startsWith("/stats");
@@ -142,37 +150,85 @@ export default function Main() {
);
})}
</div>
- <div className="hidden shrink-0 pr-2 pt-2 sm:block sm:pr-6 sm:pt-6">
- <Button
- variant="secondary"
- className="h-9 border-transparent px-2 hover:border-gray-200"
- icon={<SquareLayoutGrid6 className="h-4 w-4 text-gray-600" />}
- text="View Events"
- onClick={() => {
- if (isPublicStatsPage) {
- window.open("https://d.to/events");
- } else {
- router.push(`/${slug}/events${getQueryString()}`);
- }
- }}
- />
+ <div className="hidden sm:block">
+ <ViewButtons />
</div>
</div>
- <div className="relative p-5 pt-10 sm:p-10">
+ <div className="relative">
+ <div className="absolute right-3 top-3 z-10 w-fit sm:hidden">
+ <ViewButtons />
+ </div>
+ {view === "default" && (
+ <div className="p-5 pt-10 sm:p-10">
+ <AnalyticsAreaChart resource={tab.id} />
+ </div>
+ )}
+ {view === "funnel" && <AnalyticsFunnelChart />}
+ </div>
+ </div>
+ );
+}
+
+function ViewButtons() {
+ const { flags, slug } = useWorkspace();
+ const { basePath, demoPage, view } = useContext(AnalyticsContext);
+ const { router, queryParams, getQueryString } = useRouterStuff();
+ const isPublicStatsPage = basePath.startsWith("/stats");
+
+ return (
+ <div className="flex shrink-0 items-center gap-1 border-gray-100 pr-2 pt-2 sm:pr-6 sm:pt-6">
+ {(flags?.conversions || demoPage) && (
+ <>
+ <Tooltip content="Line chart">
+ <Button
+ variant="secondary"
+ className={cn(
+ "h-9 border-transparent px-2 hover:border-gray-200",
+ view === "default" && "border border-gray-200 bg-gray-100",
+ )}
+ icon={<ChartLine className="h-4 w-4 text-gray-600" />}
+ onClick={() => {
+ queryParams({
+ del: "view",
+ });
+ }}
+ />
+ </Tooltip>
+ <Tooltip content="Funnel chart">
+ <Button
+ variant="secondary"
+ className={cn(
+ "h-9 border-transparent px-2 hover:border-gray-200",
+ view === "funnel" && "border border-gray-200 bg-gray-100",
+ )}
+ icon={<Filter2 className="h-4 w-4 -rotate-90 text-gray-600" />}
+ onClick={() => {
+ queryParams({
+ set: {
+ view: "funnel",
+ },
+ });
+ }}
+ />
+ </Tooltip>
+ </>
+ )}
+ <Tooltip content="View Events">
<Button
- variant="outline"
+ variant="secondary"
+ className="h-9 border-transparent px-2 hover:border-gray-200"
icon={<SquareLayoutGrid6 className="h-4 w-4 text-gray-600" />}
onClick={() => {
if (isPublicStatsPage) {
window.open("https://d.to/events");
} else {
- router.push(`/${slug}/events${getQueryString()}`);
+ router.push(
+ `/${slug}/events${getQueryString({}, { ignore: ["view"] })}`,
+ );
}
}}
- className="absolute right-3 top-3 h-8 w-fit p-2 sm:hidden"
/>
- <AnalyticsAreaChart resource={tab.id} />
- </div>
+ </Tooltip>
</div>
);
}
diff --git a/packages/ui/src/icons/nucleo/filter2.tsx b/packages/ui/src/icons/nucleo/filter2.tsx
new file mode 100644
index 0000000000..37be664dc7
--- /dev/null
+++ b/packages/ui/src/icons/nucleo/filter2.tsx
@@ -0,0 +1,24 @@
+import { SVGProps } from "react";
+
+export function Filter2(props: SVGProps<SVGSVGElement>) {
+ return (
+ <svg
+ height="18"
+ width="18"
+ viewBox="0 0 18 18"
+ xmlns="http://www.w3.org/2000/svg"
+ {...props}
+ >
+ <g fill="currentColor">
+ <path
+ d="M10.5,16.25h-3v-7.25L3.106,5.3c-.226-.19-.356-.47-.356-.765v-1.785H15.25v1.785c0,.295-.13,.575-.356,.765l-4.394,3.7v7.25Z"
+ fill="none"
+ stroke="currentColor"
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ strokeWidth="1.5"
+ />
+ </g>
+ </svg>
+ );
+}
diff --git a/packages/ui/src/icons/nucleo/index.ts b/packages/ui/src/icons/nucleo/index.ts
index 7f88c641c8..0cdf62aba8 100644
--- a/packages/ui/src/icons/nucleo/index.ts
+++ b/packages/ui/src/icons/nucleo/index.ts
@@ -28,6 +28,7 @@ export * from "./download";
export * from "./earth-position";
export * from "./eye-slash";
export * from "./filter-bars";
+export * from "./filter2";
export * from "./flag-wavy";
export * from "./flag2";
export * from "./gaming-console";