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.

Flesh out area chart

Tim Wilsona5288dfe1abf
diff --git a/apps/web/ui/analytics/clicks-chart.tsx b/apps/web/ui/analytics/clicks-chart.tsx
new file mode 100644
index 0000000000..f581cae8d4
--- /dev/null
+++ b/apps/web/ui/analytics/clicks-chart.tsx
@@ -0,0 +1,49 @@
+import { fetcher } from "@dub/utils";
+import { useContext, useMemo } from "react";
+import useSWR from "swr";
+import { AnalyticsContext } from ".";
+import AreaChart from "../charts/area-chart";
+
+export default function ClicksChart() {
+ const { baseApiPath, queryString /* interval */ } =
+ useContext(AnalyticsContext);
+
+ const { data } = useSWR<{ start: Date; clicks: number }[]>(
+ `${baseApiPath}/timeseries?${queryString}`,
+ fetcher,
+ );
+
+ const chartData = useMemo(
+ () =>
+ data?.map(({ start, clicks }) => ({
+ date: new Date(start),
+ values: { clicks },
+ })) ?? null,
+ [data],
+ );
+
+ return (
+ <div className="h-72 w-full">
+ {chartData !== null && (
+ <AreaChart
+ data={chartData}
+ series={[{ id: "clicks", accessorFn: (d) => d.values.clicks }]}
+ tooltipContent={(d) => (
+ <>
+ <p className="text-gray-600">
+ <strong className="text-gray-700">{d.values.clicks}</strong>{" "}
+ clicks
+ </p>
+ <p className="text-sm text-gray-400">
+ {d.date.toLocaleDateString("en-US", {
+ month: "short",
+ day: "numeric",
+ })}
+ </p>
+ </>
+ )}
+ />
+ )}
+ </div>
+ );
+}
diff --git a/apps/web/ui/analytics/clicks.tsx b/apps/web/ui/analytics/clicks.tsx
index 51467a5bf0..c870f18098 100644
--- a/apps/web/ui/analytics/clicks.tsx
+++ b/apps/web/ui/analytics/clicks.tsx
@@ -13,7 +13,7 @@ import Link from "next/link";
import { useSearchParams } from "next/navigation";
import { useContext } from "react";
import { AnalyticsContext } from ".";
-import AreaChart from "../charts/area-chart";
+import ClicksChart from "./clicks-chart";
export default function Clicks() {
const { totalClicks } = useContext(AnalyticsContext);
@@ -101,23 +101,7 @@ export default function Clicks() {
})}
</div>
</div>
- {/* <BarChart /> */}
- <div className="h-72 w-full">
- <AreaChart
- data={[
- { date: new Date("2024-02-25"), values: { clicks: 20 } },
- { date: new Date("2024-02-26"), values: { clicks: 17 } },
- { date: new Date("2024-02-27"), values: { clicks: 23 } },
- { date: new Date("2024-02-28"), values: { clicks: 20 } },
- { date: new Date("2024-02-29"), values: { clicks: 25 } },
- { date: new Date("2024-03-01"), values: { clicks: 35 } },
- { date: new Date("2024-03-02"), values: { clicks: 30 } },
- ]}
- series={[{ id: "clicks", accessorFn: (d) => d.values.clicks }]}
- startDate={new Date("2024-02-25")}
- endDate={new Date("2024-03-02")}
- />
- </div>
+ <ClicksChart />
</div>
);
}
diff --git a/apps/web/ui/charts/area-chart.tsx b/apps/web/ui/charts/area-chart.tsx
index 4f9e8d81da..92fd0fdf59 100644
--- a/apps/web/ui/charts/area-chart.tsx
+++ b/apps/web/ui/charts/area-chart.tsx
@@ -3,9 +3,10 @@ import { LinearGradient } from "@visx/gradient";
import { Group } from "@visx/group";
import { ParentSize } from "@visx/responsive";
import { scaleLinear, scaleUtc } from "@visx/scale";
-import { Area, AreaClosed, Circle, Line } from "@visx/shape";
-import { createContext, useContext, useMemo } from "react";
+import { Area, AreaClosed, Bar, Circle, Line } from "@visx/shape";
+import { Fragment, createContext, useContext, useMemo } from "react";
import { ChartContext, Datum } from "./types";
+import { useTooltip } from "./useTooltip";
const ChartContext = createContext<ChartContext | null>(null);
@@ -15,31 +16,32 @@ function useChartContext<T extends Datum>(): ChartContext<T> {
return chartContext;
}
-export default function AreaChart<T extends Datum>(props: ChartContext<T>) {
+type AreaChartProps<T extends Datum> = Omit<
+ ChartContext<T>,
+ "width" | "height" | "xScale" | "yScale"
+>;
+
+export default function AreaChart<T extends Datum>(props: AreaChartProps<T>) {
return (
- <ChartContext.Provider value={props}>
- <ParentSize>
- {({ width, height }) => {
- return <AreaChartInner {...props} width={width} height={height} />;
- }}
- </ParentSize>
- </ChartContext.Provider>
+ <ParentSize className="relative">
+ {({ width, height }) => {
+ return <AreaChartInner {...props} width={width} height={height} />;
+ }}
+ </ParentSize>
);
}
function AreaChartInner<T extends Datum>({
width: outerWidth,
height: outerHeight,
+ ...outerProps
}: {
width: number;
height: number;
-}) {
- const chartContext = useChartContext<T>();
+} & AreaChartProps<T>) {
const {
data,
series,
- startDate,
- endDate,
tickFormat = (date) =>
date.toLocaleDateString("en-US", { month: "short", day: "numeric" }),
tooltipContent,
@@ -54,12 +56,21 @@ function AreaChartInner<T extends Datum>({
bottom: 0.1,
},
xIntervalEveryCount = 1,
- } = chartContext;
+ } = outerProps;
const width = outerWidth - margin.left - margin.right;
const height = outerHeight - margin.top - margin.bottom;
- // Find min and max y values for all series
+ const { startDate, endDate } = useMemo(() => {
+ const dates = data.map(({ date }) => date);
+ const times = dates.map((d) => d.getTime());
+
+ return {
+ startDate: dates[times.indexOf(Math.min(...times))],
+ endDate: dates[times.indexOf(Math.max(...times))],
+ };
+ }, data);
+
const { minY, maxY } = useMemo(() => {
const values = series
.filter(({ isActive }) => isActive !== false)
@@ -93,19 +104,27 @@ function AreaChartInner<T extends Datum>({
};
}, [startDate, endDate, minY, maxY, height, width, margin]);
+ const chartContext = { ...outerProps, width, height, xScale, yScale };
+ const {
+ tooltipData,
+ TooltipWrapper,
+ tooltipLeft,
+ tooltipTop,
+ handleTooltip,
+ hideTooltip,
+ containerRef,
+ } = useTooltip({
+ seriesId: series[0].id,
+ chartContext,
+ });
+
return (
- <>
- <svg width={outerWidth} height={outerHeight}>
+ <ChartContext.Provider value={chartContext}>
+ <svg width={outerWidth} height={outerHeight} ref={containerRef}>
<Group left={margin.left}>
- <Group
- top={margin.top}
- // onTouchStart={handleTooltip}
- // onTouchMove={handleTooltip}
- // onMouseMove={handleTooltip}
- // onMouseLeave={hideTooltip}
- >
+ <Group top={margin.top}>
{series.map((s) => (
- <>
+ <Fragment key={s.id}>
<LinearGradient
className="text-blue-500"
id={`${s.id}-background`}
@@ -131,21 +150,23 @@ function AreaChartInner<T extends Datum>({
data={data}
x={(d) => xScale(d.date)}
y={(d) => yScale(s.accessorFn(d) ?? 0)}
- className="text-blue-800"
+ className="text-blue-700"
stroke="currentColor"
strokeOpacity={0.8}
strokeWidth={2}
/>
{/* Latest value dot */}
- <Circle
- cx={xScale(data.at(-1)!.date)}
- cy={yScale(s.accessorFn(data.at(-1)!))}
- r={3}
- className="text-blue-700"
- fill="currentColor"
- />
- </>
+ {!tooltipData && (
+ <Circle
+ cx={xScale(data.at(-1)!.date)}
+ cy={yScale(s.accessorFn(data.at(-1)!))}
+ r={4}
+ className="text-blue-700"
+ fill="currentColor"
+ />
+ )}
+ </Fragment>
))}
{/* Vertical grid lines */}
@@ -154,15 +175,57 @@ function AreaChartInner<T extends Datum>({
.filter((_, idx) => idx % xIntervalEveryCount === 0)
.map((d, idx, { length }) => (
<Line
+ key={d.date.toString()}
x1={xScale(d.date)}
x2={xScale(d.date)}
y1={height}
y2={0}
- stroke="#00000026"
+ stroke={
+ d.date === tooltipData?.date ? "transparent" : "#00000026"
+ }
strokeWidth={1}
strokeDasharray={idx !== length - 1 ? 5 : 0}
/>
))}
+
+ {/* Tooltip hover line + circle */}
+ {tooltipData && (
+ <>
+ <Line
+ x1={xScale(tooltipData.date)}
+ x2={xScale(tooltipData.date)}
+ y1={height}
+ y2={0}
+ strokeOpacity={0.1}
+ stroke="black"
+ strokeWidth={2}
+ />
+
+ {series.map((s) => (
+ <Circle
+ key={s.id}
+ cx={xScale(tooltipData.date)}
+ cy={yScale(s.accessorFn(tooltipData))}
+ r={4}
+ className="text-blue-800"
+ fill="currentColor"
+ />
+ ))}
+ </>
+ )}
+
+ {/* Tooltip hover region */}
+ <Bar
+ x={0}
+ y={0}
+ width={width}
+ height={height}
+ onTouchStart={handleTooltip}
+ onTouchMove={handleTooltip}
+ onMouseMove={handleTooltip}
+ onMouseLeave={hideTooltip}
+ fill="transparent"
+ />
</Group>
<AxisBottom
top={margin.top + height}
@@ -171,15 +234,38 @@ function AreaChartInner<T extends Datum>({
hideTicks
stroke="#00000026"
tickFormat={(date) => tickFormat(date as Date)}
- tickLabelProps={(_, idx, { length }) => ({
+ tickLabelProps={(date, idx, { length }) => ({
+ className: "transition-colors",
textAnchor:
idx === 0 ? "start" : idx === length - 1 ? "end" : "middle",
fontSize: 12,
- fill: idx === length - 1 ? "#000" : "#00000066",
+ fill: (
+ tooltipData ? tooltipData.date === date : idx === length - 1
+ )
+ ? "#000"
+ : "#00000066",
})}
/>
</Group>
</svg>
- </>
+ <div className="pointer-events-none absolute inset-0">
+ {tooltipData && (
+ <TooltipWrapper
+ key={tooltipData.date.toString()}
+ left={(tooltipLeft ?? 0) + margin.left}
+ top={(tooltipTop ?? 0) + margin.top}
+ offsetLeft={8}
+ offsetTop={0}
+ className="absolute"
+ unstyled={true}
+ >
+ <div className="pointer-events-none rounded-md border border-gray-200 bg-white px-4 py-2 text-base shadow-sm">
+ {tooltipContent?.(tooltipData) ??
+ series[0].accessorFn(tooltipData)}
+ </div>
+ </TooltipWrapper>
+ )}
+ </div>
+ </ChartContext.Provider>
);
}
diff --git a/apps/web/ui/charts/types.ts b/apps/web/ui/charts/types.ts
index b7e807232c..7873735195 100644
--- a/apps/web/ui/charts/types.ts
+++ b/apps/web/ui/charts/types.ts
@@ -1,3 +1,4 @@
+import { ScaleTypeToD3Scale } from "@visx/scale";
import { ReactElement } from "react";
export type Datum = Record<string, any>;
@@ -24,9 +25,6 @@ export type ChartContext<T extends Datum = any> = {
data: Data<T>;
series: Series<T>[];
- startDate: Date;
- endDate: Date;
-
tickFormat?: (date: Date) => string;
tooltipContent?: (datum: TimeSeriesDatum<T>) => ReactElement;
@@ -51,4 +49,11 @@ export type ChartContext<T extends Datum = any> = {
};
xIntervalEveryCount?: number;
+
+ // Props determined by AreaChartInner
+
+ width: number;
+ height: number;
+ xScale: ScaleTypeToD3Scale<number>["utc"];
+ yScale: ScaleTypeToD3Scale<number>["linear"];
};
diff --git a/apps/web/ui/charts/useTooltip.ts b/apps/web/ui/charts/useTooltip.ts
new file mode 100644
index 0000000000..13348a789c
--- /dev/null
+++ b/apps/web/ui/charts/useTooltip.ts
@@ -0,0 +1,80 @@
+import { localPoint } from "@visx/event";
+import {
+ TooltipWithBounds,
+ defaultStyles,
+ useTooltipInPortal,
+ useTooltip as useVisxTooltip,
+} from "@visx/tooltip";
+import { bisector } from "d3-array";
+import { useCallback } from "react";
+import { ChartContext, Datum, Series, TimeSeriesDatum } from "./types";
+
+const bisectDate = bisector<Datum, Date>((d) => new Date(d.date)).left;
+
+export type TooltipOptions = {
+ renderInPortal?: boolean;
+ snapToX?: boolean;
+ snapToY?: boolean;
+};
+
+export function useTooltip<T extends Datum>({
+ seriesId,
+ chartContext,
+ renderInPortal = false,
+ snapToY = false,
+ snapToX = true,
+}: {
+ seriesId?: Series["id"];
+ chartContext: ChartContext<T>;
+} & TooltipOptions) {
+ const { series, data, xScale, yScale } = chartContext;
+
+ const visxTooltipInPortal = useTooltipInPortal({
+ scroll: true,
+ detectBounds: true,
+ debounce: 200,
+ });
+
+ const visxTooltip = useVisxTooltip<TimeSeriesDatum<T>>();
+
+ const handleTooltip = useCallback(
+ (
+ event:
+ | React.TouchEvent<SVGRectElement>
+ | React.MouseEvent<SVGRectElement>,
+ ) => {
+ const { x } = localPoint(event) || { x: 0 };
+ const x0 = xScale.invert(x);
+ const index = bisectDate(data, x0, 1);
+ const d0 = data[index - 1];
+ const d1 = data[index];
+ let d = d0;
+ if (d1?.date) {
+ d =
+ x0.valueOf() - d0.date.valueOf() > d1.date.valueOf() - x0.valueOf()
+ ? d1
+ : d0;
+ }
+ visxTooltip.showTooltip({
+ tooltipData: d,
+ tooltipLeft: snapToX ? xScale(d.date) : x,
+ tooltipTop: snapToY
+ ? yScale(series.find((s) => s.id === seriesId)!.accessorFn(d))
+ : 0,
+ });
+ },
+ [seriesId, data, xScale, yScale, series, visxTooltip.showTooltip],
+ );
+
+ const TooltipWrapper = renderInPortal
+ ? visxTooltipInPortal.TooltipInPortal
+ : TooltipWithBounds;
+
+ return {
+ handleTooltip,
+ TooltipWrapper,
+ containerRef: visxTooltipInPortal.containerRef,
+ defaultStyles,
+ ...visxTooltip,
+ };
+}