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 new analytics charts (not hooked up properly yet)

Tim Wilson17c0e005a83e
diff --git a/apps/web/ui/analytics/clicks-chart.tsx b/apps/web/ui/analytics/analytics-area-chart.tsx
similarity index 62%
rename from apps/web/ui/analytics/clicks-chart.tsx
rename to apps/web/ui/analytics/analytics-area-chart.tsx
index c713232640..651783f576 100644
--- a/apps/web/ui/analytics/clicks-chart.tsx
+++ b/apps/web/ui/analytics/analytics-area-chart.tsx
@@ -8,11 +8,15 @@ import TimeSeriesChart from "../charts/time-series-chart";
import XAxis from "../charts/x-axis";
import YAxis from "../charts/y-axis";
-export default function ClicksChart() {
+export default function AnalyticsAreaChart({
+ show,
+}: {
+ show: ("clicks" | "leads" | "sales")[];
+}) {
const { baseApiPath, queryString, interval } = useContext(AnalyticsContext);
const { data } = useSWR<{ start: Date; clicks: number }[]>(
- `${baseApiPath}/timeseries?${queryString}`,
+ `${baseApiPath}/clicks/timeseries?${queryString}`,
fetcher,
);
@@ -20,7 +24,7 @@ export default function ClicksChart() {
() =>
data?.map(({ start, clicks }) => ({
date: new Date(start),
- values: { clicks },
+ values: { clicks, leads: clicks, sales: clicks }, // TODO: Update these accessors once we have leads and sales data
})) ?? null,
[data],
);
@@ -52,21 +56,44 @@ export default function ClicksChart() {
[interval],
);
+ const series = [
+ {
+ id: "clicks",
+ valueAccessor: (d) => d.values.clicks,
+ isActive: show.includes("clicks"),
+ },
+ {
+ id: "leads",
+ valueAccessor: (d) => d.values.leads,
+ isActive: show.includes("leads"),
+ },
+ {
+ id: "sales",
+ valueAccessor: (d) => d.values.sales,
+ isActive: show.includes("sales"),
+ },
+ ];
+
return (
<div className="flex h-96 w-full items-center justify-center">
{chartData ? (
<TimeSeriesChart
key={queryString}
data={chartData}
- series={[{ id: "clicks", valueAccessor: (d) => d.values.clicks }]}
+ series={series}
tooltipContent={(d) => (
<>
- <p className="text-gray-700">
- <strong className="text-gray-800">
- {nFormatter(d.values.clicks, { full: true })}
- </strong>{" "}
- clicks
- </p>
+ {show.map((resource) => {
+ const value = d.values[resource];
+ return (
+ <p className="text-gray-700">
+ <strong className="text-gray-800">
+ {nFormatter(value, { full: true })}
+ </strong>{" "}
+ {value === 1 ? resource.slice(0, -1) : resource}
+ </p>
+ );
+ })}
<p className="text-sm text-gray-500">{formatDate(d.date)}</p>
</>
)}
diff --git a/apps/web/ui/analytics/bar-chart.module.css b/apps/web/ui/analytics/bar-chart.module.css
deleted file mode 100644
index 65a82adc3d..0000000000
--- a/apps/web/ui/analytics/bar-chart.module.css
+++ /dev/null
@@ -1,21 +0,0 @@
-.tooltip {
- z-index: 40;
- width: 200px;
- padding: 1rem !important;
- border-radius: 5px !important;
- box-shadow: rgba(0, 0, 0, 0.24) 0px 3px 8px !important;
-}
-
-.tooltip::after {
- content: "";
- position: absolute;
- width: 0px;
- height: 0px;
- margin: auto;
-
- border: 7px solid transparent;
- border-top-color: white;
-
- top: 100%;
- left: 95px;
-}
diff --git a/apps/web/ui/analytics/bar-chart.tsx b/apps/web/ui/analytics/bar-chart.tsx
deleted file mode 100644
index f564f9def7..0000000000
--- a/apps/web/ui/analytics/bar-chart.tsx
+++ /dev/null
@@ -1,258 +0,0 @@
-import { LoadingSpinner, useMediaQuery } from "@dub/ui";
-import { fetcher, nFormatter } from "@dub/utils";
-import { AxisBottom, AxisLeft } from "@visx/axis";
-import { localPoint } from "@visx/event";
-import { GridRows } from "@visx/grid";
-import { scaleBand, scaleLinear } from "@visx/scale";
-import { useTooltip, useTooltipInPortal } from "@visx/tooltip";
-import { motion } from "framer-motion";
-import { useCallback, useContext, useMemo } from "react";
-import useSWR from "swr";
-import { AnalyticsContext } from ".";
-import styles from "./bar-chart.module.css";
-
-const LEFT_AXIS_WIDTH = 30;
-const CHART_MAX_HEIGHT = 400;
-const CHART_MAX_WIDTH = 800;
-
-type TooltipData = {
- start: Date;
- end: Date;
- clicks: number;
- link: string;
-};
-
-const rangeFormatter = (maxN: number): number => {
- if (maxN < 5) return 5;
- /**
- * Get the max range for a chart based on the maxN value
- */
- return Math.ceil(maxN / 5) * 5;
-};
-
-export default function BarChart() {
- const { baseApiPath, queryString, interval } = useContext(AnalyticsContext);
-
- const { data } = useSWR<{ start: Date; clicks: number }[]>(
- `${baseApiPath}/timeseries?${queryString}`,
- fetcher,
- );
-
- const { width: screenWidth } = useMediaQuery();
-
- const [CHART_WIDTH, CHART_HEIGHT] = useMemo(() => {
- const width = screenWidth
- ? Math.min(screenWidth * 0.8, CHART_MAX_WIDTH)
- : CHART_MAX_WIDTH;
- const height = screenWidth
- ? Math.min(screenWidth * 0.5, CHART_MAX_HEIGHT)
- : CHART_MAX_HEIGHT;
- return [width, height];
- }, [screenWidth]);
-
- const xScale = useMemo(() => {
- return scaleBand({
- range: [0, CHART_WIDTH],
- domain: data ? data.map((d) => d.start) : [],
- padding: 0.4,
- });
- }, [data, interval]);
-
- const yScale = useMemo(() => {
- return scaleLinear({
- range: [CHART_HEIGHT, 0],
- domain: [
- 0,
- data ? rangeFormatter(Math.max(...data.map((d) => d.clicks))) : 0,
- ],
- nice: true,
- round: true,
- });
- }, [data, interval]);
-
- const formatTimestamp = useCallback(
- (e: Date) => {
- switch (interval) {
- case "1h":
- return new Date(e).toLocaleTimeString("en-us", {
- hour: "numeric",
- minute: "numeric",
- });
- case "24h":
- return new Date(e)
- .toLocaleDateString("en-us", {
- month: "short",
- day: "numeric",
- hour: "numeric",
- })
- .replace(",", " ");
- case "90d":
- case "all":
- return new Date(e).toLocaleDateString("en-us", {
- month: "short",
- year: "numeric",
- });
- default:
- return new Date(e).toLocaleDateString("en-us", {
- month: "short",
- day: "numeric",
- });
- }
- },
- [data, interval],
- );
- const {
- tooltipOpen,
- tooltipLeft,
- tooltipTop,
- tooltipData,
- hideTooltip,
- showTooltip,
- } = useTooltip<TooltipData>();
-
- const { containerRef, TooltipInPortal } = useTooltipInPortal({
- // TooltipInPortal is rendered in a separate child of <body /> and positioned
- // with page coordinates which should be updated on scroll. consider using
- // Tooltip or TooltipWithBounds if you don't need to render inside a Portal
- scroll: true,
- debounce: 100, // to avoid a weird tooltip flickering bug
- });
-
- let tooltipTimeout: number | undefined;
- return (
- <figure
- className={`
- ${
- data && data.length > 0 ? "" : "items-center justify-center"
- } my-10 flex`}
- style={{ width: CHART_WIDTH, height: CHART_HEIGHT }}
- >
- {data && data.length > 0 ? (
- <>
- <svg ref={containerRef} width={LEFT_AXIS_WIDTH}>
- <AxisLeft
- hideAxisLine
- hideTicks
- left={8}
- numTicks={4}
- scale={yScale}
- tickFormat={(d) => nFormatter(d as number)}
- tickLabelProps={() => ({
- fill: "#666666",
- filter: data ? "none" : "blur(8px)",
- fontSize: 14,
- textAnchor: "start",
- transition: "all 0.4s ease-in-out",
- })}
- />
- </svg>
- <svg
- className="overflow-visible"
- height={CHART_HEIGHT}
- width={`calc(100% - ${LEFT_AXIS_WIDTH}px)`}
- >
- <AxisBottom
- hideAxisLine
- hideTicks
- scale={xScale}
- tickFormat={formatTimestamp}
- tickLabelProps={() => ({
- fill: "#666666",
- filter: data ? "none" : "blur(8px)",
- fontSize: 12,
- textAnchor: "middle",
- transition: "all 0.4s ease-in-out",
- })}
- numTicks={6}
- top={CHART_HEIGHT - 5}
- />
- <GridRows
- numTicks={5}
- scale={yScale}
- stroke="#E1E1E1"
- width={CHART_WIDTH}
- />
- {data.map(({ start, clicks }, idx) => {
- const barWidth = xScale.bandwidth();
- const barHeight = CHART_HEIGHT - (yScale(clicks) ?? 0);
- const barX = xScale(start) ?? 0;
- const barY = CHART_HEIGHT - barHeight;
- return (
- <motion.rect
- key={`bar-${interval}-${start}`}
- transition={{ ease: "easeOut", duration: 0.3 }}
- className="!origin-bottom fill-[#2563eb]"
- initial={{ transform: "scaleY(0)" }}
- animate={{ transform: "scaleY(1)" }}
- x={barX}
- y={barY}
- width={barWidth}
- height={barHeight}
- onMouseLeave={() => {
- tooltipTimeout = window.setTimeout(() => {
- hideTooltip();
- }, 300);
- }}
- onMouseMove={(event) => {
- if (tooltipTimeout) clearTimeout(tooltipTimeout);
- // TooltipInPortal expects coordinates to be relative to containerRef
- // localPoint returns coordinates relative to the nearest SVG, which
- // is what containerRef is set to in this example.
- const eventSvgCoords = localPoint(event) ?? {
- x: 0,
- y: 0,
- };
- const left = barX + barWidth / 2 - 81;
- showTooltip({
- tooltipData: {
- start,
- end: data[idx + 1]?.start ?? new Date(),
- clicks,
- link: "https://google.com",
- },
- tooltipTop: eventSvgCoords.y - 150,
- tooltipLeft: left,
- });
- }}
- />
- );
- })}
- </svg>
- {tooltipOpen && tooltipData && (
- <TooltipInPortal
- top={tooltipTop}
- left={tooltipLeft}
- className={styles.tooltip}
- >
- {
- (
- <div className="text-center">
- <h3 className="my-1 text-black">
- <span className="text-2xl font-semibold">
- {nFormatter(tooltipData.clicks)}
- </span>{" "}
- click{tooltipData.clicks === 1 ? "" : "s"}
- </h3>
- <p className="text-xs text-gray-600">
- {formatTimestamp(tooltipData.start)} -{" "}
- {interval === "24h"
- ? new Date(tooltipData.end).toLocaleTimeString(
- "en-us",
- {
- hour: "numeric",
- },
- )
- : formatTimestamp(tooltipData.end)}
- </p>
- </div>
- ) as any
- }
- </TooltipInPortal>
- )}
- </>
- ) : (
- <LoadingSpinner />
- )}
- </figure>
- );
-}
diff --git a/apps/web/ui/analytics/devices.tsx b/apps/web/ui/analytics/devices.tsx
index 0c70dd1fdf..03f4690cee 100644
--- a/apps/web/ui/analytics/devices.tsx
+++ b/apps/web/ui/analytics/devices.tsx
@@ -22,7 +22,7 @@ export default function Devices() {
({
[key in DeviceTabs]: string;
} & { clicks: number })[]
- >(`${baseApiPath}/${tab}?${queryString}`, fetcher);
+ >(`${baseApiPath}/clicks/${tab}?${queryString}`, fetcher);
const { queryParams } = useRouterStuff();
const [showModal, setShowModal] = useState(false);
diff --git a/apps/web/ui/analytics/index.tsx b/apps/web/ui/analytics/index.tsx
index e71f302101..7762589fc9 100644
--- a/apps/web/ui/analytics/index.tsx
+++ b/apps/web/ui/analytics/index.tsx
@@ -11,9 +11,9 @@ import { fetcher } from "@dub/utils";
import { useParams, usePathname, useSearchParams } from "next/navigation";
import { createContext, useMemo } from "react";
import useSWR from "swr";
-import Clicks from "./clicks";
import Devices from "./devices";
import Locations from "./locations";
+import Main from "./main";
import Referer from "./referer";
import Toggle from "./toggle";
import TopLinks from "./top-links";
@@ -66,20 +66,20 @@ export default function Analytics({
if (admin) {
return {
basePath: `/analytics`,
- baseApiPath: `/api/analytics/admin/clicks`,
+ baseApiPath: `/api/analytics/admin`,
domain: domainSlug,
};
} else if (slug) {
return {
basePath: `/${slug}/analytics`,
- baseApiPath: `/api/analytics/clicks`,
+ baseApiPath: `/api/analytics`,
domain: domainSlug,
};
} else {
// Public stats page, e.g. dub.co/stats/github, stey.me/stats/weathergpt
return {
basePath: `/stats/${key}`,
- baseApiPath: "/api/analytics/edge/clicks",
+ baseApiPath: "/api/analytics/edge",
domain: staticDomain,
};
}
@@ -106,7 +106,7 @@ export default function Analytics({
}, [id, domain, key, searchParams, interval, tagId]);
const { data: totalClicks } = useSWR<number>(
- `${baseApiPath}/count?${queryString}`,
+ `${baseApiPath}/clicks/count?${queryString}`,
fetcher,
);
@@ -130,7 +130,7 @@ export default function Analytics({
<div className="bg-gray-50 py-10">
<Toggle />
<div className="mx-auto grid max-w-4xl gap-5">
- <Clicks />
+ <Main />
<div className="grid grid-cols-1 gap-5 md:grid-cols-2">
<Locations />
{!isPublicStatsPage && <TopLinks />}
diff --git a/apps/web/ui/analytics/locations.tsx b/apps/web/ui/analytics/locations.tsx
index 9a78e2ca61..2c201ff06d 100644
--- a/apps/web/ui/analytics/locations.tsx
+++ b/apps/web/ui/analytics/locations.tsx
@@ -18,7 +18,7 @@ export default function Locations() {
const { baseApiPath, queryString } = useContext(AnalyticsContext);
const { data } = useSWR<{ country: string; city: string; clicks: number }[]>(
- `${baseApiPath}/${tab}?${queryString}`,
+ `${baseApiPath}/clicks/${tab}?${queryString}`,
fetcher,
);
diff --git a/apps/web/ui/analytics/clicks.tsx b/apps/web/ui/analytics/main.tsx
similarity index 58%
rename from apps/web/ui/analytics/clicks.tsx
rename to apps/web/ui/analytics/main.tsx
index 6041e79e27..b0453a8080 100644
--- a/apps/web/ui/analytics/clicks.tsx
+++ b/apps/web/ui/analytics/main.tsx
@@ -1,16 +1,36 @@
import { VALID_ANALYTICS_FILTERS } from "@/lib/analytics/constants";
import useTags from "@/lib/swr/use-tags";
-import { Chart } from "@/ui/shared/icons";
import { CountingNumbers, NumberTooltip, useRouterStuff } from "@dub/ui";
-import { COUNTRIES, capitalize, linkConstructor, truncate } from "@dub/utils";
-import { X } from "lucide-react";
+import {
+ COUNTRIES,
+ capitalize,
+ cn,
+ linkConstructor,
+ truncate,
+} from "@dub/utils";
+import { AnimatePresence, motion } from "framer-motion";
+import {
+ Crosshair,
+ LucideIcon,
+ MousePointerClick,
+ Receipt,
+ X,
+} from "lucide-react";
import Link from "next/link";
import { useSearchParams } from "next/navigation";
-import { useContext } from "react";
+import { useContext, useMemo } from "react";
import { AnalyticsContext } from ".";
-import ClicksChart from "./clicks-chart";
+import AnalyticsAreaChart from "./analytics-area-chart";
-export default function Clicks() {
+type Tab = {
+ id: string;
+ icon: LucideIcon;
+ label: string;
+ resource: "clicks" | "leads" | "sales";
+};
+
+export default function Main() {
+ const { betaTester } = { betaTester: true }; //useWorkspace();
const { totalClicks } = useContext(AnalyticsContext);
const searchParams = useSearchParams();
const domain = searchParams.get("domain");
@@ -24,30 +44,75 @@ export default function Clicks() {
// Root domain related
const root = searchParams.get("root");
+ const tabs = useMemo(
+ () =>
+ [
+ {
+ id: "clicks",
+ icon: MousePointerClick,
+ label: "Clicks",
+ resource: "clicks",
+ },
+ ...(betaTester
+ ? [
+ {
+ id: "leads",
+ icon: Crosshair,
+ label: "Leads",
+ resource: "leads",
+ },
+ { id: "sales", icon: Receipt, label: "Sales", resource: "sales" },
+ ]
+ : []),
+ ] as Tab[],
+ [betaTester],
+ );
+
+ const tab =
+ tabs.find(({ id }) => id === (searchParams.get("tab") || "clicks")) ||
+ tabs[0];
+
return (
- <div className="max-w-4xl overflow-hidden border border-gray-200 bg-white p-5 sm:rounded-xl sm:p-10">
- <div className="mb-5 flex items-start justify-between space-x-4">
- <div className="flex-none">
- <div className="flex items-end space-x-1">
- {totalClicks || totalClicks === 0 ? (
- <NumberTooltip value={totalClicks}>
- <CountingNumbers
- as="h1"
- className="text-3xl font-bold sm:text-4xl"
- >
- {totalClicks}
- </CountingNumbers>
- </NumberTooltip>
- ) : (
- <div className="h-10 w-12 animate-pulse rounded-md bg-gray-200" />
- )}
- <Chart className="mb-1 h-6 w-6 text-gray-600" />
+ <div className="max-w-4xl overflow-hidden border border-gray-200 bg-white sm:rounded-xl">
+ <div className="scrollbar-hide mb-5 flex w-full divide-x overflow-x-scroll border-b border-gray-200">
+ {tabs.map(({ id, icon: Icon, label }) => (
+ <div>
+ <Link
+ key={id}
+ className={cn(
+ "block h-full min-w-[120px] flex-none border-black px-4 py-3 sm:min-w-[180px] sm:px-8 sm:py-6",
+ "transition-all duration-100 hover:bg-gray-50 active:bg-gray-100",
+ tab.id === id ? "border-b-2" : "border-b-none",
+ )}
+ href={
+ queryParams({
+ set: {
+ tab: id,
+ },
+ getNewPath: true,
+ }) as string
+ }
+ >
+ <div className="flex items-end gap-3">
+ {totalClicks || totalClicks === 0 ? (
+ <NumberTooltip value={totalClicks}>
+ <CountingNumbers
+ as="h1"
+ className="text-3xl font-bold sm:text-4xl"
+ >
+ {totalClicks}
+ </CountingNumbers>
+ </NumberTooltip>
+ ) : (
+ <div className="h-10 w-12 animate-pulse rounded-md bg-gray-200" />
+ )}
+ <Icon className="mb-2 h-4 w-4 text-gray-600" />
+ </div>
+ <p className="mt-1 text-sm uppercase text-gray-600">{label}</p>
+ </Link>
</div>
- <p className="text-sm font-medium uppercase text-gray-600">
- Total Clicks
- </p>
- </div>
- <div className="flex flex-wrap items-center justify-end gap-2">
+ ))}
+ <div className="flex flex-wrap items-center justify-end gap-2 p-5 sm:p-10">
{domain &&
(key ? (
<Link
@@ -142,7 +207,17 @@ export default function Clicks() {
})}
</div>
</div>
- <ClicksChart />
+ <div className="p-5 sm:p-10">
+ <AnimatePresence>
+ <motion.div
+ key={tab.id}
+ initial={{ opacity: 0, y: 6 }}
+ animate={{ opacity: 1, y: 0 }}
+ >
+ <AnalyticsAreaChart show={[tab.resource]} />
+ </motion.div>
+ </AnimatePresence>
+ </div>
</div>
);
}
diff --git a/apps/web/ui/analytics/referer.tsx b/apps/web/ui/analytics/referer.tsx
index 846b41bc23..0cce1ad105 100644
--- a/apps/web/ui/analytics/referer.tsx
+++ b/apps/web/ui/analytics/referer.tsx
@@ -10,7 +10,7 @@ export default function Referer() {
const { baseApiPath, queryString } = useContext(AnalyticsContext);
const { data } = useSWR<{ referer: string; clicks: number }[]>(
- `${baseApiPath}/referers?${queryString}`,
+ `${baseApiPath}/clicks/referers?${queryString}`,
fetcher,
);
diff --git a/apps/web/ui/analytics/top-links.tsx b/apps/web/ui/analytics/top-links.tsx
index b2d313d810..743378bc95 100644
--- a/apps/web/ui/analytics/top-links.tsx
+++ b/apps/web/ui/analytics/top-links.tsx
@@ -27,7 +27,7 @@ export default function TopLinks() {
({ domain: string; key: string } & {
[key in TopLinksTabs]: string;
} & { clicks: number })[]
- >(`${baseApiPath}/top_${tab}s?${queryString}`, fetcher);
+ >(`${baseApiPath}/clicks/top_${tab}s?${queryString}`, fetcher);
const { queryParams } = useRouterStuff();
const searchParams = useSearchParams();