Skip to content

🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.

refactor(web): Make score analytics charts re-use design-system charts (#17885)

Ben Bachem96f58d09955a
diff --git a/web/src/components/design-system/charts/BarChart/BarChart.tsx b/web/src/components/design-system/charts/BarChart/BarChart.tsx
index f7d67a65d8..5e5452824f 100644
--- a/web/src/components/design-system/charts/BarChart/BarChart.tsx
+++ b/web/src/components/design-system/charts/BarChart/BarChart.tsx
@@ -1,13 +1,14 @@
"use client";
-import { type ComponentProps } from "react";
-
-import { BarChartCore } from "@/src/components/design-system/internal/charts/BarChartCore";
+import {
+ BarChartCore,
+ type SingleBarChartCoreProps,
+} from "@/src/components/design-system/internal/charts/BarChartCore";
export type { BarChartDatum } from "@/src/components/design-system/internal/charts/BarChartCore";
-type BarChartProps = Omit<ComponentProps<typeof BarChartCore>, "barSpacing">;
+type BarChartProps = Omit<SingleBarChartCoreProps, "barSpacing" | "layout">;
export function BarChart(props: BarChartProps) {
- return <BarChartCore {...props} barSpacing="default" />;
+ return <BarChartCore {...props} layout="single" barSpacing="default" />;
}
diff --git a/web/src/components/design-system/charts/GroupedBarChart/GroupedBarChart.stories.tsx b/web/src/components/design-system/charts/GroupedBarChart/GroupedBarChart.stories.tsx
new file mode 100644
index 0000000000..35bc6ecce8
--- /dev/null
+++ b/web/src/components/design-system/charts/GroupedBarChart/GroupedBarChart.stories.tsx
@@ -0,0 +1,190 @@
+import preview from "../../../../../.storybook/preview";
+import { expect, userEvent, within } from "storybook/test";
+import { GroupedBarChart } from "./GroupedBarChart";
+
+const meta = preview.meta({
+ component: GroupedBarChart,
+ parameters: { layout: "fullscreen" },
+ args: {
+ data: [
+ { key: "False", values: { first: 12, second: 8 } },
+ { key: "True", values: { first: 18, second: 10 } },
+ ],
+ series: [
+ { id: "first", label: "First", color: "hsl(var(--chart-1))" },
+ { id: "second", label: "Second", color: "hsl(var(--chart-2))" },
+ ],
+ },
+ decorators: [
+ (Story) => (
+ <div className="h-dvh w-full">
+ <Story />
+ </div>
+ ),
+ ],
+});
+
+export const Default = meta.story({});
+
+export const SideBySide = meta.story({
+ name: "(Test) Side by Side",
+ args: {
+ legend: { visibility: "visible", interaction: "toggle", summary: "none" },
+ },
+ play: async ({ canvasElement }) => {
+ const canvas = within(canvasElement);
+ const first = canvas.getByRole("graphics-symbol", { name: "First: 12" });
+ const second = canvas.getByRole("graphics-symbol", { name: "Second: 8" });
+ await expect(first.getBoundingClientRect().right).toBeLessThanOrEqual(
+ second.getBoundingClientRect().left,
+ );
+ first.focus();
+ const tooltip = await within(canvasElement.ownerDocument.body).findByRole(
+ "tooltip",
+ );
+ await expect(tooltip).toHaveTextContent("False");
+ await expect(tooltip).toHaveTextContent("First");
+ await expect(tooltip).toHaveTextContent("Second");
+ },
+});
+
+export const LegendHighlight = meta.story({
+ name: "(Test) Legend Highlight",
+ args: {
+ legend: {
+ visibility: "visible",
+ interaction: "highlight",
+ summary: "none",
+ },
+ },
+ play: async ({ canvasElement }) => {
+ const canvas = within(canvasElement);
+ await userEvent.click(
+ canvas.getByRole("button", { name: "Show only Second" }),
+ );
+ await expect(
+ canvas.getByRole("graphics-symbol", { name: "First: 12" }),
+ ).toHaveAttribute("fill", expect.stringContaining("20%"));
+ await expect(canvas.getAllByRole("graphics-symbol")).toHaveLength(4);
+ await userEvent.click(
+ canvas.getByRole("button", { name: "Show all series" }),
+ );
+ },
+});
+
+export const LegendToggle = meta.story({
+ name: "(Test) Legend Toggle",
+ args: {
+ legend: { visibility: "visible", interaction: "toggle", summary: "sum" },
+ },
+ play: async ({ canvasElement }) => {
+ const canvas = within(canvasElement);
+ await expect(canvas.getAllByRole("graphics-symbol")).toHaveLength(4);
+ await userEvent.click(canvas.getByRole("button", { name: "Hide Second" }));
+ await expect(
+ canvas.queryAllByRole("graphics-symbol", { name: /Second:/ }),
+ ).toHaveLength(0);
+ await userEvent.click(canvas.getByRole("button", { name: "Show Second" }));
+ await expect(canvas.getAllByRole("graphics-symbol")).toHaveLength(4);
+ },
+});
+
+export const NegativeAndMissingValues = meta.story({
+ name: "(Test) Negative and Missing Values",
+ args: {
+ data: [
+ { key: "Monday", values: { first: -12, second: 8 } },
+ { key: "Tuesday", values: { first: null, second: 0 } },
+ ],
+ },
+ play: async ({ canvasElement }) => {
+ const canvas = within(canvasElement);
+ await expect(canvas.getAllByRole("graphics-symbol")).toHaveLength(3);
+ await expect(
+ canvas.getByRole("graphics-symbol", { name: "First: -12" }),
+ ).toBeInTheDocument();
+ await expect(
+ canvas.getByRole("graphics-symbol", { name: "Second: 0" }),
+ ).toBeInTheDocument();
+ await expect(
+ canvasElement.querySelector("[data-zero-baseline]"),
+ ).toBeInTheDocument();
+ },
+});
+
+export const ManyBuckets = meta.story({
+ name: "(Test) Many Buckets",
+ args: {
+ data: Array.from({ length: 60 }, (_, index) => ({
+ key: `Bucket ${index + 1}`,
+ values: { first: index + 1, second: index % 3 === 0 ? null : 10 },
+ })),
+ },
+ decorators: [
+ (Story) => (
+ <div className="h-40 w-[320px]">
+ <Story />
+ </div>
+ ),
+ ],
+ play: async ({ canvasElement }) => {
+ await expect(
+ within(canvasElement).getAllByRole("graphics-symbol"),
+ ).toHaveLength(100);
+ await expect(
+ canvasElement.querySelectorAll("[data-x-axis-label]").length,
+ ).toBeLessThan(60);
+ },
+});
+
+export const LongCategoryLabels = meta.story({
+ name: "(Test) Long Category Labels",
+ args: {
+ data: Array.from({ length: 3 }, (_, index) => ({
+ key: `dataset-run-${index + 1}-transcription`,
+ values: { first: index + 1, second: 12 - index },
+ })),
+ },
+ decorators: [
+ (Story) => (
+ <div className="h-48 w-[320px]">
+ <Story />
+ </div>
+ ),
+ ],
+ play: async ({ canvasElement }) => {
+ const canvas = within(canvasElement);
+ await expect(
+ canvasElement.querySelector("[data-x-axis-label]"),
+ ).toHaveTextContent(/…$/);
+ await userEvent.hover(
+ canvas.getByRole("graphics-symbol", { name: "First: 1" }),
+ );
+ await expect(
+ canvasElement.querySelector("[data-active-x-axis-label]"),
+ ).toHaveTextContent("dataset-run-1-transcription");
+ await expect(
+ canvasElement.querySelector("[data-active-x-axis-label-background]"),
+ ).toBeInTheDocument();
+ },
+});
+
+export const FormattedValues = meta.story({
+ name: "(Test) Formatted Values",
+ args: {
+ valueFormatter: (value) => `${value.toLocaleString()} scores`,
+ tooltipFormatter: (key) => `Category: ${key}`,
+ },
+ play: async ({ canvasElement }) => {
+ within(canvasElement)
+ .getByRole("graphics-symbol", { name: "First: 12 scores" })
+ .focus();
+ const tooltip = await within(canvasElement.ownerDocument.body).findByRole(
+ "tooltip",
+ );
+ await expect(tooltip).toHaveTextContent("Category: False");
+ await expect(tooltip).toHaveTextContent("12 scores");
+ },
+});
+
+export const Empty = meta.story({ args: { data: [] } });
diff --git a/web/src/components/design-system/charts/GroupedBarChart/GroupedBarChart.tsx b/web/src/components/design-system/charts/GroupedBarChart/GroupedBarChart.tsx
new file mode 100644
index 0000000000..3b815792cf
--- /dev/null
+++ b/web/src/components/design-system/charts/GroupedBarChart/GroupedBarChart.tsx
@@ -0,0 +1,12 @@
+"use client";
+
+import {
+ BarChartCore,
+ type MultiSeriesBarChartCoreProps,
+} from "@/src/components/design-system/internal/charts/BarChartCore";
+
+export function GroupedBarChart(
+ props: Omit<MultiSeriesBarChartCoreProps, "layout">,
+) {
+ return <BarChartCore {...props} layout="grouped" />;
+}
diff --git a/web/src/components/design-system/charts/HistogramChart/HistogramChart.tsx b/web/src/components/design-system/charts/HistogramChart/HistogramChart.tsx
index 99ca25498b..3cf162ae34 100644
--- a/web/src/components/design-system/charts/HistogramChart/HistogramChart.tsx
+++ b/web/src/components/design-system/charts/HistogramChart/HistogramChart.tsx
@@ -1,14 +1,15 @@
"use client";
-import { type ComponentProps } from "react";
-
-import { BarChartCore } from "@/src/components/design-system/internal/charts/BarChartCore";
+import {
+ BarChartCore,
+ type SingleBarChartCoreProps,
+} from "@/src/components/design-system/internal/charts/BarChartCore";
type HistogramChartProps = Omit<
- ComponentProps<typeof BarChartCore>,
- "barSpacing"
+ SingleBarChartCoreProps,
+ "barSpacing" | "layout"
>;
export function HistogramChart(props: HistogramChartProps) {
- return <BarChartCore {...props} barSpacing="histogram" />;
+ return <BarChartCore {...props} layout="single" barSpacing="histogram" />;
}
diff --git a/web/src/components/design-system/charts/StackedBarChart/StackedBarChart.stories.tsx b/web/src/components/design-system/charts/StackedBarChart/StackedBarChart.stories.tsx
index 69d06ad9e5..4f746063fb 100644
--- a/web/src/components/design-system/charts/StackedBarChart/StackedBarChart.stories.tsx
+++ b/web/src/components/design-system/charts/StackedBarChart/StackedBarChart.stories.tsx
@@ -239,14 +239,12 @@ export const SyncedBucket = meta.story({
sync: { activeKey: "Tuesday", onActiveKeyChange: () => undefined },
},
play: async ({ canvasElement }) => {
- const line = canvasElement.querySelector("[data-active-reference-line]");
- const bar = within(canvasElement).getByRole("graphics-symbol", {
- name: "API: 18",
- });
- if (!line) throw new Error("Active reference line missing");
- await expect(Number(line.getAttribute("x1"))).toBeCloseTo(
- Number(bar.getAttribute("x")) + Number(bar.getAttribute("width")) / 2,
- );
+ await expect(
+ canvasElement.querySelector("[data-active-x-axis-label]"),
+ ).toHaveTextContent("Tuesday");
+ await expect(
+ canvasElement.querySelector("[data-active-reference-line]"),
+ ).not.toBeInTheDocument();
},
});
diff --git a/web/src/components/design-system/charts/StackedBarChart/StackedBarChart.tsx b/web/src/components/design-system/charts/StackedBarChart/StackedBarChart.tsx
index 4f735cd0a6..f236e63a2d 100644
--- a/web/src/components/design-system/charts/StackedBarChart/StackedBarChart.tsx
+++ b/web/src/components/design-system/charts/StackedBarChart/StackedBarChart.tsx
@@ -1,492 +1,12 @@
"use client";
-import { useId, useState } from "react";
-import { scaleLinear } from "d3-scale";
-
-import { ChartContainer } from "@/src/components/design-system/charts/ChartContainer";
-import { ChartLegend } from "@/src/components/design-system/internal/charts/ChartLegend";
-import { CartesianChart } from "@/src/components/design-system/internal/charts/CartesianChart";
-import { CartesianLayout } from "@/src/components/design-system/internal/charts/CartesianLayout";
-import { ChartTooltip } from "@/src/components/design-system/internal/charts/ChartTooltip";
-import { createBarBandScale } from "@/src/components/design-system/internal/charts/fns/createBarBandScale";
-
-import type { LineChartLegend } from "@/src/components/design-system/charts/LineChart/LineChart";
-
-export function StackedBarChart({
- data,
- series,
- valueFormatter = (value) => value.toLocaleString(),
- tickFormatter = (value) => value,
- categoryXAxisLabels = false,
- tooltipFormatter = (value) => value,
- hideXAxisLabels = false,
- sync,
- legend,
-}: {
- data: { key: string; values: Record<string, number | null> }[];
- series: { id: string; label: string; color: string }[];
- valueFormatter?: (value: number) => string;
- tickFormatter?: (value: string) => string;
- categoryXAxisLabels?: boolean;
- tooltipFormatter?: (value: string) => string;
- hideXAxisLabels?: boolean;
- sync?: {
- activeKey: string | undefined;
- onActiveKeyChange: (key: string | undefined) => void;
- };
- legend?: LineChartLegend;
-}) {
- const [hoveredIndex, setHoveredIndex] = useState<number>();
- const clipId = useId();
- const summaries = new Map(
- series.map((item) => {
- const values = data.flatMap((datum) => {
- const value = datum.values[item.id];
- return typeof value === "number" && Number.isFinite(value)
- ? [value]
- : [];
- });
- return [
- item.id,
- values.length ? values.reduce((sum, value) => sum + value, 0) : null,
- ] as const;
- }),
- );
- const initialHidden = new Set<string>();
- if (
- legend?.visibility !== "hidden" &&
- legend?.interaction === "toggle" &&
- legend.maxVisibleSeries !== undefined
- ) {
- const keep = new Set(
- [...series]
- .sort(
- (left, right) =>
- (summaries.get(right.id) ?? -Infinity) -
- (summaries.get(left.id) ?? -Infinity),
- )
- .slice(0, Math.max(0, legend.maxVisibleSeries))
- .map((item) => item.id),
- );
- for (const item of series)
- if (!keep.has(item.id)) initialHidden.add(item.id);
- }
- const seedKey = `${legend?.visibility ?? "hidden"}|${legend?.visibility !== "hidden" ? legend?.interaction : ""}|${legend?.visibility !== "hidden" && legend?.interaction === "toggle" ? (legend.maxVisibleSeries ?? "") : ""}|${JSON.stringify(series.map((item) => item.id).sort())}`;
- const [legendState, setLegendState] = useState({
- seedKey,
- highlightedId: undefined as string | undefined,
- visibilityOverrides: new Map<string, boolean>(),
- });
- const effectiveState =
- legendState.seedKey === seedKey
- ? legendState
- : {
- seedKey,
- highlightedId: undefined,
- visibilityOverrides: new Map<string, boolean>(),
- };
- const { highlightedId, visibilityOverrides } = effectiveState;
- const hiddenIds = new Set(initialHidden);
- for (const [id, hidden] of visibilityOverrides) {
- if (hidden) hiddenIds.add(id);
- else hiddenIds.delete(id);
- }
- const visibleSeries = series.filter((item) => !hiddenIds.has(item.id));
- const showLegend =
- legend?.visibility === "visible" ||
- (legend?.visibility === "auto" &&
- (series.length > 1 || hiddenIds.size > 0));
- const totals = data.map((datum) => {
- let positive = 0;
- let negative = 0;
- for (const item of visibleSeries) {
- const value = datum.values[item.id];
- if (typeof value !== "number" || !Number.isFinite(value)) continue;
- if (value >= 0) positive += value;
- else negative += value;
- }
- return { positive, negative };
- });
- const min = Math.min(0, ...totals.map((total) => total.negative));
- const max = Math.max(1, ...totals.map((total) => total.positive));
-
- return (
- <div className="flex size-full min-w-0 flex-col">
- <div className="min-h-0 flex-1">
- <ChartContainer>
- {({ width, height }) => (
- <CartesianLayout
- width={width}
- height={height}
- showXAxisLabels={!hideXAxisLabels}
- >
- {({ measuredPlot, maxYTicks, plotForTicks }) => {
- const y = scaleLinear()
- .domain([min, max])
- .nice(maxYTicks)
- .range([
- measuredPlot.top + measuredPlot.height,
- measuredPlot.top,
- ]);
- const yTicks = y.ticks(maxYTicks);
- const plot = plotForTicks(yTicks.map(valueFormatter));
- const x = createBarBandScale(
- data.length,
- plot.left,
- plot.width,
- "default",
- );
- const syncedIndex = data.findIndex(
- (datum) => datum.key === sync?.activeKey,
- );
- const activeIndex = hoveredIndex ?? syncedIndex;
- let previousTickRight = -Infinity;
- const xTicks: {
- key: string;
- x: number;
- label: string;
- textAnchor?: "end";
- }[] = [];
- data.forEach((datum, index) => {
- const label = tickFormatter(datum.key);
- const center = (x(index) ?? plot.left) + x.bandwidth() / 2;
- const labelWidth = label.length * 7;
- if (categoryXAxisLabels) {
- const right = Math.min(width - 8, center);
- const left = right - labelWidth;
- if (left >= 8 && left >= previousTickRight + 16) {
- xTicks.push({
- key: datum.key,
- x: right,
- label,
- textAnchor: "end",
- });
- previousTickRight = right;
- }
- return;
- }
- if (index === data.length - 1) {
- const right = Math.min(width - 8, center + labelWidth / 2);
- const left = right - labelWidth;
- while (xTicks.length > 0 && left < previousTickRight + 16) {
- xTicks.pop();
- const previous = xTicks.at(-1);
- previousTickRight = previous
- ? previous.x + previous.label.length * 3.5
- : -Infinity;
- }
- if (left >= 8) {
- xTicks.push({
- key: datum.key,
- x: right,
- label,
- textAnchor: "end",
- });
- }
- return;
- }
- const left = center - labelWidth / 2;
- if (
- left < previousTickRight + 16 ||
- center + labelWidth / 2 > width - 8
- ) {
- return;
- }
- previousTickRight = center + labelWidth / 2;
- xTicks.push({ key: datum.key, x: center, label });
- });
-
- if (
- width <= 0 ||
- height <= 0 ||
- plot.width <= 0 ||
- plot.height <= 0
- ) {
- return (
- <svg width={width} height={height} aria-hidden="true" />
- );
- }
-
- return (
- <ChartTooltip>
- {({ activeIndex: tooltipIndex, getReferenceProps }) => (
- <CartesianChart
- width={width}
- height={height}
- ariaLabel="Stacked bar chart"
- plot={plot}
- yTicks={yTicks}
- y={y}
- valueFormatter={valueFormatter}
- zeroY={min < 0 ? y(0) : undefined}
- xAxis={
- hideXAxisLabels
- ? undefined
- : {
- ticks: xTicks,
- activeKey:
- activeIndex >= 0
- ? data[activeIndex]?.key
- : undefined,
- alignment: "center",
- }
- }
- >
- {activeIndex >= 0 && activeIndex < data.length ? (
- <line
- data-active-reference-line=""
- x1={
- (x(activeIndex) ?? plot.left) + x.bandwidth() / 2
- }
- x2={
- (x(activeIndex) ?? plot.left) + x.bandwidth() / 2
- }
- y1={plot.top}
- y2={plot.top + plot.height}
- stroke="hsl(var(--muted-foreground))"
- strokeDasharray="3 3"
- aria-hidden="true"
- />
- ) : null}
- {data.map((datum, index) => {
- const left = x(index);
- if (left === undefined) return null;
- let positive = 0;
- let negative = 0;
- const items = visibleSeries.flatMap((item) => {
- const value = datum.values[item.id];
- return typeof value === "number" &&
- Number.isFinite(value)
- ? [
- {
- id: item.id,
- label: item.label,
- value: valueFormatter(value),
- color: item.color,
- },
- ]
- : [];
- });
- const referenceProps = getReferenceProps({
- type: "items",
- index,
- heading: tooltipFormatter(datum.key),
- items: items.sort(
- (a, b) =>
- (datum.values[b.id] ?? 0) -
- (datum.values[a.id] ?? 0),
- ),
- });
- return (
- <g key={`${datum.key}-${index}`}>
- <defs>
- <clipPath id={`${clipId}-positive-${index}`}>
- <rect
- x={left}
- y={y(totals[index]?.positive ?? 0)}
- width={x.bandwidth()}
- height={
- y(0) - y(totals[index]?.positive ?? 0)
- }
- rx={4}
- />
- </clipPath>
- <clipPath id={`${clipId}-negative-${index}`}>
- <rect
- x={left}
- y={y(0)}
- width={x.bandwidth()}
- height={
- y(totals[index]?.negative ?? 0) - y(0)
- }
- rx={4}
- />
- </clipPath>
- </defs>
- <rect
- x={left}
- y={plot.top}
- width={x.bandwidth()}
- height={plot.height}
- fill="transparent"
- aria-hidden="true"
- {...referenceProps}
- onPointerEnter={(event) => {
- referenceProps.onPointerEnter(event);
- setHoveredIndex(index);
- sync?.onActiveKeyChange(datum.key);
- }}
- onPointerMove={(event) => {
- referenceProps.onPointerMove(event);
- setHoveredIndex(index);
- sync?.onActiveKeyChange(datum.key);
- }}
- onPointerLeave={() => {
- referenceProps.onPointerLeave();
- setHoveredIndex(undefined);
- sync?.onActiveKeyChange(undefined);
- }}
- />
- {visibleSeries.map((item) => {
- const value = datum.values[item.id];
- if (
- typeof value !== "number" ||
- !Number.isFinite(value)
- )
- return null;
- const start = value >= 0 ? positive : negative;
- if (value >= 0) positive += value;
- else negative += value;
- const top =
- value === 0
- ? y(start) - 1
- : Math.min(y(start), y(start + value));
- const barHeight = Math.max(
- 1,
- Math.abs(y(start) - y(start + value)),
- );
- let colorStrength = 100;
- if (
- highlightedId !== undefined &&
- item.id !== highlightedId
- )
- colorStrength = 20;
- else if (
- tooltipIndex !== undefined &&
- tooltipIndex !== index
- )
- colorStrength = 30;
- const fill =
- colorStrength === 100
- ? item.color
- : `color-mix(in srgb, ${item.color} ${colorStrength}%, hsl(var(--background)))`;
- return (
- <rect
- key={item.id}
- x={left}
- y={top}
- width={x.bandwidth()}
- height={barHeight}
- clipPath={
- value === 0
- ? undefined
- : `url(#${clipId}-${value >= 0 ? "positive" : "negative"}-${index})`
- }
- fill={fill}
- role="graphics-symbol"
- tabIndex={0}
- aria-label={`${item.label}: ${valueFormatter(value)}`}
- className="outline-hidden transition-[fill] duration-150 focus-visible:outline-2 focus-visible:outline-offset-2"
- {...referenceProps}
- onPointerEnter={(event) => {
- referenceProps.onPointerEnter(event);
- setHoveredIndex(index);
- sync?.onActiveKeyChange(datum.key);
- }}
- onPointerMove={(event) => {
- referenceProps.onPointerMove(event);
- setHoveredIndex(index);
- sync?.onActiveKeyChange(datum.key);
- }}
- onFocus={(event) => {
- referenceProps.onFocus(event);
- setHoveredIndex(index);
- sync?.onActiveKeyChange(datum.key);
- }}
- onPointerLeave={() => {
- referenceProps.onPointerLeave();
- setHoveredIndex(undefined);
- sync?.onActiveKeyChange(undefined);
- }}
- onBlur={() => {
- referenceProps.onBlur();
- setHoveredIndex(undefined);
- sync?.onActiveKeyChange(undefined);
- }}
- />
- );
- })}
- </g>
- );
- })}
- </CartesianChart>
- )}
- </ChartTooltip>
- );
- }}
- </CartesianLayout>
- )}
- </ChartContainer>
- </div>
- {showLegend ? (
- <ChartLegend
- selectionActions={
- legend.interaction === "toggle"
- ? {
- allSelected: hiddenIds.size === 0,
- onSelectAll: () =>
- setLegendState({
- ...effectiveState,
- visibilityOverrides: new Map(
- series.map((item) => [item.id, false]),
- ),
- }),
- onDeselectAll: () =>
- setLegendState({
- ...effectiveState,
- visibilityOverrides: new Map(
- series.map((item) => [item.id, true]),
- ),
- }),
- }
- : undefined
- }
- items={series.map((item) => {
- const hidden = hiddenIds.has(item.id);
- const focused = highlightedId === item.id;
- let label = `Show only ${item.label}`;
- if (legend.interaction === "toggle")
- label = hidden ? `Show ${item.label}` : `Hide ${item.label}`;
- else if (focused) label = "Show all series";
- const summary = summaries.get(item.id);
- return {
- id: item.id,
- label: item.label,
- color: item.color,
- value:
- legend.summary === "sum" &&
- summary !== null &&
- summary !== undefined
- ? { label: "Sum", value: valueFormatter(summary) }
- : undefined,
- muted:
- hidden ||
- (legend.interaction === "highlight" &&
- highlightedId !== undefined &&
- !focused),
- action: {
- label,
- pressed: legend.interaction === "toggle" ? !hidden : focused,
- onClick: () => {
- if (legend.interaction === "toggle") {
- const next = new Map(visibilityOverrides);
- next.set(item.id, !hidden);
- setLegendState({
- ...effectiveState,
- visibilityOverrides: next,
- });
- return;
- }
- setLegendState({
- ...effectiveState,
- highlightedId: focused ? undefined : item.id,
- });
- },
- },
- };
- })}
- />
- ) : null}
- </div>
- );
+import {
+ BarChartCore,
+ type MultiSeriesBarChartCoreProps,
+} from "@/src/components/design-system/internal/charts/BarChartCore";
+
+export function StackedBarChart(
+ props: Omit<MultiSeriesBarChartCoreProps, "layout">,
+) {
+ return <BarChartCore {...props} layout="stacked" />;
}
diff --git a/web/src/components/design-system/internal/charts/BarChartCore.tsx b/web/src/components/design-system/internal/charts/BarChartCore.tsx
index f584d07c4c..917cf0e2fe 100644
--- a/web/src/components/design-system/internal/charts/BarChartCore.tsx
+++ b/web/src/components/design-system/internal/charts/BarChartCore.tsx
@@ -1,5 +1,6 @@
"use client";
+import { useId, useState } from "react";
import { scaleLinear } from "d3-scale";
import { ChartContainer } from "@/src/components/design-system/charts/ChartContainer";
@@ -12,6 +13,7 @@ import {
} from "@/src/components/design-system/internal/charts/ChartLegend";
import { ChartTooltip } from "@/src/components/design-system/internal/charts/ChartTooltip";
import { createBarBandScale } from "@/src/components/design-system/internal/charts/fns/createBarBandScale";
+import type { LineChartLegend } from "@/src/components/design-system/charts/LineChart/LineChart";
export type BarChartDatum = {
label: string;
@@ -19,7 +21,8 @@ export type BarChartDatum = {
color?: string;
};
-type BarChartCoreProps = {
+export type SingleBarChartCoreProps = {
+ layout: "single";
data: BarChartDatum[];
valueFormatter?: (value: number) => string;
color?: string;
@@ -33,9 +36,34 @@ type BarChartCoreProps = {
barSpacing: "default" | "histogram";
};
+export type MultiSeriesBarChartCoreProps = {
+ data: { key: string; values: Record<string, number | null> }[];
+ series: { id: string; label: string; color: string }[];
+ valueFormatter?: (value: number) => string;
+ tickFormatter?: (value: string) => string;
+ categoryXAxisLabels?: boolean;
+ tooltipFormatter?: (value: string) => string;
+ hideXAxisLabels?: boolean;
+ sync?: {
+ activeKey: string | undefined;
+ onActiveKeyChange: (key: string | undefined) => void;
+ };
+ legend?: LineChartLegend;
+ layout: "stacked" | "grouped";
+};
+
+export function BarChartCore(
+ props: SingleBarChartCoreProps | MultiSeriesBarChartCoreProps,
+) {
+ if (props.layout === "single") {
+ return <SingleBarChart {...props} />;
+ }
+ return <MultiSeriesBarChart {...props} />;
+}
+
// Shared chart mechanics for categorical bars and histogram bins; the public
// components fix spacing to match their respective data semantics.
-export function BarChartCore({
+function SingleBarChart({
data,
valueFormatter = (value) => value.toLocaleString(),
color = "hsl(var(--chart-1))",
@@ -47,7 +75,7 @@ export function BarChartCore({
tooltipHeading,
tooltipValueLabel,
barSpacing,
-}: BarChartCoreProps) {
+}: SingleBarChartCoreProps) {
const firstColor = data[0]?.color ?? color;
const hasDistinctColors = data.some(
(datum) => (datum.color ?? color) !== firstColor,
@@ -260,3 +288,532 @@ export function BarChartCore({
</div>
);
}
+
+function MultiSeriesBarChart({
+ data,
+ series,
+ valueFormatter = (value) => value.toLocaleString(),
+ tickFormatter = (value) => value,
+ categoryXAxisLabels = false,
+ tooltipFormatter = (value) => value,
+ hideXAxisLabels = false,
+ sync,
+ legend,
+ layout,
+}: MultiSeriesBarChartCoreProps) {
+ const [hoveredIndex, setHoveredIndex] = useState<number>();
+ const clipId = useId();
+ const summaries = new Map(
+ series.map((item) => {
+ const values = data.flatMap((datum) => {
+ const value = datum.values[item.id];
+ return typeof value === "number" && Number.isFinite(value)
+ ? [value]
+ : [];
+ });
+ return [
+ item.id,
+ values.length ? values.reduce((sum, value) => sum + value, 0) : null,
+ ] as const;
+ }),
+ );
+ const initialHidden = new Set<string>();
+ if (
+ legend?.visibility !== "hidden" &&
+ legend?.interaction === "toggle" &&
+ legend.maxVisibleSeries !== undefined
+ ) {
+ const keep = new Set(
+ [...series]
+ .sort(
+ (left, right) =>
+ (summaries.get(right.id) ?? -Infinity) -
+ (summaries.get(left.id) ?? -Infinity),
+ )
+ .slice(0, Math.max(0, legend.maxVisibleSeries))
+ .map((item) => item.id),
+ );
+ for (const item of series)
+ if (!keep.has(item.id)) initialHidden.add(item.id);
+ }
+ const seedKey = `${legend?.visibility ?? "hidden"}|${legend?.visibility !== "hidden" ? legend?.interaction : ""}|${legend?.visibility !== "hidden" && legend?.interaction === "toggle" ? (legend.maxVisibleSeries ?? "") : ""}|${JSON.stringify(series.map((item) => item.id).sort())}`;
+ const [legendState, setLegendState] = useState({
+ seedKey,
+ highlightedId: undefined as string | undefined,
+ visibilityOverrides: new Map<string, boolean>(),
+ });
+ const effectiveState =
+ legendState.seedKey === seedKey
+ ? legendState
+ : {
+ seedKey,
+ highlightedId: undefined,
+ visibilityOverrides: new Map<string, boolean>(),
+ };
+ const { highlightedId, visibilityOverrides } = effectiveState;
+ const hiddenIds = new Set(initialHidden);
+ for (const [id, hidden] of visibilityOverrides) {
+ if (hidden) hiddenIds.add(id);
+ else hiddenIds.delete(id);
+ }
+ const visibleSeries = series.filter((item) => !hiddenIds.has(item.id));
+ const showLegend =
+ legend?.visibility === "visible" ||
+ (legend?.visibility === "auto" &&
+ (series.length > 1 || hiddenIds.size > 0));
+ const totals = data.map((datum) => {
+ let positive = 0;
+ let negative = 0;
+ for (const item of visibleSeries) {
+ const value = datum.values[item.id];
+ if (typeof value !== "number" || !Number.isFinite(value)) continue;
+ if (value >= 0) positive += value;
+ else negative += value;
+ }
+ return { positive, negative };
+ });
+ const individualValues = data.flatMap((datum) =>
+ visibleSeries.flatMap((item) => {
+ const value = datum.values[item.id];
+ return typeof value === "number" && Number.isFinite(value) ? [value] : [];
+ }),
+ );
+ const min =
+ layout === "grouped"
+ ? Math.min(0, ...individualValues)
+ : Math.min(0, ...totals.map((total) => total.negative));
+ const max =
+ layout === "grouped"
+ ? Math.max(1, ...individualValues)
+ : Math.max(1, ...totals.map((total) => total.positive));
+
+ return (
+ <div className="flex size-full min-w-0 flex-col">
+ <div className="min-h-0 flex-1">
+ <ChartContainer>
+ {({ width, height }) => (
+ <CartesianLayout
+ width={width}
+ height={height}
+ showXAxisLabels={!hideXAxisLabels}
+ >
+ {({ measuredPlot, maxYTicks, plotForTicks }) => {
+ const y = scaleLinear()
+ .domain([min, max])
+ .nice(maxYTicks)
+ .range([
+ measuredPlot.top + measuredPlot.height,
+ measuredPlot.top,
+ ]);
+ const yTicks = y.ticks(maxYTicks);
+ const plot = plotForTicks(yTicks.map(valueFormatter));
+ const x = createBarBandScale(
+ data.length,
+ plot.left,
+ plot.width,
+ "default",
+ );
+ const syncedIndex = data.findIndex(
+ (datum) => datum.key === sync?.activeKey,
+ );
+ const activeIndex = hoveredIndex ?? syncedIndex;
+ let previousTickRight = -Infinity;
+ const xTicks: {
+ key: string;
+ x: number;
+ label: string;
+ maxWidth?: number;
+ textAnchor?: "end";
+ }[] = [];
+ data.forEach((datum, index) => {
+ const label = tickFormatter(datum.key);
+ const center = (x(index) ?? plot.left) + x.bandwidth() / 2;
+ if (layout === "grouped") {
+ const maxWidth = Math.max(0, x.bandwidth() - 16);
+ const labelWidth = Math.min(label.length * 7, maxWidth);
+ if (
+ maxWidth < 14 ||
+ center - labelWidth / 2 < previousTickRight + 16 ||
+ center + labelWidth / 2 > width - 8
+ ) {
+ return;
+ }
+ xTicks.push({
+ key: datum.key,
+ x: center,
+ label,
+ maxWidth,
+ });
+ previousTickRight = center + labelWidth / 2;
+ return;
+ }
+ const labelWidth = label.length * 7;
+ if (categoryXAxisLabels) {
+ const right = Math.min(width - 8, center);
+ const left = right - labelWidth;
+ if (left >= 8 && left >= previousTickRight + 16) {
+ xTicks.push({
+ key: datum.key,
+ x: right,
+ label,
+ textAnchor: "end",
+ });
+ previousTickRight = right;
+ }
+ return;
+ }
+ if (index === data.length - 1) {
+ const right = Math.min(width - 8, center + labelWidth / 2);
+ const left = right - labelWidth;
+ while (xTicks.length > 0 && left < previousTickRight + 16) {
+ xTicks.pop();
+ const previous = xTicks.at(-1);
+ previousTickRight = previous
+ ? previous.x + previous.label.length * 3.5
+ : -Infinity;
+ }
+ if (left >= 8) {
+ xTicks.push({
+ key: datum.key,
+ x: right,
+ label,
+ textAnchor: "end",
+ });
+ }
+ return;
+ }
+ const left = center - labelWidth / 2;
+ if (
+ left < previousTickRight + 16 ||
+ center + labelWidth / 2 > width - 8
+ ) {
+ return;
+ }
+ previousTickRight = center + labelWidth / 2;
+ xTicks.push({ key: datum.key, x: center, label });
+ });
+
+ if (
+ width <= 0 ||
+ height <= 0 ||
+ plot.width <= 0 ||
+ plot.height <= 0
+ ) {
+ return (
+ <svg width={width} height={height} aria-hidden="true" />
+ );
+ }
+
+ return (
+ <ChartTooltip>
+ {({ activeIndex: tooltipIndex, getReferenceProps }) => (
+ <CartesianChart
+ width={width}
+ height={height}
+ ariaLabel={
+ layout === "grouped"
+ ? "Grouped bar chart"
+ : "Stacked bar chart"
+ }
+ plot={plot}
+ yTicks={yTicks}
+ y={y}
+ valueFormatter={valueFormatter}
+ zeroY={min < 0 ? y(0) : undefined}
+ xAxis={
+ hideXAxisLabels
+ ? undefined
+ : {
+ ticks: xTicks,
+ activeKey:
+ activeIndex >= 0
+ ? data[activeIndex]?.key
+ : undefined,
+ showCategoryTicks: layout === "grouped",
+ alignment: "center",
+ }
+ }
+ >
+ {data.map((datum, index) => {
+ const left = x(index);
+ if (left === undefined) return null;
+ let positive = 0;
+ let negative = 0;
+ const items = visibleSeries.flatMap((item) => {
+ const value = datum.values[item.id];
+ return typeof value === "number" &&
+ Number.isFinite(value)
+ ? [
+ {
+ id: item.id,
+ label: item.label,
+ value: valueFormatter(value),
+ color: item.color,
+ },
+ ]
+ : [];
+ });
+ const referenceProps = getReferenceProps({
+ type: "items",
+ index,
+ heading: tooltipFormatter(datum.key),
+ items: items.sort(
+ (a, b) =>
+ (datum.values[b.id] ?? 0) -
+ (datum.values[a.id] ?? 0),
+ ),
+ });
+ return (
+ <g key={`${datum.key}-${index}`}>
+ <defs>
+ <clipPath id={`${clipId}-positive-${index}`}>
+ <rect
+ x={left}
+ y={y(totals[index]?.positive ?? 0)}
+ width={x.bandwidth()}
+ height={
+ y(0) - y(totals[index]?.positive ?? 0)
+ }
+ rx={4}
+ />
+ </clipPath>
+ <clipPath id={`${clipId}-negative-${index}`}>
+ <rect
+ x={left}
+ y={y(0)}
+ width={x.bandwidth()}
+ height={
+ y(totals[index]?.negative ?? 0) - y(0)
+ }
+ rx={4}
+ />
+ </clipPath>
+ </defs>
+ <rect
+ x={left}
+ y={plot.top}
+ width={x.bandwidth()}
+ height={plot.height}
+ fill="transparent"
+ aria-hidden="true"
+ {...referenceProps}
+ onPointerEnter={(event) => {
+ referenceProps.onPointerEnter(event);
+ setHoveredIndex(index);
+ sync?.onActiveKeyChange(datum.key);
+ }}
+ onPointerMove={(event) => {
+ referenceProps.onPointerMove(event);
+ setHoveredIndex(index);
+ sync?.onActiveKeyChange(datum.key);
+ }}
+ onPointerLeave={() => {
+ referenceProps.onPointerLeave();
+ setHoveredIndex(undefined);
+ sync?.onActiveKeyChange(undefined);
+ }}
+ />
+ {visibleSeries.map((item, seriesIndex) => {
+ const value = datum.values[item.id];
+ if (
+ typeof value !== "number" ||
+ !Number.isFinite(value)
+ )
+ return null;
+ let start = 0;
+ if (layout === "stacked") {
+ start = value >= 0 ? positive : negative;
+ }
+ if (value >= 0) positive += value;
+ else negative += value;
+ const top =
+ value === 0
+ ? y(start) - 1
+ : Math.min(y(start), y(start + value));
+ const barHeight = Math.max(
+ 1,
+ Math.abs(y(start) - y(start + value)),
+ );
+ let colorStrength = 100;
+ if (
+ highlightedId !== undefined &&
+ item.id !== highlightedId
+ )
+ colorStrength = 20;
+ else if (
+ tooltipIndex !== undefined &&
+ tooltipIndex !== index
+ )
+ colorStrength = 30;
+ const barWidth =
+ layout === "grouped"
+ ? x.bandwidth() /
+ Math.max(visibleSeries.length, 1)
+ : x.bandwidth();
+ const barLeft =
+ left +
+ (layout === "grouped"
+ ? seriesIndex * barWidth
+ : 0);
+ const radius = Math.min(
+ 4,
+ barWidth / 2,
+ barHeight / 2,
+ );
+ const barPath =
+ value >= 0
+ ? `M ${barLeft} ${top + barHeight} V ${top + radius} Q ${barLeft} ${top} ${barLeft + radius} ${top} H ${barLeft + barWidth - radius} Q ${barLeft + barWidth} ${top} ${barLeft + barWidth} ${top + radius} V ${top + barHeight} Z`
+ : `M ${barLeft} ${top} V ${top + barHeight - radius} Q ${barLeft} ${top + barHeight} ${barLeft + radius} ${top + barHeight} H ${barLeft + barWidth - radius} Q ${barLeft + barWidth} ${top + barHeight} ${barLeft + barWidth} ${top + barHeight - radius} V ${top} Z`;
+ const fill =
+ colorStrength === 100
+ ? item.color
+ : `color-mix(in srgb, ${item.color} ${colorStrength}%, hsl(var(--background)))`;
+ const sharedBarProps = {
+ fill,
+ role: "graphics-symbol" as const,
+ tabIndex: 0,
+ "aria-label": `${item.label}: ${valueFormatter(value)}`,
+ className:
+ "outline-hidden transition-[fill] duration-150 focus-visible:outline-2 focus-visible:outline-offset-2",
+ ...referenceProps,
+ onPointerEnter: (
+ event: React.PointerEvent<SVGElement>,
+ ) => {
+ referenceProps.onPointerEnter(event);
+ setHoveredIndex(index);
+ sync?.onActiveKeyChange(datum.key);
+ },
+ onPointerMove: (
+ event: React.PointerEvent<SVGElement>,
+ ) => {
+ referenceProps.onPointerMove(event);
+ setHoveredIndex(index);
+ sync?.onActiveKeyChange(datum.key);
+ },
+ onFocus: (
+ event: React.FocusEvent<SVGElement>,
+ ) => {
+ referenceProps.onFocus(event);
+ setHoveredIndex(index);
+ sync?.onActiveKeyChange(datum.key);
+ },
+ onPointerLeave: () => {
+ referenceProps.onPointerLeave();
+ setHoveredIndex(undefined);
+ sync?.onActiveKeyChange(undefined);
+ },
+ onBlur: () => {
+ referenceProps.onBlur();
+ setHoveredIndex(undefined);
+ sync?.onActiveKeyChange(undefined);
+ },
+ };
+ if (layout === "stacked") {
+ return (
+ <rect
+ key={item.id}
+ x={barLeft}
+ y={top}
+ width={barWidth}
+ height={barHeight}
+ clipPath={
+ value === 0
+ ? undefined
+ : `url(#${clipId}-${value >= 0 ? "positive" : "negative"}-${index})`
+ }
+ {...sharedBarProps}
+ />
+ );
+ }
+ return (
+ <path
+ key={item.id}
+ d={barPath}
+ {...sharedBarProps}
+ />
+ );
+ })}
+ </g>
+ );
+ })}
+ </CartesianChart>
+ )}
+ </ChartTooltip>
+ );
+ }}
+ </CartesianLayout>
+ )}
+ </ChartContainer>
+ </div>
+ {showLegend ? (
+ <ChartLegend
+ selectionActions={
+ legend.interaction === "toggle"
+ ? {
+ allSelected: hiddenIds.size === 0,
+ onSelectAll: () =>
+ setLegendState({
+ ...effectiveState,
+ visibilityOverrides: new Map(
+ series.map((item) => [item.id, false]),
+ ),
+ }),
+ onDeselectAll: () =>
+ setLegendState({
+ ...effectiveState,
+ visibilityOverrides: new Map(
+ series.map((item) => [item.id, true]),
+ ),
+ }),
+ }
+ : undefined
+ }
+ items={series.map((item) => {
+ const hidden = hiddenIds.has(item.id);
+ const focused = highlightedId === item.id;
+ let label = `Show only ${item.label}`;
+ if (legend.interaction === "toggle")
+ label = hidden ? `Show ${item.label}` : `Hide ${item.label}`;
+ else if (focused) label = "Show all series";
+ const summary = summaries.get(item.id);
+ return {
+ id: item.id,
+ label: item.label,
+ color: item.color,
+ value:
+ legend.summary === "sum" &&
+ summary !== null &&
+ summary !== undefined
+ ? { label: "Sum", value: valueFormatter(summary) }
+ : undefined,
+ muted:
+ hidden ||
+ (legend.interaction === "highlight" &&
+ highlightedId !== undefined &&
+ !focused),
+ action: {
+ label,
+ pressed: legend.interaction === "toggle" ? !hidden : focused,
+ onClick: () => {
+ if (legend.interaction === "toggle") {
+ const next = new Map(visibilityOverrides);
+ next.set(item.id, !hidden);
+ setLegendState({
+ ...effectiveState,
+ visibilityOverrides: next,
+ });
+ return;
+ }
+ setLegendState({
+ ...effectiveState,
+ highlightedId: focused ? undefined : item.id,
+ });
+ },
+ },
+ };
+ })}
+ />
+ ) : null}
+ </div>
+ );
+}
diff --git a/web/src/components/ui/chart.tsx b/web/src/components/ui/chart.tsx
deleted file mode 100644
index 2d6ec83c1d..0000000000
--- a/web/src/components/ui/chart.tsx
+++ /dev/null
@@ -1,449 +0,0 @@
-/* eslint-disable @repo/no-style-props, @repo/no-null-render */
-"use client";
-
-import * as React from "react";
-import * as RechartsPrimitive from "recharts";
-import type {
- TooltipContentProps,
- TooltipPayloadEntry,
- TooltipValueType,
-} from "recharts";
-
-import { cn } from "@/src/utils/tailwind";
-import { getPlainTextFromReactNode } from "@/src/utils/react-node-plain-text";
-
-// Format: { THEME_NAME: CSS_SELECTOR }
-const THEMES = { light: "", dark: ".dark" } as const;
-
-export type ChartConfig = {
- [k in string]: {
- label?: React.ReactNode;
- icon?: React.ComponentType;
- } & (
- | { color?: string; theme?: never }
- | { color?: never; theme: Record<keyof typeof THEMES, string> }
- );
-};
-
-type ChartContextProps = {
- config: ChartConfig;
-};
-
-const ChartContext = React.createContext<ChartContextProps | null>(null);
-
-function useChart() {
- const context = React.useContext(ChartContext);
-
- if (!context) {
- throw new Error("useChart must be used within a <ChartContainer />");
- }
-
- return context;
-}
-
-const ChartContainer = React.forwardRef<
- HTMLDivElement,
- React.ComponentProps<"div"> & {
- config: ChartConfig;
- children: React.ComponentProps<
- typeof RechartsPrimitive.ResponsiveContainer
- >["children"];
- }
->(({ id, className, children, config, ...props }, ref) => {
- const uniqueId = React.useId();
- const chartId = `chart-${id || uniqueId.replace(/:/g, "")}`;
-
- return (
- <ChartContext.Provider value={{ config }}>
- <div
- data-chart={chartId}
- ref={ref}
- className={cn(
- "[&_.recharts-cartesian-axis-tick-value]:fill-muted-foreground/90 [&_.recharts-cartesian-axis-tick_text]:fill-muted-foreground/90 [&_.recharts-cartesian-grid_line[stroke='#ccc']]:stroke-border/50 [&_.recharts-curve.recharts-tooltip-cursor]:stroke-border [&_.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 relative h-full w-full flex-1 justify-center text-xs [&_.recharts-dot[stroke='#fff']]:stroke-transparent [&_.recharts-layer]:outline-hidden [&_.recharts-sector]:outline-hidden [&_.recharts-sector[stroke='#fff']]:stroke-transparent [&_.recharts-surface]:outline-hidden",
- className,
- )}
- {...props}
- >
- <ChartStyle id={chartId} config={config} />
- <RechartsPrimitive.ResponsiveContainer
- width="100%"
- height="100%"
- minWidth={0}
- minHeight={1}
- initialDimension={{ width: 1, height: 1 }}
- >
- {children}
- </RechartsPrimitive.ResponsiveContainer>
- </div>
- </ChartContext.Provider>
- );
-});
-ChartContainer.displayName = "Chart";
-
-const ChartStyle = ({ id, config }: { id: string; config: ChartConfig }) => {
- const colorConfig = Object.entries(config).filter(
- ([, config]) => config.theme || config.color,
- );
-
- if (!colorConfig.length) {
- return null;
- }
-
- return (
- <style
- dangerouslySetInnerHTML={{
- __html: Object.entries(THEMES)
- .map(
- ([theme, prefix]) => `
-${prefix} [data-chart=${id}] {
-${colorConfig
- .map(([key, itemConfig]) => {
- const color =
- itemConfig.theme?.[theme as keyof typeof itemConfig.theme] ||
- itemConfig.color;
- const safeKey = key.replace(/[^\p{L}\p{N}_ .()-]/gu, "_");
- return color ? ` --color-${safeKey}: ${color};` : null;
- })
- .join("\n")}
-}
-`,
- )
- .join("\n"),
- }}
- />
- );
-};
-
-type ChartTooltipProps = React.ComponentProps<typeof RechartsPrimitive.Tooltip>;
-
-function ChartTooltip({
- allowEscapeViewBox = { x: false, y: false },
- isAnimationActive = false,
- offset = 12,
- useTranslate3d = true,
- wrapperStyle,
- ...props
-}: ChartTooltipProps) {
- return (
- <RechartsPrimitive.Tooltip
- allowEscapeViewBox={allowEscapeViewBox}
- isAnimationActive={isAnimationActive}
- offset={offset}
- useTranslate3d={useTranslate3d}
- wrapperStyle={{
- pointerEvents: "none",
- zIndex: 50,
- ...wrapperStyle,
- }}
- {...props}
- />
- );
-}
-
-const ChartTooltipContent = React.forwardRef<
- HTMLDivElement,
- React.ComponentProps<"div"> &
- Partial<TooltipContentProps<TooltipValueType, string | number>> & {
- hideLabel?: boolean;
- hideIndicator?: boolean;
- indicator?: "line" | "dot" | "dashed";
- nameKey?: string;
- labelKey?: string;
- valueFormatter?: (value: number) => string;
- nameFormatter?: (name: string) => string;
- sortPayloadByValue?: "asc" | "desc";
- /** dataKeys to emphasize (e.g. the hover-proximity series); their rows are bolded. */
- highlightedKeys?: ReadonlySet<string>;
- }
->(
- (
- {
- active,
- payload,
- className,
- indicator = "dot",
- hideLabel = false,
- hideIndicator = false,
- label,
- labelFormatter,
- labelClassName,
- formatter,
- color,
- nameKey,
- labelKey,
- valueFormatter,
- nameFormatter,
- sortPayloadByValue,
- highlightedKeys,
- },
- ref,
- ) => {
- const { config } = useChart();
-
- const displayPayload = React.useMemo(() => {
- if (!payload?.length || !sortPayloadByValue) return payload ?? [];
- return [...payload].sort((a, b) => {
- const va = Number(a.value ?? 0);
- const vb = Number(b.value ?? 0);
- return sortPayloadByValue === "desc" ? vb - va : va - vb;
- });
- }, [payload, sortPayloadByValue]);
-
- const tooltipLabel = React.useMemo(() => {
- if (hideLabel || !payload?.length) {
- return null;
- }
-
- const [item] = payload;
- const key = `${labelKey || item?.dataKey || item?.name || "value"}`;
- const itemConfig = getPayloadConfigFromPayload(config, item, key);
- const value =
- !labelKey && typeof label === "string"
- ? config[label as keyof typeof config]?.label || label
- : itemConfig?.label;
-
- if (labelFormatter) {
- return (
- <div className={cn("font-bold", labelClassName)}>
- {labelFormatter(value, payload)}
- </div>
- );
- }
-
- if (!value) {
- return null;
- }
-
- return <div className={cn("font-bold", labelClassName)}>{value}</div>;
- }, [
- label,
- labelFormatter,
- payload,
- hideLabel,
- labelClassName,
- config,
- labelKey,
- ]);
-
- if (!active || !payload?.length) {
- return null;
- }
-
- const nestLabel = displayPayload.length === 1 && indicator !== "dot";
-
- return (
- <div
- ref={ref}
- className={cn(
- "border-border/50 bg-background grid min-w-32 items-start gap-1.5 rounded-lg border px-2.5 py-1.5 text-xs shadow-xl",
- className,
- )}
- >
- {!nestLabel ? tooltipLabel : null}
- <div className="grid gap-1.5">
- {displayPayload.map((item, index) => {
- const key = `${nameKey || item.name || item.dataKey || "value"}`;
- const itemConfig = getPayloadConfigFromPayload(config, item, key);
- const itemDisplayName = nameFormatter
- ? nameFormatter(String(item.name ?? item.dataKey ?? ""))
- : itemConfig?.label || item.name;
- const itemDisplayTitle = getPlainTextFromReactNode(itemDisplayName);
- const indicatorColor =
- color ||
- getFillColor(item.payload) ||
- item.color ||
- "currentColor";
- const highlighted =
- highlightedKeys?.has(String(item.dataKey ?? item.name ?? "")) ??
- false;
-
- return (
- <div
- key={String(item.dataKey ?? item.name ?? index)}
- className={cn(
- "[&>svg]:text-muted-foreground flex w-full items-center gap-2 [&>svg]:h-2.5 [&>svg]:w-2.5",
- // Emphasis must be layout-neutral: the row keeps its exact box
- // and the highlight paints around it (a box-shadow halo adds
- // the breathing room margins/padding would), so rows never
- // shift or re-truncate when the hovered series changes. (LFE-10576)
- highlighted &&
- "bg-muted rounded-xs shadow-[0_0_0_3px_hsl(var(--muted))]",
- )}
- >
- {formatter && item?.value !== undefined && item.name != null ? (
- formatter(item.value, item.name, item, index, displayPayload)
- ) : (
- <>
- {itemConfig?.icon ? (
- <itemConfig.icon />
- ) : (
- !hideIndicator && (
- <div
- className={cn(
- "border-border shrink-0 rounded-[2px] bg-(--color-bg)",
- {
- "h-2.5 w-2.5": indicator === "dot",
- // line/dashed need an explicit height: the row is
- // items-center, so a height-less swatch collapses
- // to 0px and the series color is invisible.
- "h-2.5 w-1": indicator === "line",
- "h-2.5 w-0 border-[1.5px] border-dashed bg-transparent":
- indicator === "dashed",
- "my-0.5": nestLabel && indicator === "dashed",
- },
- )}
- style={
- {
- "--color-bg": indicatorColor,
- "--color-border": indicatorColor,
- } as React.CSSProperties
- }
- />
- )
- )}
- <div
- className={cn(
- // leading-tight, not leading-none: `truncate` clips at
- // the line box, and a 1.0 line-height leaves no room
- // below the baseline — g/y/p descenders lost their
- // bottom pixel. (LFE-10576)
- "flex min-w-0 flex-1 justify-between gap-x-3 leading-tight",
- nestLabel ? "items-end" : "items-center",
- )}
- >
- <div className="grid min-w-0 gap-1.5">
- {nestLabel ? tooltipLabel : null}
- <span
- className={cn(
- "text-muted-foreground truncate",
- // Color-only emphasis: a weight change alters text
- // metrics, so the highlighted name would truncate
- // differently than its neighbors. (LFE-10576)
- highlighted && "text-foreground",
- )}
- title={itemDisplayTitle}
- >
- {itemDisplayName}
- </span>
- </div>
- {item.value !== undefined && item.value !== null && (
- <span className="text-foreground shrink-0 font-mono font-bold whitespace-nowrap tabular-nums">
- {valueFormatter
- ? valueFormatter(Number(item.value))
- : item.value.toLocaleString()}
- </span>
- )}
- </div>
- </>
- )}
- </div>
- );
- })}
- </div>
- </div>
- );
- },
-);
-ChartTooltipContent.displayName = "ChartTooltip";
-
-type ChartLegendProps = React.ComponentProps<typeof RechartsPrimitive.Legend>;
-
-function ChartLegend({ itemSorter = null, ...props }: ChartLegendProps) {
- return <RechartsPrimitive.Legend itemSorter={itemSorter} {...props} />;
-}
-
-function ChartActiveReferenceLine({
- stroke = "hsl(var(--border))",
- strokeDasharray = "4 4",
- strokeOpacity = 0.8,
- zIndex = 350,
-}: {
- stroke?: string;
- strokeDasharray?: string;
- strokeOpacity?: number;
- zIndex?: number;
-}) {
- const activeLabel = RechartsPrimitive.useActiveTooltipLabel();
- const isTooltipActive = RechartsPrimitive.useIsTooltipActive();
-
- if (!isTooltipActive || activeLabel === undefined || activeLabel === null) {
- return null;
- }
-
- return (
- <RechartsPrimitive.ReferenceLine
- x={activeLabel}
- stroke={stroke}
- strokeDasharray={strokeDasharray}
- strokeOpacity={strokeOpacity}
- ifOverflow="extendDomain"
- zIndex={zIndex}
- // The crosshair must never intercept pointer events, otherwise it creates
- // a dead "no-hover" strip down the middle of the hovered bar/point. (LFE-10549)
- style={{ pointerEvents: "none" }}
- />
- );
-}
-
-// Helper to extract item config from a payload.
-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;
- }
-
- return configLabelKey in config
- ? config[configLabelKey]
- : config[key as keyof typeof config];
-}
-
-function getFillColor(
- payload: TooltipPayloadEntry<TooltipValueType, string | number>["payload"],
-): string | undefined {
- if (
- typeof payload === "object" &&
- payload !== null &&
- "fill" in payload &&
- typeof payload.fill === "string"
- ) {
- return payload.fill;
- }
-
- return undefined;
-}
-
-export {
- ChartContainer,
- ChartTooltip,
- ChartLegend,
- ChartActiveReferenceLine,
- useChart,
- getPayloadConfigFromPayload,
-};
diff --git a/web/src/features/chart-view/components/ChartCanvas.tsx b/web/src/features/chart-view/components/ChartCanvas.tsx
index a7abf0f03c..0013c88fd3 100644
--- a/web/src/features/chart-view/components/ChartCanvas.tsx
+++ b/web/src/features/chart-view/components/ChartCanvas.tsx
@@ -6,7 +6,7 @@ import {
type DataPoint,
getWidgetMissingBucketValue,
} from "@/src/features/widgets";
-import { type ChartConfig } from "@/src/components/ui/chart";
+import { type ChartProps } from "@/src/features/widgets/chart-library/chart-props";
import { type AggregationFn } from "../types";
import { isTimeSeriesChartType } from "../vocab";
@@ -16,8 +16,8 @@ const RANKED_ROW_LIMIT = 20;
* Builds the `chart-library` `ChartConfig` (series labels + the `metric` key the
* bar/pie primitives colour through `--color-metric`) from the rendered series.
*/
-function buildChartConfig(data: DataPoint[], metricLabel: string): ChartConfig {
- const config: ChartConfig = {};
+function buildChartConfig(data: DataPoint[], metricLabel: string) {
+ const config: NonNullable<ChartProps["config"]> = {};
// Per-series labels first, so a breakdown value that is literally "metric"
// (e.g. an observation/model named "metric") keeps its own label.
for (const point of data) {
diff --git a/web/src/features/score-analytics/components/charts/ScoreChartLegendContent.tsx b/web/src/features/score-analytics/components/charts/ScoreChartLegendContent.tsx
deleted file mode 100644
index bbae57851f..0000000000
--- a/web/src/features/score-analytics/components/charts/ScoreChartLegendContent.tsx
+++ /dev/null
@@ -1,522 +0,0 @@
-/* eslint-disable @repo/no-style-props, @repo/no-null-render */
-import React, { useState, useRef, useLayoutEffect, useMemo } from "react";
-import type { DefaultLegendContentProps, LegendPayload } from "recharts";
-import { MoreVertical } from "lucide-react";
-import { Button } from "@/src/components/ui/button";
-import {
- Popover,
- PopoverContent,
- PopoverTrigger,
-} from "@/src/components/ui/popover";
-import { cn } from "@/src/utils/tailwind";
-import {
- useChart,
- getPayloadConfigFromPayload,
-} from "@/src/components/ui/chart";
-
-export interface ScoreChartLegendContentProps extends Pick<
- DefaultLegendContentProps,
- "payload" | "verticalAlign"
-> {
- /** Enable interactive click-to-toggle functionality */
- interactive?: boolean;
- /** Visibility state for each legend item (key -> visible) */
- visibilityState?: Record<string, boolean>;
- /** Callback when visibility changes */
- onVisibilityChange?: (key: string, visible: boolean) => void;
- /** Optional function to format labels */
- formatLabel?: (label: string, item: LegendPayload) => string;
- /** Custom className */
- className?: string;
- /** Name key to use for legend items */
- nameKey?: string;
-}
-
-interface LegendItemProps {
- color: string;
- label: string;
- visible: boolean;
- interactive: boolean;
- onClick?: () => void;
- noTruncate?: boolean;
-}
-
-/**
- * Individual legend item component with interactive toggle support
- */
-const LegendItem = ({
- color,
- label,
- visible,
- interactive,
- onClick,
- noTruncate = false,
-}: LegendItemProps) => {
- return (
- <button
- type="button"
- onClick={onClick}
- disabled={!interactive}
- aria-pressed={visible}
- aria-label={`${visible ? "Hide" : "Show"} ${label}`}
- className={cn(
- "flex items-center gap-1.5 text-sm transition-opacity",
- interactive && "cursor-pointer hover:opacity-80",
- !interactive && "cursor-default",
- !visible && "opacity-50",
- )}
- >
- <div
- className={cn(
- "h-2 w-2 shrink-0 rounded-full",
- visible ? "bg-current" : "border-2 border-current bg-transparent", // Filled vs outlined
- )}
- style={{
- color: color,
- ...(visible
- ? { backgroundColor: color }
- : { borderColor: color, backgroundColor: "transparent" }),
- }}
- />
- <span
- className={cn(
- "text-muted-foreground",
- !noTruncate && "max-w-[120px] truncate",
- !visible && "line-through", // Strike through when hidden
- )}
- title={label}
- >
- {label}
- </span>
- </button>
- );
-};
-
-/**
- * Interactive legend component with 2-line layout and progressive disclosure
- *
- * Features:
- * - Fixed 2-line height (no layout jumps)
- * - Overflow detection with hybrid approach
- * - Truncation with popover for full list
- * - Click-to-toggle series visibility
- * - Accessibility support (keyboard, ARIA)
- */
-export const ScoreChartLegendContent = React.forwardRef<
- HTMLDivElement,
- ScoreChartLegendContentProps
->(
- (
- {
- payload,
- interactive = false,
- visibilityState,
- onVisibilityChange,
- formatLabel,
- verticalAlign = "bottom",
- className,
- nameKey,
- },
- ref,
- ) => {
- const { config } = useChart();
- const containerRef = useRef<HTMLDivElement>(null);
- const buttonRef = useRef<HTMLButtonElement>(null);
- const [showPopover, setShowPopover] = useState(false);
- const [needsPopover, setNeedsPopover] = useState(false);
- const [buttonWidth, setButtonWidth] = useState(140); // Estimated default width
- const [maxVisibleItems, setMaxVisibleItems] = useState<number | null>(null);
-
- // Measure button width on mount only (prevent circular re-renders)
- useLayoutEffect(() => {
- if (buttonRef.current) {
- const width = buttonRef.current.offsetWidth;
- if (width > 0) {
- setButtonWidth(width);
- }
- }
- }, []); // Empty deps - run only once
-
- // Width-based overflow detection with ResizeObserver
- useLayoutEffect(() => {
- if (!containerRef.current || !payload || payload.length === 0) {
- setNeedsPopover(false);
- setMaxVisibleItems(null);
- return;
- }
-
- const container = containerRef.current;
- let isCalculating = false; // Prevent concurrent calculations
- let lastWidth = 0;
- let lastHeight = 0;
-
- const calculateLayout = () => {
- if (!container || isCalculating) return;
-
- // Skip if size hasn't changed significantly (prevent feedback loops)
- const currentWidth = container.clientWidth;
- const currentHeight = container.scrollHeight;
- if (
- Math.abs(currentWidth - lastWidth) < 10 &&
- Math.abs(currentHeight - lastHeight) < 10
- ) {
- return;
- }
-
- isCalculating = true;
- lastWidth = currentWidth;
- lastHeight = currentHeight;
-
- // First, render all items to detect if overflow occurs
- const containerHeight = container.scrollHeight;
- const lineHeight = parseInt(
- window.getComputedStyle(container).lineHeight || "24",
- );
- const twoLines = lineHeight * 2;
-
- // Add 6px tolerance for sub-pixel rendering
- const hasOverflow = containerHeight > twoLines + 6;
-
- if (!hasOverflow) {
- setNeedsPopover((prev) => {
- if (prev !== false) return false;
- return prev;
- });
- setMaxVisibleItems((prev) => {
- if (prev !== null) return null;
- return prev;
- });
- isCalculating = false;
- return;
- }
-
- // If overflow detected, calculate how many items fit WITH button space reserved
- setNeedsPopover((prev) => {
- if (prev !== true) return true;
- return prev;
- });
-
- const containerWidth = container.clientWidth;
- const gapX = 12; // gap-x-3 = 12px
- const buttonWidthWithGap = buttonWidth + gapX;
-
- // Get all legend item elements currently rendered
- const items = Array.from(
- container.querySelectorAll("button[aria-pressed]"),
- ) as HTMLElement[];
-
- if (items.length === 0) {
- // Fallback: use percentage-based estimate
- const fallbackValue = Math.max(6, Math.floor(payload.length * 0.7));
- setMaxVisibleItems((prev) => {
- if (prev !== fallbackValue) return fallbackValue;
- return prev;
- });
- isCalculating = false;
- return;
- }
-
- // Calculate cumulative width and count items that fit in one line
- let cumulativeWidth = 0;
- let itemsFitInLine = 0;
- const lineOneThreshold = containerWidth;
-
- for (let i = 0; i < items.length; i++) {
- const itemWidth = items[i]!.offsetWidth;
- const widthWithGap = i === 0 ? itemWidth : itemWidth + gapX;
-
- if (cumulativeWidth + widthWithGap <= lineOneThreshold) {
- cumulativeWidth += widthWithGap;
- itemsFitInLine++;
- } else {
- break;
- }
- }
-
- // For line 2, reserve space for the button
- const lineTwoAvailable = containerWidth - buttonWidthWithGap;
- let lineTwoCumulativeWidth = 0;
- let itemsFitInLineTwo = 0;
-
- for (let i = itemsFitInLine; i < items.length; i++) {
- const itemWidth = items[i]!.offsetWidth;
- const widthWithGap =
- i === itemsFitInLine ? itemWidth : itemWidth + gapX;
-
- if (lineTwoCumulativeWidth + widthWithGap <= lineTwoAvailable) {
- lineTwoCumulativeWidth += widthWithGap;
- itemsFitInLineTwo++;
- } else {
- break;
- }
- }
-
- // Total items that fit: line 1 + line 2 (with button space reserved)
- const totalItemsThatFit = itemsFitInLine + itemsFitInLineTwo;
-
- // Subtract 1 for safety margin to prevent edge cases
- const newMaxVisible = Math.max(5, totalItemsThatFit - 1);
- setMaxVisibleItems((prev) => {
- // Only update if changed significantly (prevent oscillation)
- if (prev === null || Math.abs(prev - newMaxVisible) > 1) {
- return newMaxVisible;
- }
- return prev;
- });
-
- isCalculating = false;
- };
-
- // Initial calculation with small delay to ensure DOM is ready
- const timeoutId = setTimeout(() => {
- calculateLayout();
- }, 0);
-
- // Use ResizeObserver for efficient resize tracking
- const resizeObserver = new ResizeObserver(() => {
- // Debounce resize events
- requestAnimationFrame(() => {
- calculateLayout();
- });
- });
-
- resizeObserver.observe(container);
-
- return () => {
- clearTimeout(timeoutId);
- resizeObserver.disconnect();
- };
- }, [payload, buttonWidth]); // Include dependencies to recalculate when they change
-
- const handleItemClick = (key: string) => {
- if (!interactive || !onVisibilityChange) return;
-
- const currentVisibility = visibilityState?.[key] ?? true;
- const newVisibility = !currentVisibility;
-
- onVisibilityChange(key, newVisibility);
- };
-
- // Group items by score name (prefix before dash)
- // Must be before early return to satisfy React hooks rules
- const groupedItems = useMemo(() => {
- if (!payload || payload.length === 0) {
- return {};
- }
-
- const groups: Record<string, LegendPayload[]> = {};
-
- payload.forEach((item) => {
- const key = `${nameKey || item.dataKey || "value"}`;
- let groupName = "Categories";
-
- // Try to extract score name from key (e.g., "sentiment-negative" → "sentiment")
- if (key.includes("-")) {
- const prefix = key.split("-")[0];
- if (prefix) {
- groupName =
- prefix.charAt(0).toUpperCase() + prefix.slice(1).toLowerCase();
- }
- }
-
- if (!groups[groupName]) {
- groups[groupName] = [];
- }
- groups[groupName].push(item);
- });
-
- return groups;
- }, [payload, nameKey]);
-
- if (!payload || payload.length === 0) {
- return null;
- }
-
- // Calculate visible items based on width-based measurement
- // maxVisibleItems is calculated by ResizeObserver to reserve button space
- const visibleCount = needsPopover
- ? (maxVisibleItems ?? Math.max(6, Math.floor(payload.length * 0.7)))
- : payload.length;
-
- const visibleItems = payload.slice(0, visibleCount);
- const hiddenCount = payload.length - visibleItems.length;
-
- // Smart label formatter for common patterns
- const smartFormatLabel = (label: string): string => {
- if (!label || typeof label !== "string") return String(label);
-
- // Pattern: "sentiment-negative" → "Negative"
- if (label.includes("-")) {
- const suffix = label.split("-").pop();
- if (suffix) {
- return suffix.charAt(0).toUpperCase() + suffix.slice(1).toLowerCase();
- }
- }
-
- // Pattern: "high_confidence" → "High Confidence"
- if (label.includes("_")) {
- return label
- .split("_")
- .map((w) => w.charAt(0).toUpperCase() + w.slice(1).toLowerCase())
- .join(" ");
- }
-
- // Pattern: "camelCase" → "Camel Case"
- if (/[a-z][A-Z]/.test(label)) {
- return label
- .replace(/([a-z])([A-Z])/g, "$1 $2")
- .replace(/^./, (str) => str.toUpperCase());
- }
-
- // Default: capitalize first letter
- return label.charAt(0).toUpperCase() + label.slice(1).toLowerCase();
- };
-
- // Format label for display
- const getFormattedLabel = (item: LegendPayload): string => {
- const key = `${nameKey || item.dataKey || "value"}`;
-
- // Try to get label from ChartConfig first
- const itemConfig = getPayloadConfigFromPayload(config, item, key);
- if (itemConfig?.label) {
- return String(itemConfig.label);
- }
-
- // Fallback to original logic
- const rawLabel = item.value || key;
-
- // Handle "__unmatched__" special case
- if (rawLabel === "__unmatched__" || rawLabel === "unmatched") {
- return "Unmatched";
- }
-
- if (formatLabel) {
- const formatted = formatLabel(rawLabel, item);
- return String(formatted);
- }
-
- // Apply smart formatting as final fallback
- return smartFormatLabel(String(rawLabel));
- };
-
- return (
- <div
- ref={ref}
- className={cn(
- "flex min-h-[48px] items-center justify-center gap-2",
- verticalAlign === "top" ? "pb-3" : "pt-3",
- className,
- )}
- >
- {/* Truncated inline legend (fixed 2-line height) */}
- <div
- ref={containerRef}
- className="flex max-h-[48px] flex-1 flex-wrap items-center justify-center gap-x-3 gap-y-1 overflow-hidden"
- >
- {visibleItems.map((item) => {
- const key = `${nameKey || item.dataKey || "value"}`;
- const visible = visibilityState?.[key] ?? true;
- const color =
- item.color ||
- (typeof item.payload === "object" &&
- item.payload &&
- "fill" in item.payload
- ? (item.payload as { fill: string }).fill
- : "hsl(var(--chart-1))");
-
- return (
- <LegendItem
- key={key}
- color={color}
- label={getFormattedLabel(item)}
- visible={visible}
- interactive={interactive}
- onClick={() => handleItemClick(key)}
- />
- );
- })}
-
- {/* Combined popover button with count - inline as last item */}
- {needsPopover && (
- <Popover open={showPopover} onOpenChange={setShowPopover}>
- <PopoverTrigger asChild>
- <Button
- ref={buttonRef}
- variant="ghost"
- size="sm"
- className="text-muted-foreground hover:bg-accent h-6 shrink-0 gap-1 px-2 text-xs"
- aria-label={`Show all ${payload.length} categories`}
- >
- <span>Show all {payload.length}</span>
- {hiddenCount > 0 && (
- <span className="font-bold">(+{hiddenCount})</span>
- )}
- <MoreVertical className="h-3 w-3" />
- </Button>
- </PopoverTrigger>
- <PopoverContent
- className="w-80"
- align="end"
- side={verticalAlign === "top" ? "bottom" : "top"}
- >
- <div className="space-y-3">
- <div className="flex items-center justify-between">
- <p className="text-sm font-bold">All Categories</p>
- <span className="text-muted-foreground text-xs">
- {payload.length} total
- </span>
- </div>
- <div className="space-y-3">
- {Object.entries(groupedItems).map(
- ([groupName, items], _groupIndex) => (
- <div key={groupName}>
- {/* Only show subheader if there are multiple groups */}
- {Object.keys(groupedItems).length > 1 && (
- <h4 className="text-muted-foreground mb-2 text-xs font-bold">
- {groupName}
- </h4>
- )}
- <div className="space-y-1">
- {items.map((item) => {
- const key = `${nameKey || item.dataKey || "value"}`;
- const visible = visibilityState?.[key] ?? true;
- const color =
- item.color ||
- (typeof item.payload === "object" &&
- item.payload &&
- "fill" in item.payload
- ? (item.payload as { fill: string }).fill
- : "hsl(var(--chart-1))");
-
- return (
- <div
- key={key}
- className="hover:bg-accent/50 rounded-sm px-2 py-1.5"
- >
- <LegendItem
- color={color}
- label={getFormattedLabel(item)}
- visible={visible}
- interactive={interactive}
- onClick={() => handleItemClick(key)}
- noTruncate={true}
- />
- </div>
- );
- })}
- </div>
- </div>
- ),
- )}
- </div>
- </div>
- </PopoverContent>
- </Popover>
- )}
- </div>
- </div>
- );
- },
-);
-
-ScoreChartLegendContent.displayName = "ScoreChartLegendContent";
diff --git a/web/src/features/score-analytics/components/charts/ScoreDistributionBooleanChart.tsx b/web/src/features/score-analytics/components/charts/ScoreDistributionBooleanChart.tsx
index 6dffa70b0c..0350c658b2 100644
--- a/web/src/features/score-analytics/components/charts/ScoreDistributionBooleanChart.tsx
+++ b/web/src/features/score-analytics/components/charts/ScoreDistributionBooleanChart.tsx
@@ -1,29 +1,15 @@
-import { useMemo, useState, useCallback } from "react";
-import { Bar, BarChart, XAxis, YAxis } from "recharts";
-import {
- ChartContainer,
- ChartLegend,
- ChartTooltip,
- type ChartConfig,
-} from "@/src/components/ui/chart";
-import { ScoreChartLegendContent } from "./ScoreChartLegendContent";
-import { ScoreChartTooltip } from "../../lib/ScoreChartTooltip";
+import { useMemo } from "react";
+import { GroupedBarChart } from "@/src/components/design-system/charts/GroupedBarChart/GroupedBarChart";
interface BooleanChartProps {
distribution1: Array<{ binIndex: number; count: number }>;
distribution2?: Array<{ binIndex: number; count: number }>;
- categories: string[]; // Should always be ["False", "True"]
+ categories: string[];
score1Name: string;
score2Name?: string;
colors: Record<string, string>;
}
-/**
- * Boolean distribution chart component
- * Renders bar charts for boolean score distributions
- * - Single score: One bar per value (False/True)
- * - Two scores: Grouped bars for comparison
- */
export function ScoreDistributionBooleanChart({
distribution1,
distribution2,
@@ -32,231 +18,60 @@ export function ScoreDistributionBooleanChart({
score2Name,
colors,
}: BooleanChartProps) {
- const isComparisonMode = Boolean(distribution2 && score2Name);
-
- // Detect if we have namespaced category keys (e.g., "Color (annotation): True")
- // This happens in "all" and "matched" tabs when comparing scores
- const namespacedKeys = useMemo(() => {
- const colorKeys = Object.keys(colors);
- // Check if any key contains ":" which indicates namespacing
- const hasNamespacing = colorKeys.some((key) => key.includes(":"));
-
- if (!hasNamespacing) {
- return null;
- }
-
- // Extract namespaced keys for each category
- const keys: Record<string, string[]> = {};
- categories.forEach((category) => {
- keys[category] = colorKeys.filter((key) => key.endsWith(`: ${category}`));
- });
-
- return keys;
- }, [colors, categories]);
-
- // Transform data for Recharts - grouped bars
- const chartData = useMemo(() => {
- const dist2Map = distribution2
- ? new Map(distribution2.map((d) => [d.binIndex, d.count]))
- : null;
-
+ const comparison = Boolean(distribution2 && score2Name);
+ const data = useMemo(() => {
+ const second = new Map(
+ distribution2?.map((item) => [item.binIndex, item.count]),
+ );
return [...distribution1]
.sort((a, b) => a.binIndex - b.binIndex)
- .map((item) => {
- const label = categories[item.binIndex] ?? `Value ${item.binIndex}`;
-
- if (isComparisonMode && dist2Map) {
- // Use namespaced keys if available, otherwise fall back to pv/uv
- if (namespacedKeys && namespacedKeys[label]) {
- const keys = namespacedKeys[label];
- const score1Key = keys[0] ?? "pv";
- const score2Key = keys[1] ?? "uv";
-
- return {
- name: label,
- [score1Key]: item.count,
- [score2Key]: dist2Map.get(item.binIndex) ?? 0,
- };
- }
-
- return {
- name: label,
- pv: item.count,
- uv: dist2Map.get(item.binIndex) ?? 0,
- };
- }
- return {
- name: label,
- pv: item.count,
- };
- });
- }, [
- distribution1,
- distribution2,
- categories,
- isComparisonMode,
- namespacedKeys,
- ]);
-
- // Extract actual dataKeys being used in the chart
- const dataKeys = useMemo(() => {
- if (!isComparisonMode) {
- return { score1Key: "pv", score2Key: null };
- }
-
- // If we have namespaced keys, use the first category's keys as representative
- if (namespacedKeys && categories.length > 0) {
- const firstCategory = categories[0];
- const keys = namespacedKeys[firstCategory];
- if (keys && keys.length >= 2) {
- return { score1Key: keys[0], score2Key: keys[1] };
- }
- }
-
- // Fall back to pv/uv
- return { score1Key: "pv", score2Key: "uv" };
- }, [isComparisonMode, namespacedKeys, categories]);
-
- // Visibility state for interactive legend (comparison mode only)
- const [hiddenKeys, setHiddenKeys] = useState<Set<string>>(new Set());
-
- // Create visibility state object for legend
- const visibilityState = useMemo(() => {
- if (!isComparisonMode) return undefined;
- return {
- [dataKeys.score1Key]: !hiddenKeys.has(dataKeys.score1Key),
- ...(dataKeys.score2Key && {
- [dataKeys.score2Key]: !hiddenKeys.has(dataKeys.score2Key),
- }),
- };
- }, [hiddenKeys, isComparisonMode, dataKeys]);
-
- // Toggle handler
- const handleVisibilityToggle = useCallback(
- (key: string, visible: boolean) => {
- setHiddenKeys((prev) => {
- const next = new Set(prev);
- if (visible) {
- next.delete(key);
- } else {
- next.add(key);
- }
- return next;
- });
+ .map((item) => ({
+ key: categories[item.binIndex] ?? `Value ${item.binIndex}`,
+ values: {
+ score1: item.count,
+ ...(comparison ? { score2: second.get(item.binIndex) ?? 0 } : {}),
+ },
+ }));
+ }, [distribution1, distribution2, categories, comparison]);
+ const category = categories[0] ?? "False";
+ const score1Key = `${score1Name}: ${category}`;
+ const score2Key = score2Name ? `${score2Name}: ${category}` : undefined;
+ const firstColor =
+ colors.score1 ??
+ colors[score1Key] ??
+ colors.True ??
+ colors.False ??
+ Object.values(colors)[0];
+ const secondColor =
+ colors.score2 ??
+ (score2Key ? colors[score2Key] : undefined) ??
+ colors.__score2_True ??
+ colors.__score2_False;
+ const series = [
+ {
+ id: "score1",
+ label: score1Name,
+ color: firstColor ?? "hsl(var(--chart-1))",
},
- [],
- );
-
- // Build chart config
- const config: ChartConfig = useMemo(() => {
- // If we have namespaced keys, use them with their colors
- if (namespacedKeys && isComparisonMode) {
- const cfg: ChartConfig = {};
-
- // Add config for score1Key
- cfg[dataKeys.score1Key] = {
- label: dataKeys.score1Key,
- color: colors[dataKeys.score1Key] || Object.values(colors)[0],
- };
-
- // Add config for score2Key if it exists
- if (dataKeys.score2Key) {
- cfg[dataKeys.score2Key] = {
- label: dataKeys.score2Key,
- color: colors[dataKeys.score2Key] || Object.values(colors)[1],
- };
- }
-
- return cfg;
- }
-
- // Fall back to original logic without namespacing
- const firstColor =
- colors["True"] || colors["False"] || Object.values(colors)[0];
-
- const cfg: ChartConfig = {
- pv: {
- label: score1Name,
- color: firstColor,
- },
- };
-
- if (isComparisonMode && score2Name) {
- cfg.uv = {
- label: score2Name,
- color:
- colors["__score2_True"] ||
- colors["__score2_False"] ||
- Object.values(colors)[1] ||
- firstColor,
- };
- }
-
- return cfg;
- }, [
- isComparisonMode,
- score1Name,
- score2Name,
- colors,
- namespacedKeys,
- dataKeys,
- ]);
-
+ ...(comparison
+ ? [
+ {
+ id: "score2",
+ label: score2Name ?? "Score 2",
+ color: secondColor ?? "hsl(var(--chart-2))",
+ },
+ ]
+ : []),
+ ];
return (
- <ChartContainer
- config={config}
- className="[&_.recharts-rectangle.recharts-tooltip-cursor]:fill-transparent"
- >
- <BarChart accessibilityLayer data={chartData} margin={{ bottom: 20 }}>
- <XAxis
- dataKey="name"
- stroke="hsl(var(--chart-grid))"
- fontSize={12}
- tickLine={false}
- axisLine={{ stroke: "hsl(var(--border) / 0.5)" }}
- interval={0}
- />
- <YAxis
- stroke="hsl(var(--chart-grid))"
- fontSize={12}
- tickLine={false}
- axisLine={false}
- niceTicks="auto"
- tickFormatter={(value) => value.toLocaleString()}
- />
- <ChartTooltip
- content={
- <ScoreChartTooltip
- valueFormatter={(value) => value.toLocaleString()}
- labelFormatter={(label) => String(label)}
- />
- }
- />
- <Bar
- dataKey={dataKeys.score1Key}
- fill={config[dataKeys.score1Key]?.color}
- fillOpacity={hiddenKeys.has(dataKeys.score1Key) ? 0 : 1}
- radius={[4, 4, 0, 0]}
- />
- {isComparisonMode && dataKeys.score2Key && (
- <Bar
- dataKey={dataKeys.score2Key}
- fill={config[dataKeys.score2Key]?.color}
- fillOpacity={hiddenKeys.has(dataKeys.score2Key) ? 0 : 1}
- radius={[4, 4, 0, 0]}
- />
- )}
-
- <ChartLegend
- content={
- <ScoreChartLegendContent
- interactive={isComparisonMode}
- visibilityState={visibilityState}
- onVisibilityChange={handleVisibilityToggle}
- />
- }
- />
- </BarChart>
- </ChartContainer>
+ <GroupedBarChart
+ data={data}
+ series={series}
+ legend={{
+ visibility: "visible",
+ interaction: comparison ? "toggle" : "highlight",
+ summary: "none",
+ }}
+ />
);
}
diff --git a/web/src/features/score-analytics/components/charts/ScoreDistributionCategoricalChart.tsx b/web/src/features/score-analytics/components/charts/ScoreDistributionCategoricalChart.tsx
index 56e36d9942..a7aa05b04c 100644
--- a/web/src/features/score-analytics/components/charts/ScoreDistributionCategoricalChart.tsx
+++ b/web/src/features/score-analytics/components/charts/ScoreDistributionCategoricalChart.tsx
@@ -1,13 +1,6 @@
-import { useMemo, useState, useCallback } from "react";
-import { Bar, BarChart, XAxis, YAxis } from "recharts";
-import {
- ChartContainer,
- ChartLegend,
- ChartTooltip,
- type ChartConfig,
-} from "@/src/components/ui/chart";
-import { ScoreChartLegendContent } from "./ScoreChartLegendContent";
-import { ScoreChartTooltip } from "../../lib/ScoreChartTooltip";
+import { useMemo } from "react";
+import { BarChart } from "@/src/components/design-system/charts/BarChart/BarChart";
+import { StackedBarChart } from "@/src/components/design-system/charts/StackedBarChart/StackedBarChart";
interface CategoricalChartProps {
distribution1: Array<{ binIndex: number; count: number }>;
@@ -24,12 +17,6 @@ interface CategoricalChartProps {
colors: Record<string, string>;
}
-/**
- * Categorical distribution chart component
- * Renders stacked bar charts for categorical score distributions
- * - Single score: One bar per category
- * - Two scores: Stacked bars showing score2 category breakdown within each score1 category
- */
export function ScoreDistributionCategoricalChart({
distribution1,
categories,
@@ -40,261 +27,88 @@ export function ScoreDistributionCategoricalChart({
score2Source,
colors,
}: CategoricalChartProps) {
- const hasStackedData = Boolean(
- stackedDistribution && stackedDistribution.length > 0,
- );
-
- // Helper: Check if a key represents an unmatched category
- // Backend can send: "__unmatched__", "0", "", or null
- const isUnmatchedKey = (key: string): boolean => {
- return (
- key === "__unmatched__" || key === "0" || key === "" || key === "null"
+ const unmatched = (key: string) =>
+ key === "__unmatched__" || key === "0" || key === "" || key === "null";
+ const { data, series } = useMemo(() => {
+ const stacks = new Set(
+ (score2Categories ?? []).filter((key) => !unmatched(key)),
);
- };
-
- // Calculate all possible stack keys from actual data
- // This ensures we include ALL categories present in the data, including those
- // not in score2Categories (e.g., "0" or other values) and __unmatched__
- const allStackKeys = useMemo(() => {
- if (!hasStackedData || !stackedDistribution || !score2Categories) {
- return [];
+ const grouped = new Map<string, Record<string, number>>();
+ for (const item of stackedDistribution ?? []) {
+ const key = unmatched(item.score2Stack)
+ ? "__unmatched__"
+ : item.score2Stack;
+ stacks.add(key);
+ const values = grouped.get(item.score1Category) ?? {};
+ values[key] = (values[key] ?? 0) + item.count;
+ grouped.set(item.score1Category, values);
}
-
- // Extract all unique score2 stack values from the actual data
- const stacksFromData = new Set<string>();
- stackedDistribution.forEach((item) => {
- stacksFromData.add(item.score2Stack);
- });
-
- // Normalize all unmatched variations to "__unmatched__" for consistent handling
- const normalizedStacks = Array.from(stacksFromData).map((key) =>
- isUnmatchedKey(key) ? "__unmatched__" : key,
- );
-
- // Separate regular categories from __unmatched__
- // This ensures __unmatched__ is always last for consistent color assignment
- const regularStacks = Array.from(
- new Set([...normalizedStacks, ...score2Categories]),
- )
- .filter((key) => key !== "__unmatched__")
- .sort(); // Sort alphabetically for stable color assignment
-
- // Add __unmatched__ at the end if it exists in the actual data
- const hasUnmatched = normalizedStacks.includes("__unmatched__");
-
- return hasUnmatched ? [...regularStacks, "__unmatched__"] : regularStacks;
- }, [hasStackedData, stackedDistribution, score2Categories]);
-
- // Transform data for Recharts
- const chartData = useMemo(() => {
- // If we have stacked distribution data (two-score comparison)
- if (hasStackedData && stackedDistribution && score2Categories) {
- const grouped = new Map<string, Record<string, number>>();
-
- stackedDistribution.forEach((item) => {
- if (!grouped.has(item.score1Category)) {
- grouped.set(item.score1Category, {});
- }
- // Normalize unmatched keys to "__unmatched__"
- const normalizedKey = isUnmatchedKey(item.score2Stack)
- ? "__unmatched__"
- : item.score2Stack;
- grouped.get(item.score1Category)![normalizedKey] = item.count;
- });
-
- // Normalize: ensure every category has all stack keys, even if count is 0
- return Array.from(grouped.entries())
- .sort((a, b) => {
- // Put __unmatched__ last (rightmost column)
- if (a[0] === "__unmatched__") return 1;
- if (b[0] === "__unmatched__") return -1;
- return a[0].localeCompare(b[0]);
- })
- .map(([category, stacks]) => {
- const normalizedStacks: Record<string, number> = {};
- allStackKeys.forEach((stackKey) => {
- normalizedStacks[stackKey] = stacks[stackKey] ?? 0;
- });
- return {
- name: category === "__unmatched__" ? "no match" : category,
- ...normalizedStacks,
- };
- });
- }
-
- // Single score: simple bar chart
- return [...distribution1]
- .sort((a, b) => a.binIndex - b.binIndex)
- .map((item) => {
- const label = categories[item.binIndex] ?? `Category ${item.binIndex}`;
- return {
- name: label,
- pv: item.count,
- };
- });
- }, [
- distribution1,
- categories,
- hasStackedData,
- stackedDistribution,
- score2Categories,
- allStackKeys,
- ]);
-
- // Visibility state for interactive legend (stacked mode only)
- const [hiddenKeys, setHiddenKeys] = useState<Set<string>>(new Set());
-
- // Create visibility state object for legend
- const visibilityState = useMemo(() => {
- if (!hasStackedData) return {};
- const state: Record<string, boolean> = {};
- allStackKeys.forEach((key) => {
- state[key] = !hiddenKeys.has(key);
- });
- return state;
- }, [hiddenKeys, hasStackedData, allStackKeys]);
-
- // Toggle handler
- const handleVisibilityToggle = useCallback(
- (key: string, visible: boolean) => {
- setHiddenKeys((prev) => {
- const next = new Set(prev);
- if (visible) {
- next.delete(key);
- } else {
- next.add(key);
- }
- return next;
- });
- },
- [],
- );
-
- // Configure chart colors and config using provided colors
- const config: ChartConfig = useMemo(() => {
- if (hasStackedData && allStackKeys.length > 0) {
- // Stacked mode: create config for all stack keys using color mappings
- const stackConfig: ChartConfig = {};
- allStackKeys.forEach((key) => {
- // Special handling for unmatched category
- if (key === "__unmatched__") {
- stackConfig[key] = {
- label: "no match",
- color: "hsl(var(--muted))", // Light grey for unmatched
- };
- return;
- }
-
- // Try namespaced key first (for when score1 and score2 have same category names)
- // Format: "ScoreName (source): category"
- let color: string | undefined;
-
- if (score2Name && score2Source) {
- const namespacedKey = `${score2Name} (${score2Source}): ${key}`;
- color = colors[namespacedKey];
- }
-
- // Fallback to non-namespaced key
- if (!color) {
- color = colors[key];
- }
-
- // Final fallback to first available color
- if (!color) {
- color = Object.values(colors)[0];
- }
-
- stackConfig[key] = {
- label: key,
- color,
- };
- });
- return stackConfig;
- }
-
- // Single score mode: use score name as label (category shown via custom tooltip)
- const firstColor = categories[0]
- ? colors[categories[0]]
- : Object.values(colors)[0];
+ const keys = [...stacks].filter((key) => key !== "__unmatched__").sort();
+ if (stacks.has("__unmatched__")) keys.push("__unmatched__");
return {
- pv: {
- label: score1Name,
- color: firstColor,
- },
+ data: [...grouped]
+ .sort(([a], [b]) => {
+ if (a === "__unmatched__") return 1;
+ if (b === "__unmatched__") return -1;
+ return a.localeCompare(b);
+ })
+ .map(([key, values]) => ({
+ key: key === "__unmatched__" ? "no match" : key,
+ values: Object.fromEntries(
+ keys.map((stack) => [stack, values[stack] ?? 0]),
+ ),
+ })),
+ series: keys.map((key) => ({
+ id: key,
+ label: key === "__unmatched__" ? "no match" : key,
+ color:
+ key === "__unmatched__"
+ ? "hsl(var(--muted))"
+ : (colors[`${score2Name} (${score2Source}): ${key}`] ??
+ colors[key] ??
+ Object.values(colors)[0] ??
+ "hsl(var(--chart-1))"),
+ })),
};
- }, [
- hasStackedData,
- allStackKeys,
- score1Name,
- score2Name,
- score2Source,
- colors,
- categories,
- ]);
+ }, [stackedDistribution, score2Categories, score2Name, score2Source, colors]);
+ if (stackedDistribution?.length && score2Categories) {
+ return (
+ <StackedBarChart
+ data={data}
+ series={series}
+ categoryXAxisLabels
+ legend={{
+ visibility: "visible",
+ interaction: "toggle",
+ summary: "none",
+ }}
+ />
+ );
+ }
+ const firstColor = categories[0]
+ ? colors[categories[0]]
+ : Object.values(colors)[0];
return (
- <ChartContainer
- config={config}
- className="[&_.recharts-rectangle.recharts-tooltip-cursor]:fill-transparent"
- >
- <BarChart accessibilityLayer data={chartData} margin={{ bottom: 20 }}>
- <XAxis
- dataKey="name"
- stroke="hsl(var(--chart-grid))"
- fontSize={12}
- tickLine={false}
- axisLine={{ stroke: "hsl(var(--border) / 0.5)" }}
- interval={0}
- />
- <YAxis
- stroke="hsl(var(--chart-grid))"
- fontSize={12}
- tickLine={false}
- axisLine={false}
- tickFormatter={(value) => value.toLocaleString()}
- />
- <ChartTooltip
- content={
- <ScoreChartTooltip
- valueFormatter={(value) => value.toLocaleString()}
- labelFormatter={(label) => String(label)}
- />
- }
- />
-
- {hasStackedData &&
- allStackKeys.map((stackKey) => {
- const isHidden = hiddenKeys.has(stackKey);
- return (
- <Bar
- key={stackKey}
- dataKey={stackKey}
- stackId="stack"
- fill={config[stackKey]?.color ?? "hsl(var(--chart-1))"}
- fillOpacity={isHidden ? 0 : 1}
- radius={[0, 0, 0, 0]}
- />
- );
- })}
- {!hasStackedData && (
- <Bar
- key="pv"
- dataKey="pv"
- fill={config.pv.color}
- radius={[4, 4, 0, 0]}
- />
- )}
-
- <ChartLegend
- content={
- <ScoreChartLegendContent
- interactive={hasStackedData}
- visibilityState={visibilityState}
- onVisibilityChange={handleVisibilityToggle}
- />
- }
- />
- </BarChart>
- </ChartContainer>
+ <BarChart
+ data={[...distribution1]
+ .sort((a, b) => a.binIndex - b.binIndex)
+ .map((item) => ({
+ label: categories[item.binIndex] ?? `Category ${item.binIndex}`,
+ value: item.count,
+ }))}
+ color={firstColor}
+ tooltipValueLabel={score1Name}
+ tooltipHeading={(label) => label}
+ legend={{
+ items: [
+ {
+ id: "score1",
+ label: score1Name,
+ color: firstColor ?? "hsl(var(--chart-1))",
+ },
+ ],
+ }}
+ />
);
}
diff --git a/web/src/features/score-analytics/components/charts/ScoreDistributionNumericChart.tsx b/web/src/features/score-analytics/components/charts/ScoreDistributionNumericChart.tsx
index 6de15b9f79..6a4f10819f 100644
--- a/web/src/features/score-analytics/components/charts/ScoreDistributionNumericChart.tsx
+++ b/web/src/features/score-analytics/components/charts/ScoreDistributionNumericChart.tsx
@@ -1,14 +1,6 @@
-import { useMemo, useState, useCallback } from "react";
-import { Bar, BarChart, XAxis, YAxis } from "recharts";
-import {
- ChartContainer,
- ChartLegend,
- ChartTooltip,
- type ChartConfig,
-} from "@/src/components/ui/chart";
-import { ScoreChartLegendContent } from "./ScoreChartLegendContent";
+import { useMemo } from "react";
+import { GroupedBarChart } from "@/src/components/design-system/charts/GroupedBarChart/GroupedBarChart";
import { compactNumberFormatter } from "@/src/utils/numbers";
-import { ScoreChartTooltip } from "../../lib/ScoreChartTooltip";
interface NumericChartProps {
distribution1: Array<{ binIndex: number; count: number }>;
@@ -19,12 +11,6 @@ interface NumericChartProps {
colors: { score1: string; score2?: string };
}
-/**
- * Numeric distribution chart component
- * Renders bar charts for numeric score distributions
- * - Single score: One bar per bin with hover effects
- * - Two scores: Grouped bars (side-by-side) for comparison
- */
export function ScoreDistributionNumericChart({
distribution1,
distribution2,
@@ -33,139 +19,47 @@ export function ScoreDistributionNumericChart({
score2Name,
colors,
}: NumericChartProps) {
- const isComparisonMode = Boolean(distribution2 && score2Name);
-
- // Transform data for Recharts
- const chartData = useMemo(() => {
- const dist2Map = distribution2
- ? new Map(distribution2.map((d) => [d.binIndex, d.count]))
- : null;
-
+ const comparison = Boolean(distribution2 && score2Name);
+ const data = useMemo(() => {
+ const second = new Map(
+ distribution2?.map((item) => [item.binIndex, item.count]),
+ );
return [...distribution1]
.sort((a, b) => a.binIndex - b.binIndex)
- .map((item) => {
- const label = binLabels[item.binIndex] ?? `Bin ${item.binIndex}`;
-
- if (isComparisonMode && dist2Map) {
- // Two score mode: use simple keys to avoid CSS variable name issues
- return {
- dimension: label,
- pv: item.count,
- uv: dist2Map.get(item.binIndex) ?? 0,
- };
- }
- // Single score mode - also use 'pv' for consistency with Bar dataKey
- return {
- dimension: label,
- pv: item.count,
- };
- });
- }, [distribution1, distribution2, binLabels, isComparisonMode]);
-
- // Configure chart config
- const config: ChartConfig = useMemo(() => {
- const cfg: ChartConfig = {
- pv: {
- label: score1Name,
- color: colors.score1,
- },
- };
-
- if (isComparisonMode && score2Name) {
- cfg.uv = {
- label: score2Name,
- color: colors.score2,
- };
- }
-
- return cfg;
- }, [isComparisonMode, score1Name, score2Name, colors]);
-
- // Visibility state for interactive legend (comparison mode only)
- const [hiddenKeys, setHiddenKeys] = useState<Set<string>>(new Set());
-
- // Create visibility state object for legend
- const visibilityState = useMemo(() => {
- if (!isComparisonMode) return undefined;
- return {
- pv: !hiddenKeys.has("pv"),
- uv: !hiddenKeys.has("uv"),
- };
- }, [hiddenKeys, isComparisonMode]);
-
- // Toggle handler
- const handleVisibilityToggle = useCallback(
- (key: string, visible: boolean) => {
- setHiddenKeys((prev) => {
- const next = new Set(prev);
- if (visible) {
- next.delete(key);
- } else {
- next.add(key);
- }
- return next;
- });
- },
- [],
+ .map((item) => ({
+ key: binLabels[item.binIndex] ?? `Bin ${item.binIndex}`,
+ values: {
+ score1: item.count,
+ ...(comparison ? { score2: second.get(item.binIndex) ?? 0 } : {}),
+ },
+ }));
+ }, [distribution1, distribution2, binLabels, comparison]);
+ const series = useMemo(
+ () => [
+ { id: "score1", label: score1Name, color: colors.score1 },
+ ...(comparison
+ ? [
+ {
+ id: "score2",
+ label: score2Name ?? "Score 2",
+ color: colors.score2 ?? colors.score1,
+ },
+ ]
+ : []),
+ ],
+ [score1Name, score2Name, colors, comparison],
);
return (
- <ChartContainer
- config={config}
- className="[&_.recharts-rectangle.recharts-tooltip-cursor]:fill-transparent"
- >
- <BarChart accessibilityLayer data={chartData} margin={{ bottom: 20 }}>
- <XAxis
- dataKey="dimension"
- stroke="hsl(var(--chart-grid))"
- fontSize={12}
- tickLine={false}
- axisLine={{ stroke: "hsl(var(--border) / 0.5)" }}
- interval={1}
- />
- <YAxis
- stroke="hsl(var(--chart-grid))"
- fontSize={12}
- tickLine={false}
- axisLine={false}
- niceTicks="auto"
- tickFormatter={(value) => compactNumberFormatter(value)}
- />
- <ChartTooltip
- content={
- <ScoreChartTooltip
- valueFormatter={compactNumberFormatter}
- labelFormatter={(label) => String(label)}
- />
- }
- />
-
- <Bar
- dataKey="pv"
- fill={colors.score1}
- fillOpacity={hiddenKeys.has("pv") ? 0 : 1}
- radius={[4, 4, 0, 0]}
- />
-
- {isComparisonMode && (
- <Bar
- dataKey="uv"
- fill={colors.score2}
- fillOpacity={hiddenKeys.has("uv") ? 0 : 1}
- radius={[4, 4, 0, 0]}
- />
- )}
-
- <ChartLegend
- content={
- <ScoreChartLegendContent
- interactive={isComparisonMode}
- visibilityState={visibilityState}
- onVisibilityChange={handleVisibilityToggle}
- />
- }
- />
- </BarChart>
- </ChartContainer>
+ <GroupedBarChart
+ data={data}
+ series={series}
+ valueFormatter={compactNumberFormatter}
+ legend={{
+ visibility: "visible",
+ interaction: comparison ? "toggle" : "highlight",
+ summary: "none",
+ }}
+ />
);
}
diff --git a/web/src/features/score-analytics/components/charts/ScoreTimeSeriesBooleanChart.tsx b/web/src/features/score-analytics/components/charts/ScoreTimeSeriesBooleanChart.tsx
index de91639f48..53eb1f09c1 100644
--- a/web/src/features/score-analytics/components/charts/ScoreTimeSeriesBooleanChart.tsx
+++ b/web/src/features/score-analytics/components/charts/ScoreTimeSeriesBooleanChart.tsx
@@ -1,211 +1,12 @@
-import { useMemo, useState, useCallback } from "react";
-import { Line, LineChart, XAxis, YAxis } from "recharts";
import {
- ChartActiveReferenceLine,
- ChartContainer,
- ChartLegend,
- ChartTooltip,
- type ChartConfig,
-} from "@/src/components/ui/chart";
-import {
- type IntervalConfig,
- type TimeRange,
-} from "@/src/utils/date-range-utils";
-import { formatChartTimestamp } from "../../lib/chart-formatters";
-import { ScoreChartTooltip } from "../../lib/ScoreChartTooltip";
-import { ScoreChartLegendContent } from "./ScoreChartLegendContent";
-
-export interface BooleanTimeSeriesChartProps {
- data: Array<{
- timestamp: Date;
- category: string;
- count: number;
- }>;
- score1Name: string;
- score2Name?: string;
- interval: IntervalConfig;
- timeRange: TimeRange;
- colors: Record<string, string>;
-}
-
-/**
- * Boolean time series chart component
- * Renders line charts showing counts for each category over time
- * One line per category with dynamic colors
- * Uses the same logic as CategoricalTimeSeriesChart
- */
-export function ScoreTimeSeriesBooleanChart({
- data,
- score1Name: _score1Name,
- score2Name: _score2Name,
- interval,
- timeRange,
- colors,
-}: BooleanTimeSeriesChartProps) {
- // Transform categorical data into pivot format for Recharts
- const { chartData, categories } = useMemo(() => {
- // Group by timestamp and collect all categories
- const groupedByTimestamp = new Map<number, Map<string, number>>();
- const allCategories = new Set<string>();
-
- data.forEach((item) => {
- const timestampKey = item.timestamp.getTime();
- if (!groupedByTimestamp.has(timestampKey)) {
- groupedByTimestamp.set(timestampKey, new Map());
- }
- const categoryMap = groupedByTimestamp.get(timestampKey)!;
- categoryMap.set(item.category, item.count);
- allCategories.add(item.category);
- });
-
- // Convert to chart data format
- // Sort by numeric timestamp BEFORE formatting to ensure chronological order
- const formattedData = Array.from(groupedByTimestamp.entries())
- .sort(([tsA], [tsB]) => tsA - tsB)
- .map(([timestamp, categoryMap]) => {
- const formattedTimestamp = formatChartTimestamp(
- new Date(timestamp),
- interval,
- timeRange,
- );
-
- const dataPoint: Record<string, string | number> = {
- time_dimension: formattedTimestamp,
- };
-
- // Add each category as a separate column
- allCategories.forEach((category) => {
- dataPoint[category] = categoryMap.get(category) ?? 0;
- });
-
- return dataPoint;
- });
-
- return {
- chartData: formattedData,
- categories: Array.from(allCategories).sort(),
- };
- }, [data, interval, timeRange]);
-
- // Visibility state for interactive legend
- const [hiddenKeys, setHiddenKeys] = useState<Set<string>>(new Set());
-
- // Create visibility state object for legend
- const visibilityState = useMemo(() => {
- const state: Record<string, boolean> = {};
- categories.forEach((category) => {
- state[category] = !hiddenKeys.has(category);
- });
- return state;
- }, [hiddenKeys, categories]);
-
- // Toggle handler
- const handleVisibilityToggle = useCallback(
- (key: string, visible: boolean) => {
- setHiddenKeys((prev) => {
- const next = new Set(prev);
- if (visible) {
- next.delete(key);
- } else {
- next.add(key);
- }
- return next;
- });
- },
- [],
- );
-
- // Create chart config with colors for each category
- const config: ChartConfig = useMemo(() => {
- const cfg: ChartConfig = {};
-
- categories.forEach((category) => {
- cfg[category] = {
- label: category,
- color: colors[category] || Object.values(colors)[0],
- };
- });
-
- return cfg;
- }, [categories, colors]);
-
- if (chartData.length === 0 || categories.length === 0) {
- return (
- <div className="text-muted-foreground flex h-[200px] items-center justify-center text-sm">
- No time series data available
- </div>
- );
- }
-
- // Check if all values are zero (no data in the selected time range)
- const hasAnyData = chartData.some((item) =>
- categories.some((category) => (item[category] as number) > 0),
- );
+ ScoreTimeSeriesCategoricalChart,
+ type CategoricalTimeSeriesChartProps,
+} from "./ScoreTimeSeriesCategoricalChart";
- if (!hasAnyData) {
- return (
- <div className="text-muted-foreground flex h-[200px] items-center justify-center text-sm">
- No data points available for the selected time range
- </div>
- );
- }
+export type BooleanTimeSeriesChartProps = CategoricalTimeSeriesChartProps;
- return (
- <ChartContainer config={config}>
- <LineChart accessibilityLayer data={chartData}>
- <XAxis
- dataKey="time_dimension"
- stroke="hsl(var(--chart-grid))"
- fontSize={12}
- tickLine={false}
- axisLine={{ stroke: "hsl(var(--border) / 0.5)" }}
- interval={1}
- />
- <YAxis
- stroke="hsl(var(--chart-grid))"
- fontSize={12}
- tickLine={false}
- axisLine={false}
- label={{ value: "Count", angle: -90, position: "insideLeft" }}
- niceTicks="auto"
- tickFormatter={(value) => value.toLocaleString()}
- />
- {categories.map((category) => {
- const isHidden = hiddenKeys.has(category);
- return (
- <Line
- key={category}
- type="monotone"
- dataKey={category}
- stroke={config[category]?.color}
- strokeWidth={2}
- strokeOpacity={isHidden ? 0 : 1}
- dot={!isHidden}
- activeDot={!isHidden ? { r: 6, strokeWidth: 0 } : false}
- connectNulls
- />
- );
- })}
- <ChartActiveReferenceLine />
- <ChartTooltip
- content={
- <ScoreChartTooltip
- interval={interval}
- timeRange={timeRange}
- valueFormatter={(value) => value.toLocaleString()}
- />
- }
- />
- <ChartLegend
- content={
- <ScoreChartLegendContent
- interactive={true}
- visibilityState={visibilityState}
- onVisibilityChange={handleVisibilityToggle}
- />
- }
- />
- </LineChart>
- </ChartContainer>
- );
+export function ScoreTimeSeriesBooleanChart(
+ props: BooleanTimeSeriesChartProps,
+) {
+ return <ScoreTimeSeriesCategoricalChart {...props} />;
}
diff --git a/web/src/features/score-analytics/components/charts/ScoreTimeSeriesCategoricalChart.tsx b/web/src/features/score-analytics/components/charts/ScoreTimeSeriesCategoricalChart.tsx
index b67f861e66..7994569dc9 100644
--- a/web/src/features/score-analytics/components/charts/ScoreTimeSeriesCategoricalChart.tsx
+++ b/web/src/features/score-analytics/components/charts/ScoreTimeSeriesCategoricalChart.tsx
@@ -1,26 +1,16 @@
-import { useMemo, useState, useCallback } from "react";
-import { Line, LineChart, XAxis, YAxis } from "recharts";
-import {
- ChartActiveReferenceLine,
- ChartContainer,
- ChartLegend,
- ChartTooltip,
- type ChartConfig,
-} from "@/src/components/ui/chart";
+import { useMemo } from "react";
+import { LineChart } from "@/src/components/design-system/charts/LineChart/LineChart";
import {
type IntervalConfig,
type TimeRange,
} from "@/src/utils/date-range-utils";
-import { formatChartTimestamp } from "../../lib/chart-formatters";
-import { ScoreChartTooltip } from "../../lib/ScoreChartTooltip";
-import { ScoreChartLegendContent } from "./ScoreChartLegendContent";
+import {
+ formatChartTimestamp,
+ formatChartTooltipTimestamp,
+} from "../../lib/chart-formatters";
export interface CategoricalTimeSeriesChartProps {
- data: Array<{
- timestamp: Date;
- category: string;
- count: number;
- }>;
+ data: Array<{ timestamp: Date; category: string; count: number }>;
score1Name: string;
score2Name?: string;
interval: IntervalConfig;
@@ -28,11 +18,6 @@ export interface CategoricalTimeSeriesChartProps {
colors: Record<string, string>;
}
-/**
- * Categorical time series chart component
- * Renders line charts showing counts for each category over time
- * One line per category with dynamic colors
- */
export function ScoreTimeSeriesCategoricalChart({
data,
score1Name: _score1Name,
@@ -41,107 +26,47 @@ export function ScoreTimeSeriesCategoricalChart({
timeRange,
colors,
}: CategoricalTimeSeriesChartProps) {
- // Transform categorical data into pivot format for Recharts
- const { chartData, categories } = useMemo(() => {
- // Group by timestamp and collect all categories
- const groupedByTimestamp = new Map<number, Map<string, number>>();
- const allCategories = new Set<string>();
-
- data.forEach((item) => {
- const timestampKey = item.timestamp.getTime();
- if (!groupedByTimestamp.has(timestampKey)) {
- groupedByTimestamp.set(timestampKey, new Map());
- }
- const categoryMap = groupedByTimestamp.get(timestampKey)!;
- categoryMap.set(item.category, item.count);
- allCategories.add(item.category);
- });
-
- // Convert to chart data format
- // Sort by numeric timestamp BEFORE formatting to ensure chronological order
- const formattedData = Array.from(groupedByTimestamp.entries())
- .sort(([tsA], [tsB]) => tsA - tsB)
- .map(([timestamp, categoryMap]) => {
- const formattedTimestamp = formatChartTimestamp(
- new Date(timestamp),
- interval,
- timeRange,
- );
-
- const dataPoint: Record<string, string | number> = {
- time_dimension: formattedTimestamp,
- };
-
- // Add each category as a separate column
- allCategories.forEach((category) => {
- dataPoint[category] = categoryMap.get(category) ?? 0;
- });
-
- return dataPoint;
- });
-
+ const { chartData, series } = useMemo(() => {
+ const grouped = new Map<number, Record<string, number>>();
+ const categories = new Set<string>();
+ for (const item of data) {
+ const key = item.timestamp.getTime();
+ const values = grouped.get(key) ?? {};
+ values[item.category] = item.count;
+ grouped.set(key, values);
+ categories.add(item.category);
+ }
+ const sorted = [...categories].sort();
return {
- chartData: formattedData,
- categories: Array.from(allCategories).sort(),
- };
- }, [data, interval, timeRange]);
-
- // Visibility state for interactive legend
- const [hiddenKeys, setHiddenKeys] = useState<Set<string>>(new Set());
-
- // Create visibility state object for legend
- const visibilityState = useMemo(() => {
- const state: Record<string, boolean> = {};
- categories.forEach((category) => {
- state[category] = !hiddenKeys.has(category);
- });
- return state;
- }, [hiddenKeys, categories]);
-
- // Toggle handler
- const handleVisibilityToggle = useCallback(
- (key: string, visible: boolean) => {
- setHiddenKeys((prev) => {
- const next = new Set(prev);
- if (visible) {
- next.delete(key);
- } else {
- next.add(key);
- }
- return next;
- });
- },
- [],
- );
-
- // Create chart config with colors for each category
- const config: ChartConfig = useMemo(() => {
- const cfg: ChartConfig = {};
-
- categories.forEach((category) => {
- cfg[category] = {
+ chartData: [...grouped]
+ .sort(([a], [b]) => a - b)
+ .map(([timestamp, values]) => ({
+ x: new Date(timestamp),
+ values: Object.fromEntries(
+ sorted.map((category) => [category, values[category] ?? 0]),
+ ) as Record<string, number>,
+ })),
+ series: sorted.map((category) => ({
+ id: category,
label: category,
- color: colors[category] || Object.values(colors)[0],
- };
- });
-
- return cfg;
- }, [categories, colors]);
+ color:
+ colors[category] ?? Object.values(colors)[0] ?? "hsl(var(--chart-1))",
+ })),
+ };
+ }, [data, colors]);
- if (chartData.length === 0 || categories.length === 0) {
+ if (chartData.length === 0 || series.length === 0) {
return (
<div className="text-muted-foreground flex h-[200px] items-center justify-center text-sm">
No time series data available
</div>
);
}
-
- // Check if all values are zero (no data in the selected time range)
- const hasAnyData = chartData.some((item) =>
- categories.some((category) => (item[category] as number) > 0),
- );
-
- if (!hasAnyData) {
+ if (
+ !chartData.some((item) =>
+ series.some((category) => item.values[category.id]! > 0),
+ )
+ ) {
return (
<div className="text-muted-foreground flex h-[200px] items-center justify-center text-sm">
No data points available for the selected time range
@@ -150,61 +75,20 @@ export function ScoreTimeSeriesCategoricalChart({
}
return (
- <ChartContainer config={config}>
- <LineChart accessibilityLayer data={chartData}>
- <XAxis
- dataKey="time_dimension"
- stroke="hsl(var(--chart-grid))"
- fontSize={12}
- tickLine={false}
- axisLine={{ stroke: "hsl(var(--border) / 0.5)" }}
- interval={1}
- />
- <YAxis
- stroke="hsl(var(--chart-grid))"
- fontSize={12}
- tickLine={false}
- axisLine={false}
- label={{ value: "Count", angle: -90, position: "insideLeft" }}
- niceTicks="auto"
- tickFormatter={(value) => value.toLocaleString()}
- />
- {categories.map((category) => {
- const isHidden = hiddenKeys.has(category);
- return (
- <Line
- key={category}
- type="monotone"
- dataKey={category}
- stroke={config[category]?.color}
- strokeWidth={2}
- strokeOpacity={isHidden ? 0 : 1}
- dot={!isHidden}
- activeDot={!isHidden ? { r: 6, strokeWidth: 0 } : false}
- connectNulls
- />
- );
- })}
- <ChartActiveReferenceLine />
- <ChartTooltip
- content={
- <ScoreChartTooltip
- interval={interval}
- timeRange={timeRange}
- valueFormatter={(value) => value.toLocaleString()}
- />
- }
- />
- <ChartLegend
- content={
- <ScoreChartLegendContent
- interactive={true}
- visibilityState={visibilityState}
- onVisibilityChange={handleVisibilityToggle}
- />
- }
- />
- </LineChart>
- </ChartContainer>
+ <LineChart
+ data={chartData}
+ series={series}
+ xAxis={{
+ type: "time",
+ tickFormatter: (value) =>
+ formatChartTimestamp(value, interval, timeRange),
+ tooltipFormatter: (value) =>
+ formatChartTooltipTimestamp(value, interval, timeRange),
+ }}
+ valueFormatter={(value) => value.toLocaleString()}
+ showDataPointDots
+ connectNulls
+ legend={{ visibility: "visible", interaction: "toggle", summary: "none" }}
+ />
);
}
diff --git a/web/src/features/score-analytics/components/charts/ScoreTimeSeriesNumericChart.tsx b/web/src/features/score-analytics/components/charts/ScoreTimeSeriesNumericChart.tsx
index c67d85c607..3e2378a47f 100644
--- a/web/src/features/score-analytics/components/charts/ScoreTimeSeriesNumericChart.tsx
+++ b/web/src/features/score-analytics/components/charts/ScoreTimeSeriesNumericChart.tsx
@@ -1,20 +1,14 @@
-import { useMemo, useState, useCallback } from "react";
-import { Line, LineChart, XAxis, YAxis } from "recharts";
-import {
- ChartActiveReferenceLine,
- ChartContainer,
- ChartLegend,
- ChartTooltip,
- type ChartConfig,
-} from "@/src/components/ui/chart";
+import { useMemo } from "react";
+import { LineChart } from "@/src/components/design-system/charts/LineChart/LineChart";
import {
type IntervalConfig,
type TimeRange,
} from "@/src/utils/date-range-utils";
import { compactNumberFormatter } from "@/src/utils/numbers";
-import { formatChartTimestamp } from "../../lib/chart-formatters";
-import { ScoreChartTooltip } from "../../lib/ScoreChartTooltip";
-import { ScoreChartLegendContent } from "./ScoreChartLegendContent";
+import {
+ formatChartTimestamp,
+ formatChartTooltipTimestamp,
+} from "../../lib/chart-formatters";
export interface NumericTimeSeriesChartProps {
data: Array<{
@@ -30,12 +24,6 @@ export interface NumericTimeSeriesChartProps {
colors: { score1: string; score2?: string };
}
-/**
- * Numeric time series chart component
- * Renders line charts for numeric score time series
- * - Single score: One line
- * - Two scores: Two lines for comparison
- */
export function ScoreTimeSeriesNumericChart({
data,
score1Name,
@@ -44,81 +32,32 @@ export function ScoreTimeSeriesNumericChart({
timeRange,
colors,
}: NumericTimeSeriesChartProps) {
- const isComparisonMode = Boolean(score2Name);
-
- // Transform data for Recharts
- const chartData = useMemo(() => {
- return data.map((item) => {
- // Format timestamp based on interval and time range
- const timestamp = formatChartTimestamp(
- item.timestamp,
- interval,
- timeRange,
- );
-
- if (isComparisonMode) {
- return {
- time_dimension: timestamp,
- [score1Name]: item.avg1,
- [score2Name!]: item.avg2,
- };
- }
-
- return {
- time_dimension: timestamp,
- [score1Name]: item.avg1,
- };
- });
- }, [data, score1Name, score2Name, interval, timeRange, isComparisonMode]);
-
- // Visibility state for interactive legend (comparison mode only)
- const [hiddenKeys, setHiddenKeys] = useState<Set<string>>(new Set());
-
- // Create visibility state object for legend
- const visibilityState = useMemo(() => {
- if (!isComparisonMode) return undefined;
- return {
- [score1Name]: !hiddenKeys.has(score1Name),
- ...(score2Name && { [score2Name]: !hiddenKeys.has(score2Name) }),
- };
- }, [hiddenKeys, score1Name, score2Name, isComparisonMode]);
-
- // Toggle handler
- const handleVisibilityToggle = useCallback(
- (key: string, visible: boolean) => {
- setHiddenKeys((prev) => {
- const next = new Set(prev);
- if (visible) {
- next.delete(key);
- } else {
- next.add(key);
- }
- return next;
- });
- },
- [],
- );
-
- const config: ChartConfig = useMemo(() => {
- if (isComparisonMode && score2Name) {
- return {
- [score1Name]: {
- label: score1Name,
- color: colors.score1,
+ const chartData = useMemo(
+ () =>
+ data.map((item) => ({
+ x: item.timestamp,
+ values: {
+ score1: item.avg1,
+ ...(score2Name ? { score2: item.avg2 } : {}),
},
- [score2Name]: {
- label: score2Name,
- color: colors.score2,
- },
- };
- }
- return {
- [score1Name]: {
- label: score1Name,
- color: colors.score1,
- },
- };
- }, [score1Name, score2Name, isComparisonMode, colors]);
+ })),
+ [data, score2Name],
+ );
+ const series = useMemo(
+ () => [
+ { id: "score1", label: score1Name, color: colors.score1 },
+ ...(score2Name
+ ? [
+ {
+ id: "score2",
+ label: score2Name,
+ color: colors.score2 ?? colors.score1,
+ },
+ ]
+ : []),
+ ],
+ [score1Name, score2Name, colors],
+ );
if (chartData.length === 0) {
return (
@@ -127,16 +66,13 @@ export function ScoreTimeSeriesNumericChart({
</div>
);
}
-
- // Check if all values are null (no data in the selected time range)
- const hasAnyData = chartData.some((item) => {
- if (isComparisonMode) {
- return item[score1Name] !== null || item[score2Name!] !== null;
- }
- return item[score1Name] !== null;
- });
-
- if (!hasAnyData) {
+ if (
+ !chartData.some(
+ (item) =>
+ item.values.score1 != null ||
+ (score2Name && item.values.score2 != null),
+ )
+ ) {
return (
<div className="text-muted-foreground flex h-[200px] items-center justify-center text-sm">
No data points available for the selected time range
@@ -145,70 +81,24 @@ export function ScoreTimeSeriesNumericChart({
}
return (
- <ChartContainer config={config}>
- <LineChart accessibilityLayer data={chartData}>
- <XAxis
- dataKey="time_dimension"
- stroke="hsl(var(--chart-grid))"
- fontSize={12}
- tickLine={false}
- axisLine={{ stroke: "hsl(var(--border) / 0.5)" }}
- interval={1}
- />
- <YAxis
- stroke="hsl(var(--chart-grid))"
- fontSize={12}
- tickLine={false}
- axisLine={false}
- niceTicks="auto"
- tickFormatter={(value) => compactNumberFormatter(value)}
- />
- <Line
- type="monotone"
- dataKey={score1Name}
- stroke={colors.score1}
- strokeWidth={2}
- strokeOpacity={hiddenKeys.has(score1Name) ? 0 : 1}
- dot={!hiddenKeys.has(score1Name)}
- activeDot={
- !hiddenKeys.has(score1Name) ? { r: 6, strokeWidth: 0 } : false
- }
- connectNulls
- />
- {isComparisonMode && score2Name && (
- <Line
- type="monotone"
- dataKey={score2Name}
- stroke={colors.score2}
- strokeWidth={2}
- strokeOpacity={hiddenKeys.has(score2Name) ? 0 : 1}
- dot={!hiddenKeys.has(score2Name)}
- activeDot={
- !hiddenKeys.has(score2Name) ? { r: 6, strokeWidth: 0 } : false
- }
- connectNulls
- />
- )}
- <ChartActiveReferenceLine />
- <ChartTooltip
- content={
- <ScoreChartTooltip
- interval={interval}
- timeRange={timeRange}
- valueFormatter={compactNumberFormatter}
- />
- }
- />
- <ChartLegend
- content={
- <ScoreChartLegendContent
- interactive={isComparisonMode}
- visibilityState={visibilityState}
- onVisibilityChange={handleVisibilityToggle}
- />
- }
- />
- </LineChart>
- </ChartContainer>
+ <LineChart
+ data={chartData}
+ series={series}
+ xAxis={{
+ type: "time",
+ tickFormatter: (value) =>
+ formatChartTimestamp(value, interval, timeRange),
+ tooltipFormatter: (value) =>
+ formatChartTooltipTimestamp(value, interval, timeRange),
+ }}
+ valueFormatter={compactNumberFormatter}
+ showDataPointDots
+ connectNulls
+ legend={{
+ visibility: "visible",
+ interaction: score2Name ? "toggle" : "highlight",
+ summary: "none",
+ }}
+ />
);
}
diff --git a/web/src/features/score-analytics/lib/ScoreChartTooltip.tsx b/web/src/features/score-analytics/lib/ScoreChartTooltip.tsx
deleted file mode 100644
index 82305d7cd5..0000000000
--- a/web/src/features/score-analytics/lib/ScoreChartTooltip.tsx
+++ /dev/null
@@ -1,157 +0,0 @@
-/* eslint-disable @repo/no-null-render */
-import {
- type IntervalConfig,
- type TimeRange,
-} from "@/src/utils/date-range-utils";
-import { formatChartTooltipTimestamp } from "./chart-formatters";
-import { useChart } from "@/src/components/ui/chart";
-import type { TooltipContentProps, TooltipValueType } from "recharts";
-
-/**
- * Props for the ScoreChartTooltip component.
- * Compatible with Recharts tooltip API.
- */
-export interface ScoreChartTooltipProps {
- active?: TooltipContentProps<TooltipValueType, string | number>["active"];
- payload?: TooltipContentProps<TooltipValueType, string | number>["payload"];
- label?: string | number;
- interval?: IntervalConfig;
- timeRange?: TimeRange;
- valueFormatter?: (value: number) => string;
- labelFormatter?: (label: string | number) => string;
-}
-
-/**
- * Custom tooltip component for Score Analytics charts.
- * Provides consistent styling and formatting across all chart types.
- *
- * Features:
- * - Sorted values (descending by magnitude)
- * - Custom value formatting (e.g., compact numbers, percentages)
- * - Dynamic timestamp formatting based on interval
- * - Color indicators for each data series
- * - Consistent design matching dashboard tooltips
- *
- * Usage:
- * ```tsx
- * <ChartTooltip
- * content={
- * <ScoreChartTooltip
- * interval={interval}
- * timeRange={timeRange}
- * valueFormatter={compactNumberFormatter}
- * />
- * }
- * />
- * ```
- */
-export function ScoreChartTooltip({
- active,
- payload,
- label,
- interval,
- timeRange,
- valueFormatter = (value: number) => value.toString(),
- labelFormatter,
-}: ScoreChartTooltipProps) {
- const { config } = useChart();
-
- if (!active || !payload || payload.length === 0) {
- return null;
- }
-
- // Filter out duplicates
- const uniquePayload = Array.from(
- new Map(
- payload.map((item) => [String(item.name ?? item.dataKey ?? ""), item]),
- ).values(),
- );
-
- // Sort payload by config key order for stable tooltip across columns
- // This maintains consistent ordering (e.g., alphabetical + unmatched last)
- // REVERSED to mirror the visual stack order (bottom-to-top becomes top-to-bottom in tooltip)
- // Falls back to value-based sorting if config keys not available
- const configKeys = Object.keys(config);
- const sortedPayload = uniquePayload.sort((a, b) => {
- const keyA = String(a.name ?? a.dataKey ?? "");
- const keyB = String(b.name ?? b.dataKey ?? "");
-
- // If both keys exist in config, sort by config order (reversed)
- const indexA = configKeys.indexOf(keyA);
- const indexB = configKeys.indexOf(keyB);
-
- if (indexA !== -1 && indexB !== -1) {
- return indexB - indexA; // Reversed: mirror visual stack order
- }
-
- // Fallback to value-based sorting (descending) for non-config keys
- return (Number(b.value) ?? 0) - (Number(a.value) ?? 0);
- });
-
- // Format the label (timestamp)
- let formattedLabel: string;
-
- if (labelFormatter) {
- // Use custom label formatter if provided
- formattedLabel = labelFormatter(label ?? "");
- } else if (typeof label === "string") {
- // Label is already formatted (from chart data transformation)
- formattedLabel = label;
- } else if (interval && timeRange && label) {
- // Format timestamp using interval-aware formatting (for numeric timestamps)
- const timestamp =
- typeof label === "number" ? new Date(label) : new Date(label);
- formattedLabel = formatChartTooltipTimestamp(
- timestamp,
- interval,
- timeRange,
- );
- } else {
- // Fallback to string representation
- formattedLabel = String(label ?? "");
- }
-
- return (
- <div className="border-border bg-background rounded-md border opacity-100 shadow-lg">
- {/* Header with timestamp/label */}
- <div className="border-border border-b px-3 py-1.5">
- <p className="text-muted-foreground text-sm font-bold">
- {formattedLabel}
- </p>
- </div>
-
- {/* Data series with values */}
- <div className="space-y-1 px-3 py-1.5">
- {sortedPayload.map((entry, index) => {
- // Get series label from config using the Bar's dataKey
- const seriesKey = String(entry.name ?? entry.dataKey ?? "");
- const seriesLabel = config[seriesKey]?.label || seriesKey;
-
- return (
- <div
- key={`${index}-${entry.name}`}
- className="flex items-center gap-2"
- >
- {/* Color indicator */}
- <div
- className="h-3 w-3 shrink-0 rounded-sm"
- style={{
- backgroundColor: entry.color ?? "hsl(var(--primary))",
- }}
- />
-
- {/* Series label from config */}
- <span className="text-muted-foreground flex-1 text-sm">
- {seriesLabel?.toString() ?? ""}
- </span>
- {/* Formatted value */}
- <span className="text-foreground text-sm font-bold">
- {valueFormatter(Number(entry.value ?? 0))}
- </span>
- </div>
- );
- })}
- </div>
- </div>
- );
-}
diff --git a/web/src/features/score-analytics/lib/chart-formatters.ts b/web/src/features/score-analytics/lib/chart-formatters.ts
index 5ae69038da..624535df40 100644
--- a/web/src/features/score-analytics/lib/chart-formatters.ts
+++ b/web/src/features/score-analytics/lib/chart-formatters.ts
@@ -31,27 +31,10 @@ export function formatChartTimestamp(
return format(date, formatString);
}
-/**
- * Format a timestamp for chart tooltips with more context than axis labels.
- * Tooltip timestamps typically include additional details like the date when
- * the axis shows only time, or the year when the axis shows only date.
- *
- * Examples:
- * - "Jan 15, 10:30:45" for second intervals (axis shows "10:30:45")
- * - "Jan 15, 10:30" for minute/hour intervals (axis shows "10:30")
- * - "Jan 15, 2025" for day intervals (axis shows "Jan 15")
- * - "Jan 2025" for month intervals (axis shows "Jan 2025")
- *
- * @param date - The timestamp to format
- * @param interval - The interval configuration (unit and count)
- * @param timeRange - The time range (relative or absolute)
- * @returns Formatted timestamp string for tooltip
- */
export function formatChartTooltipTimestamp(
date: Date,
interval: IntervalConfig,
timeRange: TimeRange,
-): string {
- const formatString = getChartTooltipFormat(interval, timeRange);
- return format(date, formatString);
+) {
+ return format(date, getChartTooltipFormat(interval, timeRange));
}
diff --git a/web/src/features/widgets/chart-library/Chart.tsx b/web/src/features/widgets/chart-library/Chart.tsx
index 55b4a53cdb..016ed25b43 100644
--- a/web/src/features/widgets/chart-library/Chart.tsx
+++ b/web/src/features/widgets/chart-library/Chart.tsx
@@ -27,7 +27,6 @@ import { AlertCircle } from "lucide-react";
import { BigNumber } from "@/src/features/widgets/chart-library/BigNumber";
import { PivotTable } from "@/src/features/widgets/chart-library/PivotTable";
import { type OrderByState } from "@langfuse/shared";
-import { type ChartConfig } from "@/src/components/ui/chart";
const DEFAULT_METRIC_THEME = {
light: "hsl(var(--chart-1))",
@@ -87,7 +86,7 @@ const ChartComponent = ({
show_data_point_dots?: boolean;
subtle_fill?: boolean;
};
- config?: ChartConfig;
+ config?: ChartProps["config"];
sortState?: OrderByState | null;
onSortChange?: (sortState: OrderByState | null) => void;
isLoading?: boolean;
@@ -156,7 +155,7 @@ const ChartComponent = ({
},
];
}),
- ) as ChartConfig;
+ ) as NonNullable<ChartProps["config"]>;
}, [config]);
const renderChart = () => {
diff --git a/web/src/features/widgets/chart-library/HistogramChart.tsx b/web/src/features/widgets/chart-library/HistogramChart.tsx
index 995a0b9863..4c89cd0117 100644
--- a/web/src/features/widgets/chart-library/HistogramChart.tsx
+++ b/web/src/features/widgets/chart-library/HistogramChart.tsx
@@ -2,12 +2,12 @@ import { HistogramChart as DesignSystemHistogramChart } from "@/src/components/d
import {
type DataPoint,
type MetricFormatterFunction,
+ type ChartProps,
} from "@/src/features/widgets/chart-library/chart-props";
import {
formatMetric,
toFullMetricString,
} from "@/src/features/widgets/chart-library/utils";
-import { type ChartConfig } from "@/src/components/ui/chart";
const HistogramChart = ({
data,
@@ -21,7 +21,7 @@ const HistogramChart = ({
metricFormatter = (value, options) => formatMetric(value, options),
}: {
data: DataPoint[];
- config?: ChartConfig;
+ config?: ChartProps["config"];
subtleFill?: boolean;
metricFormatter?: MetricFormatterFunction;
}) => {
diff --git a/web/src/features/widgets/chart-library/chart-props.ts b/web/src/features/widgets/chart-library/chart-props.ts
index 1ca4ca7ea8..05bebd6891 100644
--- a/web/src/features/widgets/chart-library/chart-props.ts
+++ b/web/src/features/widgets/chart-library/chart-props.ts
@@ -1,4 +1,4 @@
-import { type ChartConfig } from "@/src/components/ui/chart";
+import type { ComponentType, ReactNode } from "react";
import type tailwindColors from "tailwindcss/colors";
export interface DataPoint {
@@ -110,7 +110,15 @@ export interface ChartThreshold {
export interface ChartProps {
data: DataPoint[];
- config?: ChartConfig;
+ config?: {
+ [key: string]: {
+ label?: ReactNode;
+ icon?: ComponentType;
+ } & (
+ | { color?: string; theme?: never }
+ | { color?: never; theme: Record<"light" | "dark", string> }
+ );
+ };
accessibilityLayer?: boolean;
metricFormatter?: MetricFormatterFunction;
legendPosition?: LegendPosition;
diff --git a/web/src/utils/date-range-utils.ts b/web/src/utils/date-range-utils.ts
index 75fcb39d92..c50d56b454 100644
--- a/web/src/utils/date-range-utils.ts
+++ b/web/src/utils/date-range-utils.ts
@@ -517,49 +517,19 @@ export function getChartAxisFormat(
}
}
-/**
- * Get the appropriate date-fns format string for chart tooltip timestamps.
- * Tooltip formats provide more context than axis labels (e.g., include date when axis shows time).
- *
- * @param interval - The interval configuration (unit and count)
- * @param timeRange - The time range (relative or absolute)
- * @returns date-fns format string for tooltip timestamps
- */
export function getChartTooltipFormat(
interval: IntervalConfig,
timeRange: TimeRange,
-): string {
- const { unit } = interval;
-
- switch (unit) {
- case "second":
- // Show date + time with seconds for context
- return "MMM dd, HH:mm:ss";
-
- case "minute":
- // Show date + time
- return "MMM dd, HH:mm";
-
- case "hour":
- // Show date + time
- return "MMM dd, HH:mm";
-
- case "day":
- // Show date with year for extra context
- return "MMM dd, yyyy";
-
- case "month":
- // Show month and year
- return "MMM yyyy";
-
- case "year":
- // Show year
- return "yyyy";
-
- default:
- // Fallback - use axis format
- return getChartAxisFormat(interval, timeRange);
- }
+) {
+ const formats = {
+ second: "MMM dd, HH:mm:ss",
+ minute: "MMM dd, HH:mm",
+ hour: "MMM dd, HH:mm",
+ day: "MMM dd, yyyy",
+ month: "MMM yyyy",
+ year: "yyyy",
+ } satisfies Record<IntervalConfig["unit"], string>;
+ return formats[interval.unit] ?? getChartAxisFormat(interval, timeRange);
}
// Re-export fillTimeSeriesGaps from its own module