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.

Area chart WIP

Tim Wilson343501c1be86
diff --git a/apps/web/package.json b/apps/web/package.json
index 0160d61f38..76d5e0303f 100644
--- a/apps/web/package.json
+++ b/apps/web/package.json
@@ -35,7 +35,9 @@
"@visx/axis": "^2.14.0",
"@visx/event": "^2.6.0",
"@visx/geo": "^2.10.0",
+ "@visx/gradient": "^3.3.0",
"@visx/grid": "^2.12.2",
+ "@visx/group": "^3.3.0",
"@visx/responsive": "^2.10.0",
"@visx/scale": "^3.3.0",
"@visx/shape": "^2.12.2",
@@ -46,6 +48,7 @@
"cobe": "^0.6.3",
"concurrently": "^8.0.1",
"crisp-sdk-web": "^1.0.19",
+ "d3-array": "^3.2.4",
"framer-motion": "^10.16.16",
"fuse.js": "^6.6.2",
"github-slugger": "^2.0.0",
diff --git a/apps/web/ui/analytics/clicks.tsx b/apps/web/ui/analytics/clicks.tsx
index 559747ed59..51467a5bf0 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 BarChart from "./bar-chart";
+import AreaChart from "../charts/area-chart";
export default function Clicks() {
const { totalClicks } = useContext(AnalyticsContext);
@@ -101,7 +101,23 @@ export default function Clicks() {
})}
</div>
</div>
- <BarChart />
+ {/* <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>
</div>
);
}
diff --git a/apps/web/ui/charts/area-chart.tsx b/apps/web/ui/charts/area-chart.tsx
new file mode 100644
index 0000000000..4f9e8d81da
--- /dev/null
+++ b/apps/web/ui/charts/area-chart.tsx
@@ -0,0 +1,185 @@
+import { AxisBottom } from "@visx/axis";
+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 { ChartContext, Datum } from "./types";
+
+const ChartContext = createContext<ChartContext | null>(null);
+
+function useChartContext<T extends Datum>(): ChartContext<T> {
+ const chartContext = useContext(ChartContext);
+ if (!chartContext) throw new Error("No chart context");
+ return chartContext;
+}
+
+export default function AreaChart<T extends Datum>(props: ChartContext<T>) {
+ return (
+ <ChartContext.Provider value={props}>
+ <ParentSize>
+ {({ width, height }) => {
+ return <AreaChartInner {...props} width={width} height={height} />;
+ }}
+ </ParentSize>
+ </ChartContext.Provider>
+ );
+}
+
+function AreaChartInner<T extends Datum>({
+ width: outerWidth,
+ height: outerHeight,
+}: {
+ width: number;
+ height: number;
+}) {
+ const chartContext = useChartContext<T>();
+ const {
+ data,
+ series,
+ startDate,
+ endDate,
+ tickFormat = (date) =>
+ date.toLocaleDateString("en-US", { month: "short", day: "numeric" }),
+ tooltipContent,
+ margin = {
+ top: 2,
+ right: 3,
+ bottom: 32,
+ left: 3,
+ },
+ padding = {
+ top: 0.1,
+ bottom: 0.1,
+ },
+ xIntervalEveryCount = 1,
+ } = chartContext;
+
+ const width = outerWidth - margin.left - margin.right;
+ const height = outerHeight - margin.top - margin.bottom;
+
+ // Find min and max y values for all series
+ const { minY, maxY } = useMemo(() => {
+ const values = series
+ .filter(({ isActive }) => isActive !== false)
+ .map(({ accessorFn }) => data.map((d) => accessorFn(d)))
+ .flat()
+ .filter((v): v is number => v != null);
+
+ const minY = Math.min(...values);
+ const maxY = Math.max(...values);
+
+ const range = maxY - minY;
+
+ return {
+ minY: minY - range * (padding.bottom ?? 0),
+ maxY: maxY + range * (padding.top ?? 0),
+ };
+ }, [data, series, padding?.bottom, padding?.top]);
+
+ const { yScale, xScale } = useMemo(() => {
+ return {
+ yScale: scaleLinear<number>({
+ domain: [minY, maxY],
+ range: [height, 0],
+ nice: true,
+ clamp: true,
+ }),
+ xScale: scaleUtc<number>({
+ domain: [startDate, endDate],
+ range: [0, width],
+ }),
+ };
+ }, [startDate, endDate, minY, maxY, height, width, margin]);
+
+ return (
+ <>
+ <svg width={outerWidth} height={outerHeight}>
+ <Group left={margin.left}>
+ <Group
+ top={margin.top}
+ // onTouchStart={handleTooltip}
+ // onTouchMove={handleTooltip}
+ // onMouseMove={handleTooltip}
+ // onMouseLeave={hideTooltip}
+ >
+ {series.map((s) => (
+ <>
+ <LinearGradient
+ className="text-blue-500"
+ id={`${s.id}-background`}
+ fromOffset="20%"
+ from="currentColor"
+ fromOpacity={0.01}
+ to="currentColor"
+ toOpacity={0.2}
+ x={0}
+ y1={1}
+ />
+ {/* Area */}
+ <AreaClosed
+ data={data}
+ x={(d) => xScale(d.date)}
+ y={(d) => yScale(s.accessorFn(d) ?? 0)}
+ yScale={yScale}
+ fill={`url(#${s.id}-background)`}
+ />
+
+ {/* Line */}
+ <Area
+ data={data}
+ x={(d) => xScale(d.date)}
+ y={(d) => yScale(s.accessorFn(d) ?? 0)}
+ className="text-blue-800"
+ 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"
+ />
+ </>
+ ))}
+
+ {/* Vertical grid lines */}
+ {data.length > 0 &&
+ data
+ .filter((_, idx) => idx % xIntervalEveryCount === 0)
+ .map((d, idx, { length }) => (
+ <Line
+ x1={xScale(d.date)}
+ x2={xScale(d.date)}
+ y1={height}
+ y2={0}
+ stroke="#00000026"
+ strokeWidth={1}
+ strokeDasharray={idx !== length - 1 ? 5 : 0}
+ />
+ ))}
+ </Group>
+ <AxisBottom
+ top={margin.top + height}
+ scale={xScale}
+ tickValues={data.map(({ date }) => date)}
+ hideTicks
+ stroke="#00000026"
+ tickFormat={(date) => tickFormat(date as Date)}
+ tickLabelProps={(_, idx, { length }) => ({
+ textAnchor:
+ idx === 0 ? "start" : idx === length - 1 ? "end" : "middle",
+ fontSize: 12,
+ fill: idx === length - 1 ? "#000" : "#00000066",
+ })}
+ />
+ </Group>
+ </svg>
+ </>
+ );
+}
diff --git a/apps/web/ui/charts/types.ts b/apps/web/ui/charts/types.ts
new file mode 100644
index 0000000000..b7e807232c
--- /dev/null
+++ b/apps/web/ui/charts/types.ts
@@ -0,0 +1,54 @@
+import { ReactElement } from "react";
+
+export type Datum = Record<string, any>;
+
+export type TimeSeriesDatum<T extends Datum = any> = {
+ date: Date;
+ values: T;
+};
+
+export type AccessorFn<T extends Datum, TValue = number> = (
+ datum: TimeSeriesDatum<T>,
+) => TValue;
+
+export type Series<T extends Datum = any, TValue = number> = {
+ id: string;
+ isActive?: boolean;
+ accessorFn: AccessorFn<T, TValue>;
+ color?: string | AccessorFn<T, string>;
+};
+
+export type Data<T extends Datum> = TimeSeriesDatum<T>[];
+
+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;
+
+ /**
+ * Absolute pixel values for margins around the chart area.
+ * Default values accommodate axis labels and other expected overflow.
+ */
+ margin?: {
+ top: number;
+ right: number;
+ bottom: number;
+ left: number;
+ };
+
+ /**
+ * Decimal percentages for padding above and below highest and lowest y-values
+ */
+ padding?: {
+ top: number;
+ bottom: number;
+ };
+
+ xIntervalEveryCount?: number;
+};
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 9e82e1d646..b09022e4d1 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -106,9 +106,15 @@ importers:
'@visx/geo':
specifier: ^2.10.0
version: 2.10.0([email protected])
+ '@visx/gradient':
+ specifier: ^3.3.0
+ version: 3.3.0([email protected])
'@visx/grid':
specifier: ^2.12.2
version: 2.12.2([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])
@@ -139,6 +145,9 @@ importers:
crisp-sdk-web:
specifier: ^1.0.19
version: 1.0.19
+ d3-array:
+ specifier: ^3.2.4
+ version: 3.2.4
framer-motion:
specifier: ^10.16.16
@@ -7109,6 +7118,16 @@ packages:
react: 18.2.0
dev: false
+ resolution: {integrity: sha512-t3vqukahDQsJ64/fcm85woFm2XPpSPMBz92gFvaY4J8EJY3e6rFOg382v5Dm17fgNsLRKJA0Vqo7mUtDe2pWOw==}
+ peerDependencies:
+ react: ^16.0.0-0 || ^17.0.0-0 || ^18.0.0-0
+ dependencies:
+ '@types/react': 18.2.48
+ prop-types: 15.8.1
+ react: 18.2.0
+ dev: false
+
resolution: {integrity: sha512-lyMQvq5afjOh0nRqF0OBjgsLfsgUeLcFc95oj0FJ/NJ/MvtI6Gd5BxxbmYzuVfZ4f0Dm1pvtBu1swoB3451tkg==}
peerDependencies:
@@ -7136,6 +7155,17 @@ packages:
react: 18.2.0
dev: false
+ resolution: {integrity: sha512-yKepDKwJqlzvnvPS0yDuW13XNrYJE4xzT6xM7J++441nu6IybWWwextyap8ey+kU651cYDb+q1Oi6aHvQwyEyw==}
+ peerDependencies:
+ react: ^16.0.0-0 || ^17.0.0-0 || ^18.0.0-0
+ dependencies:
+ '@types/react': 18.2.48
+ classnames: 2.3.2
+ prop-types: 15.8.1
+ react: 18.2.0
+ dev: false
+
resolution: {integrity: sha512-amBi7yMz4S2VSchlPdliznN41TuES64506ySI22DeKQ+mc1s1+BudlpnY90sM1EIw4xnqbKmrghTTGfy6SVqvQ==}
dev: false
@@ -8437,6 +8467,13 @@ packages:
internmap: 2.0.3
dev: false
+ resolution: {integrity: sha512-tdQAmyA18i4J7wprpYq8ClcxZy3SC31QMeByyCFyRt7BVHdREQZ5lpzoe5mFEYZUWe+oq8HBvk9JjpibyEV4Jg==}
+ engines: {node: '>=12'}
+ dependencies:
+ internmap: 2.0.3
+ dev: false
+
resolution: {integrity: sha512-p2sTHSLCJI2QKunbGb7ocOh7DgTAn8IrLx21QRc/BSnodXM4sv6aLQlnfpvehFMLZEfBc6g9pH9SWQccFYfJ9Q==}
dev: false
@@ -8499,7 +8536,7 @@ packages:
resolution: {integrity: sha512-GZW464g1SH7ag3Y7hXjf8RoUuAFIqklOAq3MRl4OaWabTFJY9PN/E1YklhXLh+OQ3fM9yS2nOkCoS+WLZ6kvxQ==}
engines: {node: '>=12'}
dependencies:
- d3-array: 3.2.1
+ d3-array: 3.2.4
d3-format: 3.1.0
d3-interpolate: 3.0.1
d3-time: 3.1.0
@@ -8535,7 +8572,7 @@ packages:
resolution: {integrity: sha512-VqKjzBLejbSMT4IgbmVgDjpkYrNWUYJnbCGo874u7MMKIWsILRX+OpX/gTk8MqjpT1A/c6HY2dCA77ZN0lkQ2Q==}
engines: {node: '>=12'}
dependencies:
- d3-array: 3.2.1
+ d3-array: 3.2.4
dev: false
@@ -12960,7 +12997,7 @@ packages:
optional: true
dependencies:
prettier: 3.2.5
- prettier-plugin-organize-imports: 3.2.4([email protected])([email protected])
+ prettier-plugin-organize-imports: 3.2.4([email protected])([email protected])
dev: true