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 `FunnelChart` to `@dub/ui/charts`

Tim Wilson9d9d91b5a6d4
diff --git a/apps/web/ui/analytics/analytics-funnel-chart.tsx b/apps/web/ui/analytics/analytics-funnel-chart.tsx
index c0ef3830aa..486f2b03c5 100644
--- a/apps/web/ui/analytics/analytics-funnel-chart.tsx
+++ b/apps/web/ui/analytics/analytics-funnel-chart.tsx
@@ -1,243 +1,45 @@
-import { useMediaQuery } from "@dub/ui";
-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 { FunnelChart } from "@dub/ui/charts";
+import { useContext, useMemo } 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 { isMobile } = useMediaQuery();
-
- const [tooltip, setTooltip] = useState<string | null>(null);
- const tooltipStep = steps.find(({ id }) => id === tooltip);
-
- const stepValue = useCallback(
- (step: string) => totalEvents?.[step] ?? 0,
+ const steps = useMemo(
+ () => [
+ {
+ id: "clicks",
+ label: "Clicks",
+ value: totalEvents?.clicks ?? 0,
+ colorClassName: "text-blue-600",
+ },
+ {
+ id: "leads",
+ label: "Leads",
+ value: totalEvents?.leads ?? 0,
+ colorClassName: "text-violet-600",
+ },
+ {
+ id: "sales",
+ label: "Sales",
+ value: totalEvents?.sales ?? 0,
+ additionalValue: totalEvents?.saleAmount ?? 0,
+ colorClassName: "text-teal-400",
+ },
+ ],
[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)}
- onPointerDown={() => setTooltip(id)}
- onPointerLeave={() => !isMobile && setTooltip(null)}
- />
- {/* Divider line */}
- <line
- x1={xScale(idx)}
- y1={0}
- x2={xScale(idx)}
- y2={height}
- className="stroke-black/5 sm: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 select-none"
- >
- {formatPercentage((totalEvents?.[id] / maxValue) * 100) + "%"}
- </Text>
- )}
- </Fragment>
- ))}
- </svg>
- {tooltipStep && (
- <div
- key={tooltipStep.id}
- className="animate-slide-up-fade pointer-events-none absolute top-16 flex items-center justify-center px-1 pb-4 sm:top-12"
- 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-3 py-2 text-sm text-gray-900 sm:px-4 sm:py-3">
- {tooltipStep.label}
- </p>
- <div className="flex flex-wrap justify-between gap-x-4 gap-y-2 px-3 py-2 text-sm sm:px-4 sm:py-3">
- <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="whitespace-nowrap font-medium text-gray-900">
- {nFormatter(stepValue(tooltipStep.id), { full: true })}
- {tooltipStep.id === "sales" && (
- <span className="text-gray-500">
- {" "}
- (${nFormatter(totalEvents.saleAmount / 100)})
- </span>
- )}
- </p>
- </div>
- </div>
+ return (
+ <div className="h-[444px] w-full sm:h-[464px]">
+ {totalEvents ? (
+ <FunnelChart steps={steps} />
+ ) : (
+ <div className="flex h-full w-full items-center justify-center">
+ <AnalyticsLoadingSpinner />
</div>
)}
</div>
- ) : (
- <div className="flex h-full w-full items-center justify-center">
- <AnalyticsLoadingSpinner />
- </div>
);
}
-
-const formatPercentage = (value: number) => {
- return value > 0 && value < 0.01
- ? "< 0.01"
- : 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/packages/ui/src/charts/funnel-chart.tsx b/packages/ui/src/charts/funnel-chart.tsx
new file mode 100644
index 0000000000..38f18ec668
--- /dev/null
+++ b/packages/ui/src/charts/funnel-chart.tsx
@@ -0,0 +1,227 @@
+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, useMemo, useState } from "react";
+import { useMediaQuery } from "../hooks";
+
+const layers = [
+ {
+ opacity: 1,
+ padding: 0,
+ },
+ {
+ opacity: 0.3,
+ padding: 8,
+ },
+ {
+ opacity: 0.15,
+ padding: 16,
+ },
+];
+
+const maxLayerPadding = 16;
+const chartPadding = 40;
+
+type FunnelChartProps = {
+ steps: {
+ id: string;
+ label: string;
+ value: number;
+ additionalValue?: number;
+ colorClassName: string;
+ }[];
+ persistentPercentages?: boolean;
+};
+
+export function FunnelChart(props: FunnelChartProps) {
+ return (
+ <div className="size-full">
+ <ParentSize className="relative">
+ {({ width, height }) =>
+ width && height ? (
+ <FunnelChartInner {...props} width={width} height={height} />
+ ) : null
+ }
+ </ParentSize>
+ </div>
+ );
+}
+
+function FunnelChartInner({
+ width,
+ height,
+ steps,
+ persistentPercentages = true,
+}: {
+ width: number;
+ height: number;
+} & FunnelChartProps) {
+ const { isMobile } = useMediaQuery();
+
+ const [tooltip, setTooltip] = useState<string | null>(null);
+ const tooltipStep = steps.find(({ id }) => id === tooltip);
+
+ const data = useMemo(() => {
+ return Object.fromEntries(
+ steps.map(({ id, value }, idx) => [
+ id,
+ interpolate(
+ value,
+ steps[idx + 1]?.value ?? steps[steps.length - 1].value,
+ ),
+ ]),
+ );
+ }, [steps]);
+
+ const zeroData = useMemo(() => interpolate(0, 0), [steps]);
+
+ const maxValue = useMemo(
+ () => Math.max(...steps.map((step) => step.value)),
+ [steps],
+ );
+
+ const xScale = scaleLinear({
+ domain: [0, steps.length],
+ range: [0, width],
+ });
+
+ const yScale = scaleLinear({
+ domain: [maxValue, -maxValue],
+ range: [
+ height - maxLayerPadding - chartPadding,
+ maxLayerPadding + chartPadding,
+ ],
+ });
+
+ return (
+ <div className="relative">
+ <svg width={width} height={height}>
+ {steps.map(({ id, value, 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)}
+ onPointerDown={() => setTooltip(id)}
+ onPointerLeave={() => !isMobile && setTooltip(null)}
+ />
+ {/* Divider line */}
+ <line
+ x1={xScale(idx)}
+ y1={0}
+ x2={xScale(idx)}
+ y2={height}
+ className="stroke-black/5 sm: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 */}
+ {persistentPercentages && (
+ <Text
+ x={(xScale(idx) + xScale(idx + 1)) / 2}
+ y={height / 2}
+ textAnchor="middle"
+ verticalAnchor="middle"
+ fill="white"
+ fontSize={16}
+ className="pointer-events-none select-none"
+ >
+ {formatPercentage((value / maxValue) * 100) + "%"}
+ </Text>
+ )}
+ </Fragment>
+ ))}
+ </svg>
+ {tooltipStep && (
+ <div
+ key={tooltipStep.id}
+ className={cn(
+ "pointer-events-none absolute flex items-center justify-center px-1 pb-4",
+ persistentPercentages
+ ? "animate-slide-up-fade top-16 sm:top-12"
+ : "animate-fade-in top-1/2 -translate-y-1/2",
+ )}
+ 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-3 py-2 text-sm text-gray-900 sm:px-4 sm:py-3">
+ {tooltipStep.label}
+ </p>
+ <div className="flex flex-wrap justify-between gap-x-4 gap-y-2 px-3 py-2 text-sm sm:px-4 sm:py-3">
+ <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((tooltipStep.value / maxValue) * 100) + "%"}
+ </p>
+ </div>
+ <p className="whitespace-nowrap font-medium text-gray-900">
+ {nFormatter(tooltipStep.value, { full: true })}
+ {tooltipStep.additionalValue !== undefined && (
+ <span className="text-gray-500">
+ {" "}
+ (${nFormatter(tooltipStep.additionalValue / 100)})
+ </span>
+ )}
+ </p>
+ </div>
+ </div>
+ </div>
+ )}
+ </div>
+ );
+}
+
+const formatPercentage = (value: number) => {
+ return value > 0 && value < 0.01
+ ? "< 0.01"
+ : 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/packages/ui/src/charts/index.ts b/packages/ui/src/charts/index.ts
index 35ba921840..528aa9e7a6 100644
--- a/packages/ui/src/charts/index.ts
+++ b/packages/ui/src/charts/index.ts
@@ -1,6 +1,7 @@
export * from "./areas";
export * from "./bars";
export * from "./chart-context";
+export * from "./funnel-chart";
export * from "./time-series-chart";
export * from "./x-axis";
export * from "./y-axis";