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.

More refactoring + axis/tick improvements

Tim Wilson9a6b1085a59f
diff --git a/apps/web/package.json b/apps/web/package.json
index 76d5e0303f..7c7472cceb 100644
--- a/apps/web/package.json
+++ b/apps/web/package.json
@@ -41,6 +41,7 @@
"@visx/responsive": "^2.10.0",
"@visx/scale": "^3.3.0",
"@visx/shape": "^2.12.2",
+ "@visx/text": "^3.3.0",
"@visx/tooltip": "^2.16.0",
"bottleneck": "^2.19.5",
"cloudinary": "^1.40.0",
diff --git a/apps/web/ui/analytics/clicks-chart.tsx b/apps/web/ui/analytics/clicks-chart.tsx
index 34eab74ab6..c5af344fa2 100644
--- a/apps/web/ui/analytics/clicks-chart.tsx
+++ b/apps/web/ui/analytics/clicks-chart.tsx
@@ -3,9 +3,9 @@ import { useCallback, useContext, useMemo } from "react";
import useSWR from "swr";
import { AnalyticsContext } from ".";
import Areas from "../charts/areas";
-import GridLines from "../charts/grid-lines";
import TimeSeriesChart from "../charts/time-series-chart";
import XAxis from "../charts/x-axis";
+import YAxis from "../charts/y-axis";
export default function ClicksChart() {
const { baseApiPath, queryString, interval } = useContext(AnalyticsContext);
@@ -42,7 +42,7 @@ export default function ClicksChart() {
);
return (
- <div className="h-72 w-full">
+ <div className="h-80 w-full">
{chartData !== null && (
<TimeSeriesChart
key={queryString}
@@ -58,9 +58,9 @@ export default function ClicksChart() {
</>
)}
>
- <GridLines />
<Areas />
<XAxis tickFormat={dateFormatter} />
+ <YAxis integerTicks showGridLines />
</TimeSeriesChart>
)}
</div>
diff --git a/apps/web/ui/charts/grid-lines.tsx b/apps/web/ui/charts/grid-lines.tsx
deleted file mode 100644
index 66a7b02bfc..0000000000
--- a/apps/web/ui/charts/grid-lines.tsx
+++ /dev/null
@@ -1,32 +0,0 @@
-import { Group } from "@visx/group";
-import { Line } from "@visx/shape";
-import { useChartContext, useChartTooltipContext } from "./chart-context";
-
-export default function GridLines() {
- const { data, endDate, margin, height, xScale, xTickInterval } =
- useChartContext();
-
- const { tooltipData } = useChartTooltipContext();
-
- return (
- <Group left={margin.left} top={margin.top}>
- {data.length > 0 &&
- data
- .filter((_, idx) => idx % xTickInterval === 0)
- .map((d) => (
- <Line
- key={d.date.toString()}
- x1={xScale(d.date)}
- x2={xScale(d.date)}
- y1={height}
- y2={0}
- stroke={
- d.date === tooltipData?.date ? "transparent" : "#00000026"
- }
- strokeWidth={1}
- strokeDasharray={d.date !== endDate ? 5 : 0}
- />
- ))}
- </Group>
- );
-}
diff --git a/apps/web/ui/charts/time-series-chart.tsx b/apps/web/ui/charts/time-series-chart.tsx
index c4e33cc17d..13f8761f23 100644
--- a/apps/web/ui/charts/time-series-chart.tsx
+++ b/apps/web/ui/charts/time-series-chart.tsx
@@ -2,7 +2,7 @@ import { Group } from "@visx/group";
import { ParentSize } from "@visx/responsive";
import { scaleLinear, scaleUtc } from "@visx/scale";
import { Bar, Circle, Line } from "@visx/shape";
-import { PropsWithChildren, useMemo } from "react";
+import { PropsWithChildren, useMemo, useState } from "react";
import { ChartContext, ChartTooltipContext } from "./chart-context";
import {
ChartProps,
@@ -11,9 +11,6 @@ import {
} from "./types";
import { useTooltip } from "./useTooltip";
-const factors = (number) =>
- [...Array(number + 1).keys()].filter((i) => number % i === 0);
-
type TimeSeriesChartProps<T extends Datum> = PropsWithChildren<ChartProps<T>>;
export default function TimeSeriesChart<T extends Datum>(
@@ -40,8 +37,8 @@ function TimeSeriesChartInner<T extends Datum>({
data,
series,
tooltipContent = (d) => series[0].accessorFn(d).toString(),
- margin = {
- top: 2,
+ margin: marginProp = {
+ top: 12,
right: 4,
bottom: 32,
left: 4,
@@ -50,11 +47,17 @@ function TimeSeriesChartInner<T extends Datum>({
top: 0.1,
bottom: 0.1,
},
- maxTicks: maxTicksProp,
}: {
width: number;
height: number;
} & TimeSeriesChartProps<T>) {
+ const [leftAxisMargin, setLeftAxisMargin] = useState<number>();
+
+ const margin = {
+ ...marginProp,
+ left: marginProp.left + (leftAxisMargin ?? 0),
+ };
+
const width = outerWidth - margin.left - margin.right;
const height = outerHeight - margin.top - margin.bottom;
@@ -75,21 +78,20 @@ function TimeSeriesChartInner<T extends Datum>({
.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),
+ minY: Math.min(...values),
+ maxY: Math.max(...values),
};
}, [data, series, padding?.bottom, padding?.top]);
const { yScale, xScale } = useMemo(() => {
+ const rangeY = maxY - minY;
return {
yScale: scaleLinear<number>({
- domain: [minY, maxY],
+ domain: [
+ minY - rangeY * (padding.bottom ?? 0),
+ maxY + rangeY * (padding.top ?? 0),
+ ],
range: [height, 0],
nice: true,
clamp: true,
@@ -101,14 +103,6 @@ function TimeSeriesChartInner<T extends Datum>({
};
}, [startDate, endDate, minY, maxY, height, width, margin]);
- const { maxTicks, xTickInterval } = useMemo(() => {
- const maxTicks = maxTicksProp ?? width < 500 ? 6 : width < 800 ? 8 : 12;
- const xTickInterval =
- factors(data.length).find((f) => data.length / f < maxTicks) ?? 1;
-
- return { maxTicks, xTickInterval };
- }, [width, maxTicksProp]);
-
const chartContext: ChartContextType<T> = {
width,
height,
@@ -118,11 +112,13 @@ function TimeSeriesChartInner<T extends Datum>({
endDate,
xScale,
yScale,
+ minY,
+ maxY,
margin,
padding,
tooltipContent,
- maxTicks,
- xTickInterval,
+ leftAxisMargin,
+ setLeftAxisMargin,
};
const tooltipContext = useTooltip({
diff --git a/apps/web/ui/charts/types.ts b/apps/web/ui/charts/types.ts
index a5eac2e912..3b45f597ac 100644
--- a/apps/web/ui/charts/types.ts
+++ b/apps/web/ui/charts/types.ts
@@ -2,7 +2,7 @@ import { ScaleTypeToD3Scale } from "@visx/scale";
import { TooltipWithBounds } from "@visx/tooltip";
import { UseTooltipParams } from "@visx/tooltip/lib/hooks/useTooltip";
import { TooltipInPortalProps } from "@visx/tooltip/lib/hooks/useTooltipInPortal";
-import { FC, ReactElement } from "react";
+import { Dispatch, FC, ReactElement, SetStateAction } from "react";
export type Datum = Record<string, any>;
@@ -50,8 +50,6 @@ type ChartOptionalProps<T extends Datum = any> = {
top: number;
bottom: number;
};
-
- maxTicks?: number;
};
export type ChartProps<T extends Datum = any> = ChartRequiredProps<T> &
@@ -64,7 +62,10 @@ export type ChartContext<T extends Datum = any> = Required<ChartProps<T>> & {
endDate: Date;
xScale: ScaleTypeToD3Scale<number>["utc"];
yScale: ScaleTypeToD3Scale<number>["linear"];
- xTickInterval: number;
+ minY: number;
+ maxY: number;
+ leftAxisMargin?: number;
+ setLeftAxisMargin: Dispatch<SetStateAction<number | undefined>>;
};
export type ChartTooltipContext<T extends Datum = any> = {
diff --git a/apps/web/ui/charts/useTooltip.ts b/apps/web/ui/charts/useTooltip.ts
index 9f85733667..04614be969 100644
--- a/apps/web/ui/charts/useTooltip.ts
+++ b/apps/web/ui/charts/useTooltip.ts
@@ -16,7 +16,9 @@ import {
const bisectDate = bisector<Datum, Date>((d) => new Date(d.date)).left;
-export type TooltipOptions = {
+export type TooltipOptions<T extends Datum> = {
+ seriesId?: Series["id"];
+ chartContext: ChartContext<T>;
renderInPortal?: boolean;
snapToX?: boolean;
snapToY?: boolean;
@@ -28,11 +30,8 @@ export function useTooltip<T extends Datum>({
renderInPortal = false,
snapToY = false,
snapToX = true,
-}: {
- seriesId?: Series["id"];
- chartContext: ChartContext<T>;
-} & TooltipOptions): ChartTooltipContext {
- const { series, data, xScale, yScale } = chartContext;
+}: TooltipOptions<T>): ChartTooltipContext {
+ const { series, data, xScale, yScale, margin } = chartContext;
const visxTooltipInPortal = useTooltipInPortal({
scroll: true,
@@ -48,7 +47,8 @@ export function useTooltip<T extends Datum>({
| React.TouchEvent<SVGRectElement>
| React.MouseEvent<SVGRectElement>,
) => {
- const { x } = localPoint(event) || { x: 0 };
+ const lp = localPoint(event) || { x: 0 };
+ const x = lp.x - margin.left;
const x0 = xScale.invert(x);
const index = bisectDate(data, x0, 1);
const d0 = data[index - 1];
diff --git a/apps/web/ui/charts/utils.ts b/apps/web/ui/charts/utils.ts
new file mode 100644
index 0000000000..8294bcac21
--- /dev/null
+++ b/apps/web/ui/charts/utils.ts
@@ -0,0 +1,5 @@
+/**
+ * Finds all whole factors of a number
+ */
+export const getFactors = (number) =>
+ [...Array(number + 1).keys()].filter((i) => number % i === 0);
diff --git a/apps/web/ui/charts/x-axis.tsx b/apps/web/ui/charts/x-axis.tsx
index 9f8cb0e091..5a6f10daf4 100644
--- a/apps/web/ui/charts/x-axis.tsx
+++ b/apps/web/ui/charts/x-axis.tsx
@@ -1,37 +1,95 @@
-import { cn } from "@dub/utils";
import { AxisBottom } from "@visx/axis";
+import { Group } from "@visx/group";
+import { Line } from "@visx/shape";
+import { useMemo } from "react";
import { useChartContext, useChartTooltipContext } from "./chart-context";
+import { getFactors } from "./utils";
+
+export type XAxisProps = {
+ /**
+ * Maximum number of ticks to generate
+ */
+ maxTicks?: number;
+
+ /**
+ * Whether to render dashed grid lines across the chart area
+ */
+ showGridLines?: boolean;
+
+ /**
+ * Custom formatting function for tick labels
+ */
+ tickFormat?: (date: Date) => string;
+};
export default function XAxis({
+ maxTicks: maxTicksProp,
+ showGridLines = false,
tickFormat = (date) =>
date.toLocaleDateString("en-US", { month: "short", day: "numeric" }),
-}: {
- tickFormat?: (date: Date) => string;
-}) {
- const { data, margin, height, xScale, xTickInterval } = useChartContext();
+}: XAxisProps) {
+ const { data, margin, width, height, xScale, startDate, endDate } =
+ useChartContext();
const { tooltipData } = useChartTooltipContext();
+ const tickValues = useMemo(() => {
+ const maxTicks = maxTicksProp ?? width < 450 ? 4 : width < 600 ? 6 : 8;
+
+ const tickInterval =
+ getFactors(data.length).find((f) => (data.length + 1) / f <= maxTicks) ??
+ 1;
+
+ const twoTicks = data.length / tickInterval < 2;
+
+ return data
+ .filter((_, idx, { length }) =>
+ twoTicks
+ ? idx === 0 || idx === length - 1
+ : (idx + 1) % tickInterval === 0,
+ )
+ .map(({ date }) => date);
+ }, [width, maxTicksProp, data]);
+
return (
- <AxisBottom
- left={margin.left}
- top={margin.top + height}
- scale={xScale}
- tickValues={data.map(({ date }) => date)}
- hideTicks
- stroke="#00000026"
- tickFormat={(date) => tickFormat(date as Date)}
- tickLabelProps={(date, idx, { length }) => ({
- className: cn(
- "transition-colors",
- idx % xTickInterval !== 0 && "hidden",
- ),
- textAnchor: idx === 0 ? "start" : idx === length - 1 ? "end" : "middle",
- fontSize: 12,
- fill: (tooltipData ? tooltipData.date === date : idx === length - 1)
- ? "#000"
- : "#00000066",
- })}
- />
+ <>
+ <AxisBottom
+ left={margin.left}
+ top={margin.top + height}
+ scale={xScale}
+ tickValues={tickValues}
+ hideTicks
+ stroke="#00000026"
+ tickFormat={(date) => tickFormat(date as Date)}
+ tickLabelProps={(date, idx, { length }) => ({
+ className: "transition-colors",
+ textAnchor:
+ idx === 0 ? "start" : idx === length - 1 ? "end" : "middle",
+ fontSize: 12,
+ fill: (tooltipData ? tooltipData.date === date : idx === length - 1)
+ ? "#000"
+ : "#00000066",
+ })}
+ />
+ {showGridLines && (
+ <Group left={margin.left} top={margin.top}>
+ {tickValues.length > 0 &&
+ tickValues.map((date) => (
+ <Line
+ key={date.toString()}
+ x1={xScale(date)}
+ x2={xScale(date)}
+ y1={height}
+ y2={0}
+ stroke={
+ date === tooltipData?.date ? "transparent" : "#00000026"
+ }
+ strokeWidth={1}
+ strokeDasharray={[startDate, endDate].includes(date) ? 0 : 5}
+ />
+ ))}
+ </Group>
+ )}
+ </>
);
}
diff --git a/apps/web/ui/charts/y-axis.tsx b/apps/web/ui/charts/y-axis.tsx
new file mode 100644
index 0000000000..0beac262a7
--- /dev/null
+++ b/apps/web/ui/charts/y-axis.tsx
@@ -0,0 +1,116 @@
+import { AxisLeft } from "@visx/axis";
+import { Group } from "@visx/group";
+import { Line } from "@visx/shape";
+import { getStringWidth } from "@visx/text";
+import { useEffect, useMemo } from "react";
+import { useChartContext } from "./chart-context";
+
+export type YAxisProps = {
+ /**
+ * Approximate number of ticks to generate (see d3-array's `ticks`)
+ */
+ numTicks?: number;
+
+ /**
+ * Whether to render dashed grid lines across the chart area
+ */
+ showGridLines?: boolean;
+
+ /**
+ * Whether to only generate integer ticks (no decimals)
+ */
+ integerTicks?: boolean;
+
+ /**
+ * Tick values to override dynamic tick generation
+ */
+ tickValues?: number[];
+
+ /**
+ * Custom formatting function for tick labels
+ */
+ tickFormat?: (value: number) => string;
+
+ /**
+ * Amount of space between tick labels and the axis line / chart area
+ */
+ tickAxisSpacing?: number;
+};
+
+export default function YAxis({
+ numTicks: numTicksProp,
+ showGridLines = false,
+ integerTicks = false,
+ tickValues: tickValuesProp,
+ tickFormat = (value: number) => value.toString(),
+ tickAxisSpacing = 8,
+}: YAxisProps) {
+ const {
+ width,
+ height,
+ margin,
+ yScale,
+ minY,
+ leftAxisMargin,
+ setLeftAxisMargin,
+ } = useChartContext();
+
+ const tickValues = useMemo(() => {
+ if (tickValuesProp) return tickValuesProp;
+
+ const numTicks = numTicksProp ?? height < 350 ? 3 : 4;
+
+ return yScale.ticks(numTicks).filter((value) =>
+ // Both of these reduce the number of ticks farther below numTicks, but this should only affect small ranges
+ value >= minY && integerTicks ? Number.isInteger(value) : true,
+ );
+ }, [tickValuesProp, numTicksProp, height, yScale, integerTicks]);
+
+ useEffect(() => {
+ const maxWidth =
+ Math.max(
+ ...tickValues.map(
+ (v) => getStringWidth(tickFormat(v), { fontSize: 12 }) ?? 0,
+ ),
+ ) + tickAxisSpacing;
+ if ((leftAxisMargin ?? 0) < maxWidth) setLeftAxisMargin(maxWidth);
+ }, [tickValues, tickAxisSpacing, leftAxisMargin]);
+
+ return (
+ <>
+ <AxisLeft
+ left={margin.left}
+ top={margin.top}
+ scale={yScale}
+ tickValues={tickValues}
+ hideTicks
+ stroke="transparent"
+ tickFormat={(value) => tickFormat(value as number)}
+ tickLength={tickAxisSpacing}
+ tickLabelProps={() => ({
+ fontSize: 12,
+ fill: "#00000066",
+ textAnchor: "end",
+ verticalAnchor: "middle",
+ })}
+ />
+ {showGridLines && (
+ <Group left={margin.left} top={margin.top}>
+ {tickValues.length > 0 &&
+ tickValues.map((value) => (
+ <Line
+ key={value.toString()}
+ y1={yScale(value)}
+ y2={yScale(value)}
+ x1={0}
+ x2={width}
+ stroke="#00000026"
+ strokeWidth={1}
+ strokeDasharray={5}
+ />
+ ))}
+ </Group>
+ )}
+ </>
+ );
+}
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index b09022e4d1..8556615c99 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -124,6 +124,9 @@ importers:
'@visx/shape':
specifier: ^2.12.2
version: 2.12.2([email protected])
+ '@visx/text':
+ specifier: ^3.3.0
+ version: 3.3.0([email protected])
'@visx/tooltip':
specifier: ^2.16.0
@@ -7234,6 +7237,20 @@ packages:
reduce-css-calc: 1.3.0
dev: false
+ resolution: {integrity: sha512-fOimcsf0GtQE9whM5MdA/xIkHMaV29z7qNqNXysUDE8znSMKsN+ott7kSg2ljAEE89CQo3WKHkPNettoVsa84w==}
+ peerDependencies:
+ react: ^16.3.0-0 || ^17.0.0-0 || ^18.0.0-0
+ dependencies:
+ '@types/lodash': 4.14.199
+ '@types/react': 18.2.48
+ classnames: 2.3.2
+ lodash: 4.17.21
+ prop-types: 15.8.1
+ react: 18.2.0
+ reduce-css-calc: 1.3.0
+ dev: false
+
resolution: {integrity: sha512-kCjVtNGYpYm6AuMc1fT9cIwqpBivfQ8A5Qd7fQMC2xm4YVmehFdbyRr0nVft8zNXyUW3lDxbcq5bPIMRYhuhlA==}
peerDependencies: