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 stats cards

Tim Wilsondfac0eb845b4
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/referrals/page.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/referrals/page.tsx
index ba7fefe581..62d08ed00d 100644
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/referrals/page.tsx
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/referrals/page.tsx
@@ -18,6 +18,7 @@ import { EventTabs } from "./event-tabs";
import { GenerateButton } from "./generate-button";
import { InviteButton } from "./invite-button";
import ReferralsPageClient from "./page-client";
+import { Stats } from "./stats";
export const dynamic = "auto";
@@ -88,7 +89,7 @@ export default async function ReferralsPage({
))}
</div>
- {/* Referral link + invite button */}
+ {/* Referral link + invite button or empty/error states */}
<div className="mt-8">
{linkUrl && !errorCode ? (
<div className="grid gap-1.5">
@@ -131,19 +132,26 @@ export default async function ReferralsPage({
</p>
</a>
</div>
- {!errorCode && (
- <div className="mt-12">
- <div className="mb-5 flex flex-wrap items-end justify-between gap-4">
- <h2 className="text-xl font-semibold text-gray-800">Activity</h2>
- <EventTabs />
+ {!errorCode && link && (
+ <>
+ <div className="mt-8">
+ <Stats linkId={link.id} />
</div>
- <Suspense
- key={`${slug}-${event}-${page}`}
- fallback={<EventListSkeleton />}
- >
- <ActivityListRSC slug={slug} event={event} page={page} />
- </Suspense>
- </div>
+ <div className="mt-12">
+ <div className="mb-5 flex flex-wrap items-end justify-between gap-4">
+ <h2 className="text-xl font-semibold text-gray-800">
+ Activity
+ </h2>
+ <EventTabs />
+ </div>
+ <Suspense
+ key={`${slug}-${event}-${page}`}
+ fallback={<EventListSkeleton />}
+ >
+ <ActivityListRSC linkId={link.id} event={event} page={page} />
+ </Suspense>
+ </div>
+ </>
)}
</div>
</ReferralsPageClient>
@@ -151,17 +159,16 @@ export default async function ReferralsPage({
}
async function ActivityListRSC({
- slug,
+ linkId,
event,
page,
}: {
- slug: string;
+ linkId: string;
event: EventType;
page: number;
}) {
const eventsParams = {
- domain: "refer.dub.co",
- key: slug,
+ linkId,
event,
};
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/referrals/stats.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/referrals/stats.tsx
new file mode 100644
index 0000000000..f9028fb09e
--- /dev/null
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/referrals/stats.tsx
@@ -0,0 +1,89 @@
+import { dub } from "@/lib/dub";
+import { StatCard, StatCardSkeleton } from "@dub/blocks";
+import { CountingNumbers } from "@dub/ui";
+import { ClicksCount, SalesCount } from "dub/dist/commonjs/models/components";
+import { Suspense } from "react";
+
+export function Stats({ linkId }: { linkId: string }) {
+ return (
+ <div className="grid grid-cols-1 gap-x-6 gap-y-4 sm:grid-cols-2">
+ <Suspense
+ fallback={[...Array(2)].map(() => (
+ <StatCardSkeleton />
+ ))}
+ >
+ <StatsInner linkId={linkId} />
+ </Suspense>
+ </div>
+ );
+}
+
+async function StatsInner({ linkId }: { linkId: string }) {
+ try {
+ const { totalClicks, clicks, totalSales, sales } = await loadData(linkId);
+
+ return (
+ <>
+ <StatCard label="Clicks" timeseriesData={clicks}>
+ <CountingNumbers>{totalClicks}</CountingNumbers>
+ </StatCard>
+ <StatCard label="Sales" timeseriesData={sales}>
+ <CountingNumbers prefix="$" fullNumber>
+ {totalSales / 100}
+ </CountingNumbers>
+ </StatCard>
+ </>
+ );
+ } catch (e) {
+ console.error("Failed to load referral stats", e);
+ }
+
+ return [...Array(2)].map(() => <StatCardSkeleton error />);
+}
+
+async function loadData(linkId: string) {
+ const [totalClicks, clicks, totalSales, sales] = await Promise.all([
+ // Total clicks
+ dub.analytics.retrieve({
+ linkId,
+ event: "clicks",
+ interval: "all_unfiltered",
+ }) as any as Promise<ClicksCount>,
+
+ // Clicks timeseries
+ dub.analytics.retrieve({
+ linkId,
+ event: "clicks",
+ interval: "30d",
+ groupBy: "timeseries",
+ }) as any as Promise<{ start: string; clicks: number }[]>,
+
+ // Total sales
+ dub.analytics.retrieve({
+ linkId,
+ event: "sales",
+ interval: "all", // temp fix until we add sales to all_unfiltered
+ }) as any as Promise<SalesCount>,
+
+ // Sales timeseries
+ (await dub.analytics.retrieve({
+ linkId,
+ event: "sales",
+ interval: "30d",
+ groupBy: "timeseries",
+ })) as any as Promise<{ start: string; sales: number; amount: number }[]>,
+ ]);
+
+ return {
+ totalClicks: totalClicks.clicks,
+ clicks: clicks.map((d) => ({
+ date: new Date(d.start),
+ value: d.clicks,
+ })),
+ totalSales: totalSales.amount,
+ sales: sales.map((d) => ({
+ date: new Date(d.start),
+ value: d.amount,
+ })),
+ };
+}
diff --git a/apps/web/ui/analytics/events/events-tabs.tsx b/apps/web/ui/analytics/events/events-tabs.tsx
index 7de66dba6c..ace3d0a6c6 100644
--- a/apps/web/ui/analytics/events/events-tabs.tsx
+++ b/apps/web/ui/analytics/events/events-tabs.tsx
@@ -1,15 +1,9 @@
import { CompositeAnalyticsResponseOptions } from "@/lib/analytics/types";
import { editQueryString } from "@/lib/analytics/utils";
import useWorkspace from "@/lib/swr/use-workspace";
+import { MiniAreaChart } from "@dub/blocks";
import { CountingNumbers, useMediaQuery, useRouterStuff } from "@dub/ui";
import { capitalize, cn, fetcher } from "@dub/utils";
-import { curveNatural } from "@visx/curve";
-import { LinearGradient } from "@visx/gradient";
-import { Group } from "@visx/group";
-import { ParentSize } from "@visx/responsive";
-import { scaleLinear, scaleUtc } from "@visx/scale";
-import { Area, AreaClosed } from "@visx/shape";
-import { motion } from "framer-motion";
import { useCallback, useContext, useEffect, useMemo } from "react";
import useSWR from "swr";
import useSWRImmutable from "swr/immutable";
@@ -60,6 +54,15 @@ export default function EventsTabs() {
},
);
+ const chartData = useMemo(() => {
+ if (!timeseriesData) return [];
+ return timeseriesData.map((d) => ({
+ date: new Date(d.start),
+ value:
+ ((tab === "sales" ? d?.amount : d?.[tab]) as number | undefined) ?? 0,
+ }));
+ }, [timeseriesData, tab]);
+
const onEventTabClick = useCallback(
(event: string) => {
const sortOptions =
@@ -130,7 +133,7 @@ export default function EventsTabs() {
isLoadingTimeseries && "opacity-40",
)}
>
- <Chart data={timeseriesData} event={event} />
+ <MiniAreaChart data={chartData} />
</div>
)}
</button>
@@ -138,137 +141,3 @@ export default function EventsTabs() {
</div>
);
}
-
-type ChartProps = { data: TimeseriesData; event: string };
-function Chart(props: ChartProps) {
- return (
- <ParentSize className="relative">
- {({ width, height }) => {
- return (
- width > 0 &&
- height > 0 && <ChartInner {...{ width, height, ...props }} />
- );
- }}
- </ParentSize>
- );
-}
-
-const padding = { top: 8, right: 2, bottom: 2, left: 2 };
-
-function ChartInner({
- data,
- event,
- width,
- height,
-}: ChartProps & { width: number; height: number }) {
- const chartData = useMemo(
- () =>
- data.map((d) => ({
- date: new Date(d.start),
- value:
- ((event === "sales" ? d?.amount : d?.[event]) as
- | number
- | undefined) ?? 0,
- })) ?? null,
- [data, event],
- );
-
- const zeroedData = useMemo(
- () =>
- chartData.map(({ date }) => ({
- date,
- value: 0,
- })),
- [chartData],
- );
-
- const { yScale, xScale } = useMemo(() => {
- const values = chartData.map(({ value }) => value);
- const maxY = Math.max(...values);
-
- const dateTimes = chartData.map(({ date }) => date.getTime());
- const minDate = new Date(Math.min(...dateTimes));
- const maxDate = new Date(Math.max(...dateTimes));
-
- return {
- yScale: scaleLinear<number>({
- domain: [-2, Math.max(maxY, 2)],
- range: [height - padding.top - padding.bottom, 0],
- nice: true,
- clamp: true,
- }),
- xScale: scaleUtc<number>({
- domain: [minDate, maxDate],
- range: [0, width - padding.left - padding.right],
- nice: true,
- }),
- };
- }, [chartData, height, width]);
-
- return (
- <svg width={width} height={height} key={chartData.length}>
- <defs>
- <LinearGradient
- id="color-gradient"
- from="#7D3AEC"
- to="#DA2778"
- x1={0}
- x2={width - padding.left - padding.right}
- gradientUnits="userSpaceOnUse"
- />
- <LinearGradient
- id="mask-gradient"
- from="white"
- to="white"
- fromOpacity={0.3}
- toOpacity={0}
- x1={0}
- x2={0}
- y1={0}
- y2={1}
- />
- <mask id="mask" maskContentUnits="objectBoundingBox">
- <rect width="1" height="1" fill="url(#mask-gradient)" />
- </mask>
- </defs>
- <Group left={padding.left} top={padding.top}>
- <Area
- data={chartData}
- x={({ date }) => xScale(date)}
- y={({ value }) => yScale(value) ?? 0}
- curve={curveNatural}
- >
- {({ path }) => {
- return (
- <motion.path
- initial={{ d: path(zeroedData) || "", opacity: 0 }}
- animate={{ d: path(chartData) || "", opacity: 1 }}
- strokeWidth={1.5}
- stroke="url(#color-gradient)"
- />
- );
- }}
- </Area>
-
- <AreaClosed
- data={chartData}
- x={({ date }) => xScale(date)}
- y={({ value }) => yScale(value) ?? 0}
- yScale={yScale}
- curve={curveNatural}
- >
- {({ path }) => {
- return (
- <motion.path
- initial={{ d: path(zeroedData) || "", opacity: 0 }}
- animate={{ d: path(chartData) || "", opacity: 1 }}
- fill="url(#color-gradient)"
- mask="url(#mask)"
- />
- );
- }}
- </AreaClosed>
- </Group>
- </svg>
- );
-}
diff --git a/packages/blocks/package.json b/packages/blocks/package.json
index 8f3f2f6654..45af5607f9 100644
--- a/packages/blocks/package.json
+++ b/packages/blocks/package.json
@@ -36,7 +36,14 @@
"typescript": "^5.1.6"
},
"dependencies": {
- "class-variance-authority": "^0.7.0"
+ "@visx/curve": "^3.3.0",
+ "@visx/gradient": "^3.3.0",
+ "@visx/group": "^3.3.0",
+ "@visx/responsive": "^2.10.0",
+ "@visx/scale": "^3.3.0",
+ "@visx/shape": "^2.12.2",
+ "class-variance-authority": "^0.7.0",
+ "framer-motion": "^10.16.16"
},
"author": "Steven Tey <[email protected]>",
"homepage": "https://dub.co",
diff --git a/packages/blocks/src/index.tsx b/packages/blocks/src/index.ts
similarity index 67%
rename from packages/blocks/src/index.tsx
rename to packages/blocks/src/index.ts
index 03dcbf38e1..0d8618279b 100644
--- a/packages/blocks/src/index.tsx
+++ b/packages/blocks/src/index.ts
@@ -3,4 +3,6 @@ import "./styles.css";
export * from "./empty-state";
export * from "./event-list";
+export * from "./mini-area-chart";
export * from "./pagination-controls";
+export * from "./stat-card";
diff --git a/packages/blocks/src/mini-area-chart.tsx b/packages/blocks/src/mini-area-chart.tsx
new file mode 100644
index 0000000000..e331955d9c
--- /dev/null
+++ b/packages/blocks/src/mini-area-chart.tsx
@@ -0,0 +1,132 @@
+import { curveNatural } from "@visx/curve";
+import { LinearGradient } from "@visx/gradient";
+import { Group } from "@visx/group";
+import { ParentSize } from "@visx/responsive";
+import { scaleLinear, scaleUtc } from "@visx/scale";
+import { Area, AreaClosed } from "@visx/shape";
+import { motion } from "framer-motion";
+import { useMemo } from "react";
+
+export type MiniAreaChartProps = {
+ data: { date: Date; value: number }[];
+};
+
+export function MiniAreaChart(props: MiniAreaChartProps) {
+ return (
+ <ParentSize className="relative">
+ {({ width, height }) => {
+ return (
+ width > 0 &&
+ height > 0 && <MiniAreaChartInner {...{ width, height, ...props }} />
+ );
+ }}
+ </ParentSize>
+ );
+}
+
+const padding = { top: 8, right: 2, bottom: 2, left: 2 };
+
+function MiniAreaChartInner({
+ data,
+ width,
+ height,
+}: MiniAreaChartProps & { width: number; height: number }) {
+ const zeroedData = useMemo(
+ () =>
+ data.map(({ date }) => ({
+ date,
+ value: 0,
+ })),
+ [data],
+ );
+
+ const { yScale, xScale } = useMemo(() => {
+ const values = data.map(({ value }) => value);
+ const maxY = Math.max(...values);
+
+ const dateTimes = data.map(({ date }) => date.getTime());
+ const minDate = new Date(Math.min(...dateTimes));
+ const maxDate = new Date(Math.max(...dateTimes));
+
+ return {
+ yScale: scaleLinear<number>({
+ domain: [-2, Math.max(maxY, 2)],
+ range: [height - padding.top - padding.bottom, 0],
+ nice: true,
+ clamp: true,
+ }),
+ xScale: scaleUtc<number>({
+ domain: [minDate, maxDate],
+ range: [0, width - padding.left - padding.right],
+ nice: true,
+ }),
+ };
+ }, [data, height, width]);
+
+ return (
+ <svg width={width} height={height} key={data.length}>
+ <defs>
+ <LinearGradient
+ id="color-gradient"
+ from="#7D3AEC"
+ to="#DA2778"
+ x1={0}
+ x2={width - padding.left - padding.right}
+ gradientUnits="userSpaceOnUse"
+ />
+ <LinearGradient
+ id="mask-gradient"
+ from="white"
+ to="white"
+ fromOpacity={0.3}
+ toOpacity={0}
+ x1={0}
+ x2={0}
+ y1={0}
+ y2={1}
+ />
+ <mask id="mask" maskContentUnits="objectBoundingBox">
+ <rect width="1" height="1" fill="url(#mask-gradient)" />
+ </mask>
+ </defs>
+ <Group left={padding.left} top={padding.top}>
+ <Area
+ data={data}
+ x={({ date }) => xScale(date)}
+ y={({ value }) => yScale(value) ?? 0}
+ curve={curveNatural}
+ >
+ {({ path }) => {
+ return (
+ <motion.path
+ initial={{ d: path(zeroedData) || "", opacity: 0 }}
+ animate={{ d: path(data) || "", opacity: 1 }}
+ strokeWidth={1.5}
+ stroke="url(#color-gradient)"
+ />
+ );
+ }}
+ </Area>
+
+ <AreaClosed
+ data={data}
+ x={({ date }) => xScale(date)}
+ y={({ value }) => yScale(value) ?? 0}
+ yScale={yScale}
+ curve={curveNatural}
+ >
+ {({ path }) => {
+ return (
+ <motion.path
+ initial={{ d: path(zeroedData) || "", opacity: 0 }}
+ animate={{ d: path(data) || "", opacity: 1 }}
+ fill="url(#color-gradient)"
+ mask="url(#mask)"
+ />
+ );
+ }}
+ </AreaClosed>
+ </Group>
+ </svg>
+ );
+}
diff --git a/packages/blocks/src/stat-card.tsx b/packages/blocks/src/stat-card.tsx
new file mode 100644
index 0000000000..bf829c901a
--- /dev/null
+++ b/packages/blocks/src/stat-card.tsx
@@ -0,0 +1,45 @@
+import { PropsWithChildren } from "react";
+import { MiniAreaChart, MiniAreaChartProps } from "./mini-area-chart";
+
+const wrapperClassName =
+ "flex justify-between gap-4 rounded-xl border border-gray-200 bg-white px-5 py-4 text-left";
+
+export function StatCard({
+ label,
+ timeseriesData,
+ children,
+}: PropsWithChildren<{
+ label: string;
+ timeseriesData: MiniAreaChartProps["data"];
+}>) {
+ return (
+ <div className={wrapperClassName}>
+ <div className="flex flex-col gap-2">
+ <span className="text-sm text-gray-600">{label}</span>
+ <span className="text-2xl font-medium">{children}</span>
+ </div>
+ {timeseriesData && (
+ <div className="relative h-full min-w-0 max-w-[140px] grow">
+ <MiniAreaChart data={timeseriesData} />
+ </div>
+ )}
+ </div>
+ );
+}
+
+export function StatCardSkeleton({ error }: { error?: boolean }) {
+ return (
+ <div className={wrapperClassName}>
+ {error ? (
+ <div className="flex h-[60px] w-full items-center justify-center text-sm text-gray-500">
+ Failed to load data
+ </div>
+ ) : (
+ <div className="flex flex-col gap-2">
+ <span className="h-[22px] w-16 animate-pulse rounded-full bg-gray-200" />
+ <span className="h-[30px] w-32 animate-pulse rounded-full bg-gray-200" />
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/packages/blocks/tsup.config.ts b/packages/blocks/tsup.config.ts
index 6a8a1e5cb0..78a41d1e80 100644
--- a/packages/blocks/tsup.config.ts
+++ b/packages/blocks/tsup.config.ts
@@ -1,7 +1,7 @@
import { defineConfig, Options } from "tsup";
export default defineConfig((options: Options) => ({
- entry: ["src/**/*.tsx"],
+ entry: ["src/**/*.tsx", "src/**/*.ts"],
format: ["esm"],
esbuildOptions(options) {
options.banner = {
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 1df9068afb..31fce0a7b5 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -423,9 +423,30 @@ importers:
'@dub/utils':
specifier: workspace:*
version: link:../utils
+ '@visx/curve':
+ specifier: ^3.3.0
+ version: 3.3.0
+ '@visx/gradient':
+ specifier: ^3.3.0
+ version: 3.3.0([email protected])
+ '@visx/group':
+ specifier: ^3.3.0
+ version: 3.3.0([email protected])
+ '@visx/responsive':
+ specifier: ^2.10.0
+ version: 2.10.0([email protected])
+ '@visx/scale':
+ specifier: ^3.3.0
+ version: 3.3.0
+ '@visx/shape':
+ specifier: ^2.12.2
+ version: 2.12.2([email protected])
class-variance-authority:
specifier: ^0.7.0
version: 0.7.0
+ framer-motion:
+ specifier: ^10.16.16
react-dom:
specifier: ^18.2.0
version: 18.2.0([email protected])