Skip to content

Open source alternative to Semrush and Ahrefs

Style the shadcn chart for OpenSEO and use it on every chart (EVE-296) (#735)

Carter Smith8ec0fd84b0e3
diff --git a/src/client/components/ChartAxes.tsx b/src/client/components/ChartAxes.tsx
new file mode 100644
index 00000000..bebc6f9a
--- /dev/null
+++ b/src/client/components/ChartAxes.tsx
@@ -0,0 +1,37 @@
+import type { ComponentProps } from "react";
+import { CartesianGrid, XAxis, YAxis } from "recharts";
+
+// Shared grid and axis defaults for charts inside the shadcn ChartContainer.
+// ChartContainer colors the grid lines and tick labels from the --trend-*
+// variables, so these wrappers set only the shape. Props override defaults.
+// The tick font size is a prop, not CSS, because Recharts measures tick labels
+// with it to decide which ticks fit.
+const TICK = { fontSize: 10 };
+
+export function ChartGrid(props: ComponentProps<typeof CartesianGrid>) {
+ return <CartesianGrid strokeDasharray="3 3" vertical={false} {...props} />;
+}
+
+export function ChartXAxis(props: ComponentProps<typeof XAxis>) {
+ return (
+ <XAxis
+ tick={TICK}
+ tickLine={false}
+ axisLine={false}
+ minTickGap={32}
+ {...props}
+ />
+ );
+}
+
+export function ChartYAxis(props: ComponentProps<typeof YAxis>) {
+ return (
+ <YAxis
+ tick={TICK}
+ tickLine={false}
+ axisLine={false}
+ width={44}
+ {...props}
+ />
+ );
+}
diff --git a/src/client/components/ui/chart.tsx b/src/client/components/ui/chart.tsx
index 80d3c6b1..4437edfa 100644
--- a/src/client/components/ui/chart.tsx
+++ b/src/client/components/ui/chart.tsx
@@ -1,16 +1,16 @@
-// Stock shadcn output. The stacked OpenSEO PR makes this file pass the
-// project's lint rules and removes this line.
-// oxlint-disable eslint/no-shadow, typescript/no-unsafe-type-assertion, typescript/no-unnecessary-type-arguments, typescript/restrict-template-expressions, typescript/no-unsafe-assignment, typescript/no-unsafe-member-access, typescript/no-unsafe-argument
import * as React from "react";
import { cn } from "cn";
import * as RechartsPrimitive from "recharts";
-import type { TooltipValueType } from "recharts";
+import type { TooltipPayloadEntry, TooltipValueType } from "recharts";
// Format: { THEME_NAME: CSS_SELECTOR }
-const THEMES = { light: "", dark: ".dark" } as const;
+const THEMES = { light: "", dark: "[data-theme=openseo-dark]" } as const;
+
+// A series with no color or theme takes the next color of the unified
+// --chart-* palette, so new charts get theme-aware colors by default.
+const PALETTE_SIZE = 5;
const INITIAL_DIMENSION = { width: 320, height: 200 } as const;
-type TooltipNameType = number | string;
export type ChartConfig = Record<
string,
@@ -65,7 +65,7 @@ function ChartContainer({
data-slot="chart"
data-chart={chartId}
className={cn(
- "flex aspect-video justify-center text-xs [&_.recharts-cartesian-axis-tick_text]:fill-muted-foreground [&_.recharts-cartesian-grid_line[stroke='#ccc']]:stroke-border/50 [&_.recharts-curve.recharts-tooltip-cursor]:stroke-border [&_.recharts-dot[stroke='#fff']]:stroke-transparent [&_.recharts-layer]:outline-hidden [&_.recharts-polar-grid_[stroke='#ccc']]:stroke-border [&_.recharts-radial-bar-background-sector]:fill-muted [&_.recharts-rectangle.recharts-tooltip-cursor]:fill-muted [&_.recharts-reference-line_[stroke='#ccc']]:stroke-border [&_.recharts-sector]:outline-hidden [&_.recharts-sector[stroke='#fff']]:stroke-transparent [&_.recharts-surface]:outline-hidden",
+ "flex w-full min-w-0 justify-center text-xs [&_.recharts-cartesian-axis-tick_text]:fill-(--trend-axis-color) [&_.recharts-cartesian-grid_line[stroke='#ccc']]:stroke-(--trend-grid-color) [&_.recharts-curve.recharts-tooltip-cursor]:stroke-(--trend-grid-color) [&_.recharts-dot[stroke='#fff']]:stroke-transparent [&_.recharts-layer]:outline-hidden [&_.recharts-polar-grid_[stroke='#ccc']]:stroke-border [&_.recharts-radial-bar-background-sector]:fill-muted [&_.recharts-rectangle.recharts-tooltip-cursor]:fill-foreground/5 [&_.recharts-reference-line_[stroke='#ccc']]:stroke-border [&_.recharts-sector]:outline-hidden [&_.recharts-sector[stroke='#fff']]:stroke-transparent [&_.recharts-surface]:outline-hidden",
className,
)}
{...props}
@@ -82,33 +82,30 @@ function ChartContainer({
}
const ChartStyle = ({ id, config }: { id: string; config: ChartConfig }) => {
- const colorConfig = Object.entries(config).filter(
- ([, config]) => config.theme ?? config.color,
- );
+ const entries = Object.entries(config);
- if (!colorConfig.length) {
+ if (!entries.length) {
return null;
}
- return (
- <style
- dangerouslySetInnerHTML={{
- __html: Object.entries(THEMES)
- .map(
- ([theme, prefix]) => `
-${prefix} [data-chart=${id}] {
-${colorConfig
- .map(([key, itemConfig]) => {
+ const themeRule = (theme: keyof typeof THEMES) => `
+${THEMES[theme]} [data-chart=${id}] {
+${entries
+ .map(([key, itemConfig], index) => {
const color =
- itemConfig.theme?.[theme as keyof typeof itemConfig.theme] ??
- itemConfig.color;
- return color ? ` --color-${key}: ${color};` : null;
+ itemConfig.theme?.[theme] ??
+ itemConfig.color ??
+ `var(--chart-${(index % PALETTE_SIZE) + 1})`;
+ return ` --color-${key}: ${color};`;
})
.join("\n")}
}
-`,
- )
- .join("\n"),
+`;
+
+ return (
+ <style
+ dangerouslySetInnerHTML={{
+ __html: `${themeRule("light")}\n${themeRule("dark")}`,
}}
/>
);
@@ -127,6 +124,7 @@ function ChartTooltipContent({
labelFormatter,
labelClassName,
formatter,
+ valueFormatter = formatTooltipValue,
color,
nameKey,
labelKey,
@@ -137,11 +135,13 @@ function ChartTooltipContent({
indicator?: "line" | "dot" | "dashed";
nameKey?: string;
labelKey?: string;
+ /** Formats the value of one row and keeps its indicator and name. */
+ valueFormatter?: (
+ value: TooltipValueType,
+ item: TooltipPayloadEntry,
+ ) => React.ReactNode;
} & Omit<
- RechartsPrimitive.DefaultTooltipContentProps<
- TooltipValueType,
- TooltipNameType
- >,
+ RechartsPrimitive.DefaultTooltipContentProps,
"accessibilityLayer"
>) {
const { config } = useChart();
@@ -152,7 +152,7 @@ function ChartTooltipContent({
}
const [item] = payload;
- const key = `${labelKey ?? item?.dataKey ?? item?.name ?? "value"}`;
+ const key = labelKey ?? payloadKey(item, "dataKey") ?? "value";
const itemConfig = getPayloadConfigFromPayload(config, item, key);
const value =
!labelKey && typeof label === "string"
@@ -162,7 +162,7 @@ function ChartTooltipContent({
if (labelFormatter) {
return (
<div className={cn("font-medium", labelClassName)}>
- {labelFormatter(value, payload)}
+ {labelFormatter(typeof label === "number" ? label : value, payload)}
</div>
);
}
@@ -191,7 +191,7 @@ function ChartTooltipContent({
return (
<div
className={cn(
- "grid min-w-32 items-start gap-1.5 rounded-lg border border-border/50 bg-background px-2.5 py-1.5 text-xs shadow-xl",
+ "grid min-w-32 items-start gap-1.5 rounded-lg border border-(--trend-tooltip-border) bg-(--trend-tooltip-bg) px-2.5 py-1.5 text-xs text-foreground shadow-[0_8px_24px_var(--trend-tooltip-shadow)]",
className,
)}
>
@@ -200,9 +200,10 @@ function ChartTooltipContent({
{payload
.filter((item) => item.type !== "none")
.map((item, index) => {
- const key = `${nameKey ?? item.name ?? item.dataKey ?? "value"}`;
+ const key = nameKey ?? payloadKey(item, "name") ?? "value";
const itemConfig = getPayloadConfigFromPayload(config, item, key);
- const indicatorColor = color ?? item.payload?.fill ?? item.color;
+ const indicatorColor =
+ color ?? readString(item.payload, "fill") ?? item.color;
return (
<div
@@ -212,8 +213,8 @@ function ChartTooltipContent({
indicator === "dot" && "items-center",
)}
>
- {formatter && item?.value !== undefined && item.name ? (
- formatter(item.value, item.name, item, index, item.payload)
+ {formatter && item.value !== undefined && item.name ? (
+ formatter(item.value, item.name, item, index, payload)
) : (
<>
{itemConfig?.icon ? (
@@ -231,18 +232,16 @@ function ChartTooltipContent({
"my-0.5": nestLabel && indicator === "dashed",
},
)}
- style={
- {
- "--color-bg": indicatorColor,
- "--color-border": indicatorColor,
- } as React.CSSProperties
- }
+ style={{
+ ["--color-bg" as string]: indicatorColor,
+ ["--color-border" as string]: indicatorColor,
+ }}
/>
)
)}
<div
className={cn(
- "flex flex-1 justify-between leading-none",
+ "flex flex-1 justify-between gap-4 leading-none",
nestLabel ? "items-end" : "items-center",
)}
>
@@ -253,10 +252,8 @@ function ChartTooltipContent({
</span>
</div>
{item.value != null && (
- <span className="font-mono font-medium text-foreground tabular-nums">
- {typeof item.value === "number"
- ? item.value.toLocaleString()
- : String(item.value)}
+ <span className="font-medium text-foreground tabular-nums">
+ {valueFormatter(item.value, item)}
</span>
)}
</div>
@@ -270,6 +267,10 @@ function ChartTooltipContent({
);
}
+function formatTooltipValue(value: TooltipValueType) {
+ return typeof value === "number" ? value.toLocaleString() : String(value);
+}
+
const ChartLegend = RechartsPrimitive.Legend;
function ChartLegendContent({
@@ -299,7 +300,7 @@ function ChartLegendContent({
{payload
.filter((item) => item.type !== "none")
.map((item, index) => {
- const key = `${nameKey ?? item.dataKey ?? "value"}`;
+ const key = nameKey ?? payloadKey(item, "dataKey") ?? "value";
const itemConfig = getPayloadConfigFromPayload(config, item, key);
return (
@@ -327,38 +328,34 @@ function ChartLegendContent({
);
}
+/** Reads a string or number field of a Recharts payload as a config key. */
+function payloadKey(item: unknown, field: "dataKey" | "name") {
+ const value = readField(item, field);
+ return typeof value === "string" || typeof value === "number"
+ ? String(value)
+ : undefined;
+}
+
+function readField(value: unknown, field: string): unknown {
+ return typeof value === "object" && value !== null && field in value
+ ? Reflect.get(value, field)
+ : undefined;
+}
+
+function readString(value: unknown, field: string) {
+ const fieldValue = readField(value, field);
+ return typeof fieldValue === "string" ? fieldValue : undefined;
+}
+
function getPayloadConfigFromPayload(
config: ChartConfig,
payload: unknown,
key: string,
) {
- if (typeof payload !== "object" || payload === null) {
- return undefined;
- }
-
- const payloadPayload =
- "payload" in payload &&
- typeof payload.payload === "object" &&
- payload.payload !== null
- ? payload.payload
- : undefined;
-
- let configLabelKey: string = key;
-
- if (
- key in payload &&
- typeof payload[key as keyof typeof payload] === "string"
- ) {
- configLabelKey = payload[key as keyof typeof payload] as string;
- } else if (
- payloadPayload &&
- key in payloadPayload &&
- typeof payloadPayload[key as keyof typeof payloadPayload] === "string"
- ) {
- configLabelKey = payloadPayload[
- key as keyof typeof payloadPayload
- ] as string;
- }
+ const configLabelKey =
+ readString(payload, key) ??
+ readString(readField(payload, "payload"), key) ??
+ key;
return configLabelKey in config ? config[configLabelKey] : config[key];
}
diff --git a/src/client/features/ai-search/components/BrandLookupMentionTrendCard.tsx b/src/client/features/ai-search/components/BrandLookupMentionTrendCard.tsx
index d15462d5..c2f3862e 100644
--- a/src/client/features/ai-search/components/BrandLookupMentionTrendCard.tsx
+++ b/src/client/features/ai-search/components/BrandLookupMentionTrendCard.tsx
@@ -1,13 +1,16 @@
import { useMemo } from "react";
+import { Line, LineChart } from "recharts";
import {
- CartesianGrid,
- Line,
- LineChart,
- ResponsiveContainer,
- Tooltip,
- XAxis,
- YAxis,
-} from "recharts";
+ ChartGrid,
+ ChartXAxis,
+ ChartYAxis,
+} from "@/client/components/ChartAxes";
+import {
+ ChartContainer,
+ ChartTooltip,
+ ChartTooltipContent,
+ type ChartConfig,
+} from "@/client/components/ui/chart";
import { formatCount } from "@/client/features/ai-search/platformLabels";
import type { BrandLookupResult } from "@/types/schemas/ai-search";
@@ -15,6 +18,10 @@ type Props = {
result: BrandLookupResult;
};
+const chartConfig = {
+ volume: { label: "Mentions", color: "hsl(220 70% 50%)" },
+} satisfies ChartConfig;
+
export function BrandLookupMentionTrendCard({ result }: Props) {
const chartData = useMemo(
() =>
@@ -26,62 +33,29 @@ export function BrandLookupMentionTrendCard({ result }: Props) {
);
return (
- <div className="h-56">
- <ResponsiveContainer width="100%" height="100%">
- <LineChart
- data={chartData}
- margin={{ top: 12, right: 12, bottom: 4, left: 0 }}
- >
- <CartesianGrid
- strokeDasharray="3 3"
- stroke="currentColor"
- opacity={0.12}
- />
- <XAxis
- dataKey="label"
- tick={{ fontSize: 11, fill: "#888" }}
- tickLine={false}
- axisLine={false}
- />
- <YAxis
- tick={{ fontSize: 11, fill: "#888" }}
- tickLine={false}
- axisLine={false}
- allowDecimals={false}
- />
- <Tooltip
- content={<MentionTooltip />}
- cursor={{ stroke: "currentColor", strokeOpacity: 0.2 }}
- />
- <Line
- type="monotone"
- dataKey="volume"
- stroke="hsl(220 70% 50%)"
- strokeWidth={2}
- dot={false}
- />
- </LineChart>
- </ResponsiveContainer>
- </div>
- );
-}
-
-function MentionTooltip({
- active,
- payload,
- label,
-}: {
- active?: boolean;
- payload?: Array<{ value: number }>;
- label?: string;
-}) {
- if (!active || !payload?.length) return null;
- return (
- <div className="rounded-md border border-base-300 bg-base-100 px-3 py-2 shadow-sm">
- <p className="text-xs text-base-content/60">{label}</p>
- <p className="text-sm font-medium tabular-nums">
- {formatCount(payload[0].value)} mentions
- </p>
- </div>
+ <ChartContainer config={chartConfig} className="h-56">
+ <LineChart
+ data={chartData}
+ margin={{ top: 12, right: 12, bottom: 4, left: 0 }}
+ >
+ <ChartGrid />
+ <ChartXAxis dataKey="label" />
+ <ChartYAxis allowDecimals={false} />
+ <ChartTooltip
+ content={
+ <ChartTooltipContent
+ valueFormatter={(value) => formatCount(Number(value))}
+ />
+ }
+ />
+ <Line
+ type="monotone"
+ dataKey="volume"
+ stroke="var(--color-volume)"
+ strokeWidth={2}
+ dot={false}
+ />
+ </LineChart>
+ </ChartContainer>
);
}
diff --git a/src/client/features/backlinks/BacklinksPageCharts.tsx b/src/client/features/backlinks/BacklinksPageCharts.tsx
index 523a74ee..132879f2 100644
--- a/src/client/features/backlinks/BacklinksPageCharts.tsx
+++ b/src/client/features/backlinks/BacklinksPageCharts.tsx
@@ -1,13 +1,17 @@
-import { useEffect, useRef, useState } from "react";
+import { Line, LineChart } from "recharts";
import {
- CartesianGrid,
- Legend,
- Line,
- LineChart,
- Tooltip,
- XAxis,
- YAxis,
-} from "recharts";
+ ChartGrid,
+ ChartXAxis,
+ ChartYAxis,
+} from "@/client/components/ChartAxes";
+import {
+ ChartContainer,
+ ChartLegend,
+ ChartLegendContent,
+ ChartTooltip,
+ ChartTooltipContent,
+ type ChartConfig,
+} from "@/client/components/ui/chart";
import type { BacklinksOverviewData } from "./backlinksPageTypes";
import {
formatCompactDate,
@@ -15,73 +19,78 @@ import {
formatTooltipValue,
} from "./backlinksPageUtils";
+const trendChartConfig = {
+ backlinks: { label: "Backlinks", color: "#2563eb" },
+ referringDomains: { label: "Referring domains", color: "#14b8a6" },
+} satisfies ChartConfig;
+
+const newLostChartConfig = {
+ lostBacklinks: { label: "Lost backlinks", color: "#ef4444" },
+ newBacklinks: { label: "New backlinks", color: "#16a34a" },
+} satisfies ChartConfig;
+
+const tooltip = (
+ <ChartTooltip
+ content={
+ <ChartTooltipContent
+ labelFormatter={formatChartLabel}
+ valueFormatter={formatTooltipValue}
+ />
+ }
+ />
+);
+
+const legend = <ChartLegend content={<ChartLegendContent />} />;
+
export function BacklinksTrendChart({
data,
}: {
data: BacklinksOverviewData["trends"];
}) {
- const { containerRef, chartWidth } = useChartWidth();
-
if (data.length === 0) {
return <EmptyChartState />;
}
return (
- <div
- ref={containerRef}
- className="h-56 min-w-0"
+ <ChartContainer
+ config={trendChartConfig}
+ className="h-56"
aria-label="Backlink trend chart"
>
- {chartWidth > 0 ? (
- <LineChart
- width={chartWidth}
- height={224}
- data={data}
- margin={{ left: 8, right: 8, top: 8, bottom: 0 }}
- >
- <CartesianGrid
- strokeDasharray="3 3"
- stroke="currentColor"
- opacity={0.12}
- />
- <XAxis
- dataKey="date"
- tickFormatter={formatChartTick}
- minTickGap={24}
- />
- <YAxis yAxisId="left" tickFormatter={formatAxisValue} width={60} />
- <YAxis
- yAxisId="right"
- orientation="right"
- tickFormatter={formatAxisValue}
- width={60}
- />
- <Tooltip
- formatter={formatTooltipValue}
- labelFormatter={formatChartLabel}
- />
- <Legend />
- <Line
- yAxisId="left"
- type="monotone"
- dataKey="backlinks"
- stroke="#2563eb"
- strokeWidth={2}
- dot={false}
- name="Backlinks"
- />
- <Line
- yAxisId="right"
- type="monotone"
- dataKey="referringDomains"
- stroke="#14b8a6"
- strokeWidth={2}
- dot={false}
- name="Referring domains"
- />
- </LineChart>
- ) : null}
- </div>
+ <LineChart data={data} margin={{ left: 8, right: 8, top: 8, bottom: 0 }}>
+ <ChartGrid />
+ <ChartXAxis
+ dataKey="date"
+ tickFormatter={formatChartTick}
+ minTickGap={24}
+ />
+ <ChartYAxis yAxisId="left" tickFormatter={formatAxisValue} width={60} />
+ <ChartYAxis
+ yAxisId="right"
+ orientation="right"
+ tickFormatter={formatAxisValue}
+ width={60}
+ />
+ {tooltip}
+ {legend}
+ <Line
+ yAxisId="left"
+ type="monotone"
+ dataKey="backlinks"
+ stroke="var(--color-backlinks)"
+ strokeWidth={2}
+ dot={false}
+ />
+ <Line
+ yAxisId="right"
+ type="monotone"
+ dataKey="referringDomains"
+ stroke="var(--color-referringDomains)"
+ strokeWidth={2}
+ dot={false}
+ />
+ </LineChart>
+ </ChartContainer>
);
}
@@ -90,90 +99,45 @@ export function BacklinksNewLostChart({
}: {
data: BacklinksOverviewData["newLostTrends"];
}) {
- const { containerRef, chartWidth } = useChartWidth();
-
if (data.length === 0) {
return <EmptyChartState />;
}
return (
- <div
- ref={containerRef}
- className="h-56 min-w-0"
+ <ChartContainer
+ config={newLostChartConfig}
+ className="h-56"
aria-label="New and lost backlinks chart"
>
- {chartWidth > 0 ? (
- <LineChart
- width={chartWidth}
- height={224}
- data={data}
- margin={{ left: 8, right: 8, top: 8, bottom: 0 }}
- >
- <CartesianGrid
- strokeDasharray="3 3"
- stroke="currentColor"
- opacity={0.12}
- />
- <XAxis
- dataKey="date"
- tickFormatter={formatChartTick}
- minTickGap={24}
- />
- <YAxis tickFormatter={formatAxisValue} width={60} />
- <Tooltip
- formatter={formatTooltipValue}
- labelFormatter={formatChartLabel}
- />
- <Legend />
- <Line
- type="monotone"
- dataKey="lostBacklinks"
- stroke="#ef4444"
- strokeWidth={2}
- dot={false}
- name="Lost backlinks"
- />
- <Line
- type="monotone"
- dataKey="newBacklinks"
- stroke="#16a34a"
- strokeWidth={2}
- dot={false}
- name="New backlinks"
- />
- </LineChart>
- ) : null}
- </div>
+ <LineChart data={data} margin={{ left: 8, right: 8, top: 8, bottom: 0 }}>
+ <ChartGrid />
+ <ChartXAxis
+ dataKey="date"
+ tickFormatter={formatChartTick}
+ minTickGap={24}
+ />
+ <ChartYAxis tickFormatter={formatAxisValue} width={60} />
+ {tooltip}
+ {legend}
+ <Line
+ type="monotone"
+ dataKey="lostBacklinks"
+ stroke="var(--color-lostBacklinks)"
+ strokeWidth={2}
+ dot={false}
+ />
+ <Line
+ type="monotone"
+ dataKey="newBacklinks"
+ stroke="var(--color-newBacklinks)"
+ strokeWidth={2}
+ dot={false}
+ />
+ </LineChart>
+ </ChartContainer>
);
}
-function useChartWidth() {
- const containerRef = useRef<HTMLDivElement | null>(null);
- const [chartWidth, setChartWidth] = useState(0);
-
- useEffect(() => {
- const container = containerRef.current;
- if (!container) {
- return;
- }
-
- const updateWidth = () => {
- setChartWidth(container.clientWidth);
- };
-
- updateWidth();
-
- const observer = new ResizeObserver(updateWidth);
- observer.observe(container);
-
- return () => {
- observer.disconnect();
- };
- }, []);
-
- return { containerRef, chartWidth };
-}
-
function EmptyChartState() {
return (
<div className="flex h-56 items-center justify-center rounded-xl border border-dashed border-base-300 text-sm text-base-content/55">
diff --git a/src/client/features/billing/BillingUsageChart.tsx b/src/client/features/billing/BillingUsageChart.tsx
index 2933f3c5..8afe3d20 100644
--- a/src/client/features/billing/BillingUsageChart.tsx
+++ b/src/client/features/billing/BillingUsageChart.tsx
@@ -1,34 +1,33 @@
import { useAggregateEvents } from "autumn-js/react";
-import { useEffect, useRef, useState } from "react";
-import { Bar, BarChart, CartesianGrid, Tooltip, XAxis, YAxis } from "recharts";
+import { Bar, BarChart } from "recharts";
import {
AUTUMN_SEO_DATA_BALANCE_FEATURE_ID,
AUTUMN_SEO_DATA_TOPUP_BALANCE_FEATURE_ID,
autumnSeoDataCreditsToUsd,
} from "@/shared/billing";
import { QueryError } from "@/client/components/QueryState";
+import {
+ ChartGrid,
+ ChartXAxis,
+ ChartYAxis,
+} from "@/client/components/ChartAxes";
+import {
+ ChartContainer,
+ ChartTooltip,
+ ChartTooltipContent,
+ type ChartConfig,
+} from "@/client/components/ui/chart";
const BILLING_USAGE_FEATURE_IDS: string[] = [
AUTUMN_SEO_DATA_BALANCE_FEATURE_ID,
AUTUMN_SEO_DATA_TOPUP_BALANCE_FEATURE_ID,
];
-export function BillingUsageChart() {
- const containerRef = useRef<HTMLDivElement>(null);
- const [chartWidth, setChartWidth] = useState(0);
-
- useEffect(() => {
- const el = containerRef.current;
- if (!el) return;
-
- const update = () => setChartWidth(el.clientWidth);
- update();
-
- const observer = new ResizeObserver(update);
- observer.observe(el);
- return () => observer.disconnect();
- }, []);
+const chartConfig = {
+ credits: { label: "Usage", color: "#7c3aed" },
+} satisfies ChartConfig;
+export function BillingUsageChart() {
const eventsQuery = useAggregateEvents({
featureId: BILLING_USAGE_FEATURE_IDS,
range: "30d",
@@ -58,7 +57,7 @@ export function BillingUsageChart() {
${totalSpend.toFixed(2)}
</div>
- <div ref={containerRef} className="w-full h-32 min-w-0">
+ <div className="w-full h-32 min-w-0">
{eventsQuery.isLoading ? null : eventsQuery.list === undefined &&
eventsQuery.isError ? (
<QueryError
@@ -73,77 +72,43 @@ export function BillingUsageChart() {
No usage recorded yet
</span>
</div>
- ) : chartWidth > 0 ? (
- <BarChart
- width={chartWidth}
- height={128}
- data={chartData}
- margin={{ top: 4, right: 0, bottom: 0, left: 0 }}
- >
- <CartesianGrid
- strokeDasharray="3 3"
- stroke="currentColor"
- opacity={0.06}
- vertical={false}
- />
- <XAxis
- dataKey="date"
- tickFormatter={formatShortDate}
- tick={{ fontSize: 10, fill: "#888" }}
- tickLine={false}
- axisLine={false}
- minTickGap={40}
- />
- <YAxis
- tickFormatter={formatUsdAxis}
- tick={{ fontSize: 10, fill: "#888" }}
- tickLine={false}
- axisLine={false}
- width={44}
- />
- <Tooltip
- content={<UsageTooltip />}
- cursor={{ fill: "rgba(150,150,150,0.1)" }}
- />
- <Bar
- dataKey="credits"
- fill="#7c3aed"
- radius={[2, 2, 0, 0]}
- maxBarSize={12}
- />
- </BarChart>
- ) : null}
+ ) : (
+ <ChartContainer config={chartConfig} className="h-full">
+ <BarChart
+ data={chartData}
+ margin={{ top: 4, right: 0, bottom: 0, left: 0 }}
+ >
+ <ChartGrid />
+ <ChartXAxis
+ dataKey="date"
+ tickFormatter={formatShortDate}
+ minTickGap={40}
+ />
+ <ChartYAxis tickFormatter={formatUsdAxis} />
+ <ChartTooltip
+ content={
+ <ChartTooltipContent
+ labelFormatter={(label: unknown) =>
+ typeof label === "number" ? formatShortDate(label) : ""
+ }
+ valueFormatter={(value) => `$${Number(value).toFixed(2)}`}
+ />
+ }
+ />
+ <Bar
+ dataKey="credits"
+ fill="var(--color-credits)"
+ radius={[2, 2, 0, 0]}
+ maxBarSize={12}
+ />
+ </BarChart>
+ </ChartContainer>
+ )}
</div>
</div>
);
}
-function UsageTooltip({
- active,
- payload,
- label,
-}: {
- active?: boolean;
- payload?: Array<{ value: number }>;
- label?: number;
-}) {
- if (!active || !payload?.length || label == null) return null;
-
- return (
- <div className="rounded-md border border-base-300 bg-base-100 px-3 py-2 shadow-sm">
- <p className="text-xs text-base-content/60">
- {new Date(label).toLocaleDateString("en-US", {
- month: "short",
- day: "numeric",
- })}
- </p>
- <p className="text-sm font-medium tabular-nums">
- ${payload[0].value.toFixed(2)}
- </p>
- </div>
- );
-}
-
function formatShortDate(timestamp: number) {
return new Date(timestamp).toLocaleDateString("en-US", {
month: "short",
diff --git a/src/client/features/dashboard/Ga4Card.tsx b/src/client/features/dashboard/Ga4Card.tsx
index 799bc29d..4a0a5b86 100644
--- a/src/client/features/dashboard/Ga4Card.tsx
+++ b/src/client/features/dashboard/Ga4Card.tsx
@@ -1,14 +1,7 @@
import { CardShell } from "@/client/components/CardShell";
import { Link } from "@tanstack/react-router";
import { useQuery } from "@tanstack/react-query";
-import {
- Area,
- AreaChart,
- ResponsiveContainer,
- Tooltip,
- XAxis,
- YAxis,
-} from "recharts";
+import { Area, AreaChart, XAxis, YAxis } from "recharts";
import {
moreDetailsClass,
PercentDelta,
@@ -21,6 +14,16 @@ import {
} from "@/client/features/search-performance/SearchPerformanceColumns";
import { getGa4DashboardReport } from "@/serverFunctions/ga4";
import { Skeleton } from "@/client/components/ui/skeleton";
+import {
+ ChartContainer,
+ ChartTooltip,
+ ChartTooltipContent,
+ type ChartConfig,
+} from "@/client/components/ui/chart";
+
+const sessionsChartConfig = {
+ sessions: { label: "Sessions", color: "var(--color-primary)" },
+} satisfies ChartConfig;
function formatTrendDay(date: string): string {
// Construct in local time: Date.parse("2026-08-01") is UTC midnight, which
@@ -45,28 +48,6 @@ function statDelta(current: number | null, previous: number | null) {
) : undefined;
}
-function SessionsTooltip({
- active,
- payload,
- label,
-}: {
- active?: boolean;
- payload?: Array<{ value: number }>;
- label?: string;
-}) {
- if (!active || !payload?.length) return null;
- return (
- <div className="rounded-md border border-base-300 bg-base-100 px-3 py-2 shadow-sm">
- <p className="text-xs text-base-content/60">
- {label ? formatTrendDay(label) : ""}
- </p>
- <p className="text-sm font-medium tabular-nums">
- {formatCount(payload[0].value)} sessions
- </p>
- </div>
- );
-}
-
export function Ga4Card({
projectId,
connected,
@@ -153,29 +134,33 @@ export function Ga4Card({
)}
/>
</div>
- <div className="h-24">
- <ResponsiveContainer width="100%" height="100%">
- <AreaChart
- data={report.trend}
- margin={{ top: 4, right: 0, bottom: 0, left: 0 }}
- >
- <XAxis dataKey="date" hide />
- <YAxis hide domain={[0, "auto"]} />
- <Tooltip
- content={<SessionsTooltip />}
- cursor={{ stroke: "currentColor", strokeOpacity: 0.2 }}
- />
- <Area
- type="monotone"
- dataKey="sessions"
- stroke="var(--color-primary)"
- strokeWidth={2}
- fill="var(--color-primary)"
- fillOpacity={0.08}
- />
- </AreaChart>
- </ResponsiveContainer>
- </div>
+ <ChartContainer config={sessionsChartConfig} className="h-24">
+ <AreaChart
+ data={report.trend}
+ margin={{ top: 4, right: 0, bottom: 0, left: 0 }}
+ >
+ <XAxis dataKey="date" hide />
+ <YAxis hide domain={[0, "auto"]} />
+ <ChartTooltip
+ content={
+ <ChartTooltipContent
+ labelFormatter={(label: unknown) =>
+ typeof label === "string" ? formatTrendDay(label) : ""
+ }
+ valueFormatter={(value) => formatCount(Number(value))}
+ />
+ }
+ />
+ <Area
+ type="monotone"
+ dataKey="sessions"
+ stroke="var(--color-sessions)"
+ strokeWidth={2}
+ fill="var(--color-sessions)"
+ fillOpacity={0.08}
+ />
+ </AreaChart>
+ </ChartContainer>
</div>
)}
</CardShell>
diff --git a/src/client/features/keywords/components/DisplayPrimitives.tsx b/src/client/features/keywords/components/DisplayPrimitives.tsx
index 14f2a5f2..ee7a20de 100644
--- a/src/client/features/keywords/components/DisplayPrimitives.tsx
+++ b/src/client/features/keywords/components/DisplayPrimitives.tsx
@@ -1,14 +1,17 @@
import { ChevronDown, ChevronUp } from "lucide-react";
-import { useEffect, useRef, useState } from "react";
import { createPortal } from "react-dom";
+import { Area, AreaChart } from "recharts";
import {
- Area,
- AreaChart,
- CartesianGrid,
- Tooltip,
- XAxis,
- YAxis,
-} from "recharts";
+ ChartGrid,
+ ChartXAxis,
+ ChartYAxis,
+} from "@/client/components/ChartAxes";
+import {
+ ChartContainer,
+ ChartTooltip,
+ ChartTooltipContent,
+ type ChartConfig,
+} from "@/client/components/ui/chart";
import type { MonthlySearch } from "@/types/keywords";
import {
formatCompactNumber,
@@ -28,108 +31,64 @@ export type SortField =
| "keywordDifficulty";
export type SortDir = "asc" | "desc";
+const trendChartConfig = {
+ searchVolume: { label: "Search volume", color: "var(--color-primary)" },
+} satisfies ChartConfig;
+
export function AreaTrendChart({ trend }: { trend: MonthlySearch[] }) {
const last12 = lastTwelveMonths(trend);
- const containerRef = useRef<HTMLDivElement | null>(null);
- const [chartWidth, setChartWidth] = useState(0);
-
if (last12.length === 0) return null;
- useEffect(() => {
- const container = containerRef.current;
- if (!container) return;
-
- const update = () => {
- setChartWidth(container.clientWidth);
- };
-
- update();
-
- const observer = new ResizeObserver(update);
- observer.observe(container);
-
- return () => {
- observer.disconnect();
- };
- }, []);
-
const data = last12.map((m) => ({
month: MONTH_SHORT_LABELS[m.month - 1],
searchVolume: m.searchVolume,
}));
return (
- <div
- ref={containerRef}
- className="w-full h-[210px] min-w-0"
+ <ChartContainer
+ config={trendChartConfig}
+ className="h-[210px]"
aria-label="Search trend chart"
>
- {chartWidth > 0 ? (
- <AreaChart
- width={chartWidth}
- height={210}
- data={data}
- margin={{ top: 8, right: 8, left: 0, bottom: 4 }}
- accessibilityLayer
- >
- <defs>
- <linearGradient id="trendGrad" x1="0" y1="0" x2="0" y2="1">
- <stop
- offset="0%"
- stopColor="var(--color-primary)"
- stopOpacity="var(--trend-fill-start-opacity)"
- />
- <stop
- offset="100%"
- stopColor="var(--color-primary)"
- stopOpacity="var(--trend-fill-end-opacity)"
- />
- </linearGradient>
- </defs>
- <CartesianGrid
- stroke="var(--trend-grid-color)"
- strokeDasharray="2 4"
- vertical={true}
- horizontal={true}
- />
- <XAxis
- dataKey="month"
- tick={{ fill: "var(--trend-axis-color)", fontSize: 11 }}
- axisLine={false}
- tickLine={false}
- />
- <YAxis
- tickFormatter={(value: number | string) =>
- formatCompactNumber(Number(value))
- }
- tick={{ fill: "var(--trend-axis-color)", fontSize: 11 }}
- width={44}
- axisLine={false}
- tickLine={false}
- />
- <Tooltip
- contentStyle={{
- backgroundColor: "var(--trend-tooltip-bg)",
- border: "1px solid var(--trend-tooltip-border)",
- borderRadius: "10px",
- boxShadow: "0 8px 24px var(--trend-tooltip-shadow)",
- color: "var(--color-base-content)",
- }}
- />
- <Area
- type="monotone"
- dataKey="searchVolume"
- name="Search volume"
- stroke="var(--color-primary)"
- strokeWidth={2}
- fill="url(#trendGrad)"
- isAnimationActive={false}
- dot={{ r: 3, fill: "var(--color-primary)", strokeWidth: 0 }}
- activeDot={{ r: 5, fill: "var(--color-primary)" }}
- />
- </AreaChart>
- ) : null}
- </div>
+ <AreaChart
+ data={data}
+ margin={{ top: 8, right: 8, left: 0, bottom: 4 }}
+ accessibilityLayer
+ >
+ <defs>
+ <linearGradient id="trendGrad" x1="0" y1="0" x2="0" y2="1">
+ <stop
+ offset="0%"
+ stopColor="var(--color-searchVolume)"
+ stopOpacity="var(--trend-fill-start-opacity)"
+ />
+ <stop
+ offset="100%"
+ stopColor="var(--color-searchVolume)"
+ stopOpacity="var(--trend-fill-end-opacity)"
+ />
+ </linearGradient>
+ </defs>
+ <ChartGrid />
+ <ChartXAxis dataKey="month" minTickGap={5} />
+ <ChartYAxis
+ tickFormatter={(value: number | string) =>
+ formatCompactNumber(Number(value))
+ }
+ />
+ <ChartTooltip content={<ChartTooltipContent />} />
+ <Area
+ type="monotone"
+ dataKey="searchVolume"
+ stroke="var(--color-searchVolume)"
+ strokeWidth={2}
+ fill="url(#trendGrad)"
+ isAnimationActive={false}
+ dot={{ r: 3, fill: "var(--color-searchVolume)", strokeWidth: 0 }}
+ activeDot={{ r: 5, fill: "var(--color-searchVolume)" }}
+ />
+ </AreaChart>
+ </ChartContainer>
);
}
diff --git a/src/client/features/rank-tracking/KeywordTrendModal.tsx b/src/client/features/rank-tracking/KeywordTrendModal.tsx
index a5563aa4..4cdb3a3e 100644
--- a/src/client/features/rank-tracking/KeywordTrendModal.tsx
+++ b/src/client/features/rank-tracking/KeywordTrendModal.tsx
@@ -176,14 +176,25 @@ export function KeywordTrendModal({
series={series}
serpDepth={serpDepth}
showBottomBand
- renderTooltip={(label, entries) => (
- <ChartTooltip
- label={label}
- entries={entries}
- serpDepth={serpDepth}
- bottomBandKeys={bottomBandKeys}
- />
- )}
+ valueFormatter={(value, item) => {
+ // The payload is the chart row, typed `any` upstream.
+ const row: unknown = item.payload;
+ const checkedAt =
+ typeof row === "object" &&
+ row !== null &&
+ "checkedAt" in row
+ ? row.checkedAt
+ : undefined;
+ return typeof checkedAt === "number" &&
+ typeof item.dataKey === "string" &&
+ bottomBandKeys.has(`${checkedAt}:${item.dataKey}`) ? (
+ <span className="font-normal text-muted-foreground">
+ Not in top {serpDepth}
+ </span>
+ ) : (
+ String(value)
+ );
+ }}
/>
<div className="flex items-center justify-end gap-2">
@@ -297,49 +308,6 @@ function EmptyState({ count }: { count: number }) {
);
}
-function ChartTooltip({
- label,
- entries,
- serpDepth,
- bottomBandKeys,
-}: {
- label: number;
- entries: Array<{ dataKey?: string | number; value: number | null }>;
- serpDepth: number;
- bottomBandKeys: Set<string>;
-}) {
- return (
- <div className="rounded-md border border-base-300 bg-base-100 px-3 py-2 shadow-sm space-y-0.5">
- <p className="text-xs text-base-content/60">
- {new Date(label).toLocaleDateString("en-US", {
- month: "short",
- day: "numeric",
- year: "numeric",
- })}
- </p>
- {entries.map((e) => {
- const device =
- e.dataKey === "desktop" || e.dataKey === "mobile"
- ? DEVICE_STYLE[e.dataKey].label
- : String(e.dataKey ?? "");
- const inBottomBand = bottomBandKeys.has(`${label}:${e.dataKey}`);
- return (
- <p key={String(e.dataKey)} className="text-sm font-medium">
- {device}:{" "}
- {inBottomBand ? (
- <span className="text-base-content/60">
- Not in top {serpDepth}
- </span>
- ) : (
- e.value
- )}
- </p>
- );
- })}
- </div>
- );
-}
-
// ---------------------------------------------------------------------------
// Data shaping
// ---------------------------------------------------------------------------
diff --git a/src/client/features/rank-tracking/RankTrackingOverview.tsx b/src/client/features/rank-tracking/RankTrackingOverview.tsx
index a979fa0c..e00302f8 100644
--- a/src/client/features/rank-tracking/RankTrackingOverview.tsx
+++ b/src/client/features/rank-tracking/RankTrackingOverview.tsx
@@ -1,21 +1,24 @@
import { useMemo, useState } from "react";
import { Loader2 } from "lucide-react";
import { useQuery } from "@tanstack/react-query";
-import {
- Area,
- AreaChart,
- CartesianGrid,
- Tooltip,
- XAxis,
- YAxis,
-} from "recharts";
-import type { TooltipContentProps } from "recharts";
+import { Area, AreaChart } from "recharts";
import { getRankConfigTrend } from "@/serverFunctions/rank-tracking";
import { QueryState } from "@/client/components/QueryState";
import {
- formatDateTick,
+ ChartGrid,
+ ChartXAxis,
+ ChartYAxis,
+} from "@/client/components/ChartAxes";
+import {
+ ChartContainer,
+ ChartTooltip,
+ ChartTooltipContent,
+ type ChartConfig,
+} from "@/client/components/ui/chart";
+import {
+ formatDateLabel,
+ TIME_AXIS,
TrendRangeToggle,
- useChartWidth,
} from "./RankTrackingTrendChart";
const BUCKETS = [
@@ -25,6 +28,10 @@ const BUCKETS = [
{ key: "notRanking", label: "Not in top 20", color: "#6b7280" },
] as const;
+const chartConfig: ChartConfig = Object.fromEntries(
+ BUCKETS.map((b) => [b.key, { label: b.label, color: b.color }]),
+);
+
export function RankTrackingOverview({
device,
projectId,
@@ -57,8 +64,6 @@ export function RankTrackingOverview({
[trend],
);
- const { containerRef, width } = useChartWidth();
-
return (
<div className="px-4 pt-4 pb-4">
<div className="rounded-lg border border-base-300 p-3 space-y-2">
@@ -99,80 +104,33 @@ export function RankTrackingOverview({
: "Only 1 check so far — the trend fills in after the next check."}
</div>
) : (
- <div
- ref={containerRef}
- className="w-full min-w-0"
- style={{ height: 220 }}
- >
- {width > 0 ? (
- <AreaChart
- width={width}
- height={220}
- data={chartData}
- margin={{ top: 8, right: 8, bottom: 0, left: 0 }}
- >
- <CartesianGrid
- strokeDasharray="3 3"
- stroke="currentColor"
- opacity={0.1}
- vertical={false}
- />
- <XAxis
- dataKey="checkedAt"
- type="number"
- scale="time"
- domain={["dataMin", "dataMax"]}
- tickFormatter={formatDateTick}
- tick={{ fontSize: 10, fill: "#888" }}
- tickLine={false}
- axisLine={false}
- minTickGap={32}
- />
- <YAxis
- allowDecimals={false}
- tick={{ fontSize: 10, fill: "#888" }}
- tickLine={false}
- axisLine={false}
- width={28}
- />
- <Tooltip
- content={(props: TooltipContentProps) => {
- const { active, payload, label } = props;
- if (
- !active ||
- !payload?.length ||
- typeof label !== "number"
- ) {
- return null;
- }
- const byKey = new Map(
- payload.map((p) => [
- String(p.dataKey),
- typeof p.value === "number" ? p.value : 0,
- ]),
- );
- return (
- <DistributionTooltip label={label} byKey={byKey} />
- );
- }}
- cursor={{ stroke: "rgba(150,150,150,0.3)" }}
+ <ChartContainer config={chartConfig} className="h-[220px]">
+ <AreaChart
+ data={chartData}
+ margin={{ top: 8, right: 8, bottom: 0, left: 0 }}
+ >
+ <ChartGrid />
+ <ChartXAxis {...TIME_AXIS} />
+ <ChartYAxis allowDecimals={false} width={28} />
+ <ChartTooltip
+ content={
+ <ChartTooltipContent labelFormatter={formatDateLabel} />
+ }
+ />
+ {BUCKETS.map((b) => (
+ <Area
+ key={b.key}
+ type="monotone"
+ dataKey={b.key}
+ stackId="positions"
+ stroke={`var(--color-${b.key})`}
+ fill={`var(--color-${b.key})`}
+ fillOpacity={0.7}
+ isAnimationActive={false}
/>
- {BUCKETS.map((b) => (
- <Area
- key={b.key}
- type="monotone"
- dataKey={b.key}
- name={b.label}
- stackId="positions"
- stroke={b.color}
- fill={b.color}
- fillOpacity={0.7}
- isAnimationActive={false}
- />
- ))}
- </AreaChart>
- ) : null}
- </div>
+ ))}
+ </AreaChart>
+ </ChartContainer>
)
}
</QueryState>
@@ -180,35 +138,3 @@ export function RankTrackingOverview({
</div>
);
}
-
-function DistributionTooltip({
- label,
- byKey,
-}: {
- label: number;
- byKey: Map<string, number>;
-}) {
- return (
- <div className="rounded-md border border-base-300 bg-base-100 px-3 py-2 shadow-sm space-y-0.5">
- <p className="text-xs text-base-content/60">
- {new Date(label).toLocaleDateString("en-US", {
- month: "short",
- day: "numeric",
- year: "numeric",
- })}
- </p>
- {BUCKETS.map((b) => (
- <p key={b.key} className="text-xs flex items-center gap-1.5">
- <span
- className="size-2 rounded-sm"
- style={{ backgroundColor: b.color }}
- />
- <span className="text-base-content/60">{b.label}:</span>
- <span className="font-medium tabular-nums">
- {byKey.get(b.key) ?? 0}
- </span>
- </p>
- ))}
- </div>
- );
-}
diff --git a/src/client/features/rank-tracking/RankTrackingTrendChart.tsx b/src/client/features/rank-tracking/RankTrackingTrendChart.tsx
index 9745e3d4..256bd636 100644
--- a/src/client/features/rank-tracking/RankTrackingTrendChart.tsx
+++ b/src/client/features/rank-tracking/RankTrackingTrendChart.tsx
@@ -1,14 +1,16 @@
-import { useCallback, useRef, useState, type ReactNode } from "react";
+import type { ComponentProps } from "react";
+import { Line, LineChart, ReferenceArea } from "recharts";
import {
- CartesianGrid,
- Line,
- LineChart,
- ReferenceArea,
- Tooltip,
- XAxis,
- YAxis,
-} from "recharts";
-import type { TooltipContentProps } from "recharts";
+ ChartGrid,
+ ChartXAxis,
+ ChartYAxis,
+} from "@/client/components/ChartAxes";
+import {
+ ChartContainer,
+ ChartTooltip,
+ ChartTooltipContent,
+ type ChartConfig,
+} from "@/client/components/ui/chart";
export interface TrendSeries {
/** key into each data row holding the position value (1 = best, serpDepth = bottom band) */
@@ -19,13 +21,6 @@ export interface TrendSeries {
strokeDasharray?: string;
}
-interface TooltipEntry {
- dataKey?: string | number;
- name?: string;
- value: number | null;
- color?: string;
-}
-
/**
* Shared inverted-axis line chart for rank trends. Y-axis is reversed so #1 is
* pinned at the top and an improving line moves up. The very bottom of the
@@ -37,20 +32,20 @@ export function RankTrendChart({
data,
series,
serpDepth,
- height = 224,
- renderTooltip,
+ valueFormatter,
showBottomBand = false,
}: {
data: Array<Record<string, unknown>>;
series: TrendSeries[];
serpDepth: number;
- height?: number;
- renderTooltip: (label: number, entries: TooltipEntry[]) => ReactNode;
+ valueFormatter?: ComponentProps<typeof ChartTooltipContent>["valueFormatter"];
/** Show the muted "not in top {serpDepth}" band — only meaningful for a
* single keyword's position line, not for an averaged value. */
showBottomBand?: boolean;
}) {
- const { containerRef, width: chartWidth } = useChartWidth();
+ const config: ChartConfig = Object.fromEntries(
+ series.map((s) => [s.dataKey, { label: s.name, color: s.color }]),
+ );
return (
<div className="space-y-1">
@@ -60,115 +55,82 @@ export function RankTrendChart({
Better <span aria-hidden>↑</span>
</span>
</div>
- <div ref={containerRef} className="w-full min-w-0" style={{ height }}>
- {chartWidth > 0 ? (
- <LineChart
- width={chartWidth}
- height={height}
- data={data}
- margin={{ top: 8, right: 8, bottom: 0, left: 0 }}
- >
- <CartesianGrid
- strokeDasharray="3 3"
- stroke="currentColor"
- opacity={0.1}
- vertical={false}
+ <ChartContainer config={config} className="h-56">
+ <LineChart
+ data={data}
+ margin={{ top: 8, right: 8, bottom: 0, left: 0 }}
+ >
+ <ChartGrid />
+ {/* Muted bottom band: not in top {serpDepth} */}
+ {showBottomBand && (
+ <ReferenceArea
+ y1={serpDepth - 0.5}
+ y2={serpDepth}
+ fill="currentColor"
+ fillOpacity={0.06}
+ ifOverflow="extendDomain"
/>
- {/* Muted bottom band: not in top {serpDepth} */}
- {showBottomBand && (
- <ReferenceArea
- y1={serpDepth - 0.5}
- y2={serpDepth}
- fill="currentColor"
- fillOpacity={0.06}
- ifOverflow="extendDomain"
+ )}
+ <ChartXAxis {...TIME_AXIS} />
+ <ChartYAxis
+ reversed
+ domain={[1, serpDepth]}
+ allowDecimals={false}
+ width={32}
+ />
+ <ChartTooltip
+ content={
+ <ChartTooltipContent
+ labelFormatter={formatDateLabel}
+ valueFormatter={valueFormatter}
/>
- )}
- <XAxis
- dataKey="checkedAt"
- type="number"
- scale="time"
- domain={["dataMin", "dataMax"]}
- tickFormatter={formatDateTick}
- tick={{ fontSize: 10, fill: "#888" }}
- tickLine={false}
- axisLine={false}
- minTickGap={32}
- />
- <YAxis
- reversed
- domain={[1, serpDepth]}
- allowDecimals={false}
- tick={{ fontSize: 10, fill: "#888" }}
- tickLine={false}
- axisLine={false}
- width={32}
+ }
+ />
+ {series.map((s) => (
+ <Line
+ key={s.dataKey}
+ type="monotone"
+ dataKey={s.dataKey}
+ stroke={`var(--color-${s.dataKey})`}
+ strokeWidth={2}
+ strokeDasharray={s.strokeDasharray}
+ dot={{ r: 2 }}
+ activeDot={{ r: 4 }}
+ connectNulls={false}
+ isAnimationActive={false}
/>
- <Tooltip
- content={(props: TooltipContentProps) => {
- const { active, payload, label } = props;
- if (!active || !payload?.length || typeof label !== "number") {
- return null;
- }
- const entries: TooltipEntry[] = payload.map((p) => ({
- dataKey:
- typeof p.dataKey === "function" ? undefined : p.dataKey,
- name: typeof p.name === "string" ? p.name : undefined,
- value: typeof p.value === "number" ? p.value : null,
- color: p.color,
- }));
- return renderTooltip(label, entries);
- }}
- cursor={{ stroke: "rgba(150,150,150,0.3)" }}
- />
- {series.map((s) => (
- <Line
- key={s.dataKey}
- type="monotone"
- dataKey={s.dataKey}
- name={s.name}
- stroke={s.color}
- strokeWidth={2}
- strokeDasharray={s.strokeDasharray}
- dot={{ r: 2 }}
- activeDot={{ r: 4 }}
- connectNulls={false}
- isAnimationActive={false}
- />
- ))}
- </LineChart>
- ) : null}
- </div>
+ ))}
+ </LineChart>
+ </ChartContainer>
</div>
);
}
-export function formatDateTick(value: number): string {
+/** X axis for charts keyed by a `checkedAt` timestamp in ms. */
+export const TIME_AXIS = {
+ dataKey: "checkedAt",
+ type: "number",
+ scale: "time",
+ domain: ["dataMin", "dataMax"],
+ tickFormatter: formatDateTick,
+} as const;
+
+function formatDateTick(value: number): string {
return new Date(value).toLocaleDateString("en-US", {
month: "short",
day: "numeric",
});
}
-/** Responsive chart width via ResizeObserver — recharts needs an explicit px
- * width. Uses a callback ref so it measures whenever the chart node mounts,
- * including after a loading state (an effect-on-mount would miss that and leave
- * the width stuck at 0). Shared by the line chart and the distribution chart. */
-export function useChartWidth() {
- const [width, setWidth] = useState(0);
- const observerRef = useRef<ResizeObserver | null>(null);
-
- const containerRef = useCallback((el: HTMLDivElement | null) => {
- observerRef.current?.disconnect();
- observerRef.current = null;
- if (!el) return;
- setWidth(el.clientWidth);
- const observer = new ResizeObserver(() => setWidth(el.clientWidth));
- observer.observe(el);
- observerRef.current = observer;
- }, []);
-
- return { containerRef, width };
+/** Tooltip label for a `checkedAt` timestamp: "Sep 28, 2026". */
+export function formatDateLabel(label: unknown): string {
+ return typeof label === "number"
+ ? new Date(label).toLocaleDateString("en-US", {
+ month: "short",
+ day: "numeric",
+ year: "numeric",
+ })
+ : "";
}
/** 30d / 90d / All range toggle shared by the modal and overview charts. */