Skip to content

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

refactor(web): Create design-system BarChart (#17829)

Ben Bachem320af330f015
diff --git a/web/eslint.config.mjs b/web/eslint.config.mjs
index a89eddb331..576b21d4bd 100644
--- a/web/eslint.config.mjs
+++ b/web/eslint.config.mjs
@@ -286,11 +286,11 @@ export default [
{
name: "langfuse/web/design-system-component-structure",
files: ["src/components/design-system/**/*.{ts,tsx}"],
- ignores: [
- "src/components/design-system/charts/**",
- "src/components/design-system/factories/**",
- "src/components/design-system/internal/**",
- "src/components/design-system/table/**",
+ ignores: [
+ "src/components/design-system/charts/**",
+ "src/components/design-system/factories/**",
+ "src/components/design-system/internal/**",
+ "src/components/design-system/table/**",
],
plugins: {
"check-file": checkFile,
@@ -323,11 +323,11 @@ export default [
{
name: "langfuse/web/design-system-component-exports",
files: ["src/components/design-system/*/*.{ts,tsx}"],
- ignores: [
- "src/components/design-system/**/*.stories.{ts,tsx}",
- "src/components/design-system/charts/**",
- "src/components/design-system/table/**",
- ],
+ ignores: [
+ "src/components/design-system/**/*.stories.{ts,tsx}",
+ "src/components/design-system/charts/**",
+ "src/components/design-system/table/**",
+ ],
rules: {
"@repo/filename-matches-export": "error",
"import/no-default-export": "error",
@@ -538,6 +538,21 @@ export default [
},
},
+ {
+ name: "langfuse/web/design-system-internal-charts-naming",
+ files: ["src/components/design-system/internal/charts/**/*.{ts,tsx}"],
+ rules: {
+ "check-file/folder-naming-convention": [
+ "warn",
+ {
+ "src/components/design-system/*/": "KEBAB_CASE",
+ "src/components/design-system/internal/*/": "KEBAB_CASE",
+ "src/components/design-system/internal/charts/*/": "PASCAL_CASE",
+ },
+ ],
+ },
+ },
+
// Sanctioned homes for raw Sentry capture APIs: the reportError seam itself
// and the SDK init (`import * as Sentry` would otherwise trip the
// importNames restriction). Last-match wins in flat config, so these files
diff --git a/web/src/components/design-system/charts/BarChart/BarChart.stories.tsx b/web/src/components/design-system/charts/BarChart/BarChart.stories.tsx
new file mode 100644
index 0000000000..62ec4ac7d3
--- /dev/null
+++ b/web/src/components/design-system/charts/BarChart/BarChart.stories.tsx
@@ -0,0 +1,256 @@
+import preview from "../../../../../.storybook/preview";
+import { expect, userEvent, within } from "storybook/test";
+
+import { BarChart } from "./BarChart";
+
+const data = [
+ { label: "Alpha", value: 12 },
+ { label: "Beta", value: 24 },
+ { label: "Gamma", value: 18 },
+];
+
+const meta = preview.meta({
+ component: BarChart,
+ parameters: { layout: "fullscreen" },
+ args: { data },
+ decorators: [
+ (Story) => (
+ <div className="h-dvh w-full">
+ <Story />
+ </div>
+ ),
+ ],
+});
+
+export const Default = meta.story({});
+
+export const PositiveBaseline = meta.story({
+ name: "(Test) Positive Baseline",
+ play: async ({ canvasElement }) => {
+ const bars = within(canvasElement).getAllByRole("graphics-symbol");
+ const smallestBar = bars[0];
+ if (!smallestBar) throw new Error("Bar not found");
+ await expect(Number(smallestBar.getAttribute("height"))).toBeGreaterThan(1);
+ },
+});
+
+export const KeyboardFocus = meta.story({
+ name: "(Test) Keyboard Focus",
+ play: async ({ canvasElement }) => {
+ const canvas = within(canvasElement);
+ const firstBar = canvas.getByRole("graphics-symbol", { name: "Alpha: 12" });
+ firstBar.focus();
+ const tooltip = await within(canvasElement.ownerDocument.body).findByRole(
+ "tooltip",
+ );
+ await expect(tooltip).toHaveTextContent("Alpha");
+ await expect(tooltip).toHaveTextContent("12");
+ await expect(tooltip.querySelector("svg")).toBeNull();
+ await expect(firstBar).toHaveAttribute("fill", "hsl(var(--chart-1))");
+ await expect(
+ canvas.getByRole("graphics-symbol", { name: "Beta: 24" }),
+ ).toHaveAttribute("fill", expect.stringContaining("20%"));
+ await userEvent.tab();
+ await expect(
+ canvas.getByRole("graphics-symbol", { name: "Beta: 24" }),
+ ).toHaveFocus();
+ },
+});
+
+export const CategoryColors = meta.story({
+ args: {
+ data: data.map((item, index) => ({
+ ...item,
+ color: ["#3a3dee", "#07b9d5", "#f18a42"][index],
+ })),
+ legend: {
+ items: data.map((item, index) => ({
+ id: item.label,
+ label: item.label,
+ color: ["#3a3dee", "#07b9d5", "#f18a42"][index] ?? "",
+ })),
+ },
+ },
+});
+
+export const CategoryColorTooltip = meta.story({
+ name: "(Test) Category Color Tooltip",
+ args: {
+ data: data.map((item, index) => ({
+ ...item,
+ color: ["#3a3dee", "#07b9d5", "#f18a42"][index],
+ })),
+ },
+ play: async ({ canvasElement }) => {
+ const canvas = within(canvasElement);
+ canvas.getByRole("graphics-symbol", { name: "Alpha: 12" }).focus();
+ const tooltip = await within(canvasElement.ownerDocument.body).findByRole(
+ "tooltip",
+ );
+ await expect(tooltip.querySelector("svg rect")).toHaveAttribute(
+ "fill",
+ "#3a3dee",
+ );
+ },
+});
+
+export const CategoryColorsWithoutLegend = meta.story({
+ args: {
+ data: data.map((item, index) => ({
+ ...item,
+ color: ["#3a3dee", "#07b9d5", "#f18a42"][index],
+ })),
+ },
+});
+
+export const CompactLegend = meta.story({
+ name: "(Test) Compact Legend",
+ args: {
+ hideXAxisLabels: true,
+ data: data.map((item, index) => ({
+ ...item,
+ label: `production-evaluation-run-${item.label}-with-a-long-name`,
+ color: ["#3a3dee", "#07b9d5", "#f18a42"][index],
+ })),
+ legend: {
+ items: data.map((item, index) => ({
+ id: item.label,
+ label: `production-evaluation-run-${item.label}-with-a-long-name`,
+ color: ["#3a3dee", "#07b9d5", "#f18a42"][index] ?? "",
+ })),
+ },
+ },
+ play: async ({ canvasElement }) => {
+ const canvas = within(canvasElement);
+ await expect(
+ canvas
+ .getAllByTitle("production-evaluation-run-Alpha-with-a-long-name")
+ .some((item) => !item.closest('[aria-hidden="true"]')),
+ ).toBe(true);
+ await expect(
+ canvasElement.querySelectorAll("[data-x-axis-label]"),
+ ).toHaveLength(0);
+ },
+});
+
+export const ManyCategories = meta.story({
+ args: {
+ data: Array.from({ length: 9 }, (_, index) => ({
+ label: `Run ${index + 1}`,
+ value: 10 + index,
+ })),
+ },
+});
+
+export const SubtleFill = meta.story({
+ args: { variant: "subtle" },
+});
+
+export const LongLabels = meta.story({
+ name: "(Test) Long Labels",
+ args: {
+ data: Array.from({ length: 12 }, (_, index) => ({
+ label: `production-evaluation-run-${index + 1}-with-a-long-name`,
+ value: 12 + index,
+ })),
+ },
+ play: async ({ canvasElement }) => {
+ const canvas = within(canvasElement);
+ const firstBar = canvas.getAllByRole("graphics-symbol")[0];
+ if (!firstBar) throw new Error("Bar not found");
+ for (const label of canvasElement.querySelectorAll("[data-x-axis-label]")) {
+ await expect(label).toHaveAttribute("text-anchor", "middle");
+ }
+ await expect(
+ canvasElement.querySelector("[data-x-axis-label]"),
+ ).toHaveTextContent(/…$/);
+ await userEvent.hover(firstBar);
+ await expect(
+ canvasElement.querySelector("[data-active-x-axis-label]"),
+ ).toHaveTextContent("production-evaluation-run-1-with-a-long-name");
+ await expect(
+ canvasElement.querySelector("[data-active-x-axis-label-background]"),
+ ).toBeInTheDocument();
+ },
+});
+
+export const EdgeLabels = meta.story({
+ name: "(Test) Edge Labels",
+ args: {
+ data: [
+ { label: "production-evaluation-run-Alpha-with-a-long-name", value: 12 },
+ { label: "production-evaluation-run-Beta-with-a-long-name", value: 24 },
+ ],
+ },
+ decorators: [
+ (Story) => (
+ <div className="h-40 w-[300px]">
+ <Story />
+ </div>
+ ),
+ ],
+ play: async ({ canvasElement }) => {
+ for (const bar of within(canvasElement).getAllByRole("graphics-symbol")) {
+ await userEvent.hover(bar);
+ const label = canvasElement.querySelector<SVGTextElement>(
+ "[data-active-x-axis-label]",
+ );
+ const background = canvasElement.querySelector<SVGRectElement>(
+ "[data-active-x-axis-label-background]",
+ );
+ if (!label || !background) throw new Error("Active label not found");
+ const chartWidth = label.ownerSVGElement?.width.baseVal.value ?? 0;
+ for (const element of [label, background]) {
+ const bounds = element.getBBox();
+ await expect(bounds.x).toBeGreaterThanOrEqual(0);
+ await expect(bounds.x + bounds.width).toBeLessThanOrEqual(chartWidth);
+ }
+ }
+ },
+});
+
+export const FullyTruncatedLabels = meta.story({
+ name: "(Test) Fully Truncated Labels",
+ args: {
+ data: Array.from({ length: 20 }, (_, index) => ({
+ label: `Experiment ${index + 1}`,
+ value: index + 1,
+ })),
+ },
+ decorators: [
+ (Story) => (
+ <div className="h-40 w-[300px]">
+ <Story />
+ </div>
+ ),
+ ],
+ play: async ({ canvasElement }) => {
+ const canvas = within(canvasElement);
+ await expect(
+ canvasElement.querySelectorAll("[data-x-axis-label]"),
+ ).toHaveLength(0);
+ await expect(
+ canvasElement.querySelectorAll("[data-category-tick]"),
+ ).toHaveLength(20);
+ const firstBar = canvas.getByRole("graphics-symbol", {
+ name: "Experiment 1: 1",
+ });
+ firstBar.focus();
+ const tooltip = await within(canvasElement.ownerDocument.body).findByRole(
+ "tooltip",
+ );
+ await expect(tooltip).toHaveTextContent("Experiment 1");
+ },
+});
+
+export const NegativeValues = meta.story({
+ args: {
+ data: [
+ { label: "Increase", value: 8 },
+ { label: "Decrease", value: -5 },
+ { label: "No data", value: null },
+ ],
+ },
+});
+
+export const Empty = meta.story({ args: { data: [] } });
diff --git a/web/src/components/design-system/charts/BarChart/BarChart.tsx b/web/src/components/design-system/charts/BarChart/BarChart.tsx
new file mode 100644
index 0000000000..5f6011072c
--- /dev/null
+++ b/web/src/components/design-system/charts/BarChart/BarChart.tsx
@@ -0,0 +1,200 @@
+"use client";
+
+import { scaleBand, scaleLinear } from "d3-scale";
+
+import { ChartContainer } from "@/src/components/design-system/charts/ChartContainer";
+import { CartesianChart } from "@/src/components/design-system/internal/charts/CartesianChart";
+import { CartesianLayout } from "@/src/components/design-system/internal/charts/CartesianLayout";
+import {
+ ChartLegend,
+ type ChartLegendItem,
+} from "@/src/components/design-system/internal/charts/ChartLegend";
+import { ChartTooltip } from "@/src/components/design-system/internal/charts/ChartTooltip";
+
+export type BarChartDatum = {
+ label: string;
+ value: number | null;
+ color?: string;
+};
+
+type BarChartProps = {
+ data: BarChartDatum[];
+ valueFormatter?: (value: number) => string;
+ color?: string;
+ variant?: "default" | "subtle";
+ hideXAxisLabels?: boolean;
+ zeroBaseline?: boolean;
+ ariaLabel?: string;
+ legend?: { items: ChartLegendItem[] };
+};
+
+export function BarChart({
+ data,
+ valueFormatter = (value) => value.toLocaleString(),
+ color = "hsl(var(--chart-1))",
+ variant = "default",
+ hideXAxisLabels = false,
+ zeroBaseline = true,
+ ariaLabel = "Bar chart",
+ legend,
+}: BarChartProps) {
+ const firstColor = data[0]?.color ?? color;
+ const hasDistinctColors = data.some(
+ (datum) => (datum.color ?? color) !== firstColor,
+ );
+
+ 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 values = data.flatMap((datum) =>
+ typeof datum.value === "number" &&
+ Number.isFinite(datum.value)
+ ? [datum.value]
+ : [],
+ );
+ const min = values.length ? Math.min(...values) : 0;
+ const max = values.length ? Math.max(...values) : 1;
+ const domainMin = zeroBaseline ? Math.min(0, min) : min;
+ const domainMax = Math.max(
+ zeroBaseline || min < 0 ? 0 : min,
+ max,
+ );
+ const domainPadding = Math.max(Math.abs(domainMin) * 0.1, 1);
+ const plotHeight = measuredPlot.height;
+ const yScale = scaleLinear()
+ .domain(
+ domainMin === domainMax
+ ? [domainMin - domainPadding, domainMax + domainPadding]
+ : [domainMin, domainMax],
+ )
+ .nice(maxYTicks)
+ .range([measuredPlot.top + plotHeight, measuredPlot.top]);
+ const yTicks = yScale.ticks(maxYTicks);
+ const plot = plotForTicks(yTicks.map(valueFormatter));
+ const leftMargin = plot.left;
+ const plotWidth = plot.width;
+ const xScale = scaleBand<number>()
+ .domain(data.map((_, index) => index))
+ .range([leftMargin, leftMargin + plotWidth])
+ .paddingInner(0.2)
+ .paddingOuter(0.1);
+ const baseline = yScale(
+ zeroBaseline || min < 0 ? 0 : (yScale.domain()[0] ?? 0),
+ );
+ const xTicks = data.map((datum, index) => ({
+ key: String(index),
+ x: (xScale(index) ?? leftMargin) + xScale.bandwidth() / 2,
+ label: datum.label,
+ maxWidth: xScale.bandwidth() - 8,
+ }));
+
+ if (
+ width <= 0 ||
+ height <= 0 ||
+ plotWidth <= 0 ||
+ plotHeight <= 0
+ ) {
+ return (
+ <svg width={width} height={height} aria-hidden="true" />
+ );
+ }
+
+ return (
+ <ChartTooltip>
+ {({ activeIndex, getReferenceProps }) => (
+ <CartesianChart
+ width={width}
+ height={height}
+ ariaLabel={ariaLabel}
+ overflow="hidden"
+ plot={plot}
+ yTicks={yTicks}
+ y={yScale}
+ valueFormatter={valueFormatter}
+ zeroY={min < 0 ? yScale(0) : undefined}
+ xAxis={
+ hideXAxisLabels
+ ? undefined
+ : {
+ ticks: xTicks,
+ activeKey:
+ activeIndex === undefined
+ ? undefined
+ : String(activeIndex),
+ showCategoryTicks: true,
+ alignment: "center",
+ }
+ }
+ >
+ {data.map((datum, index) => {
+ const x = xScale(index);
+ if (x === undefined) return null;
+ const barColor = datum.color ?? color;
+ const y =
+ datum.value !== null && Number.isFinite(datum.value)
+ ? yScale(datum.value)
+ : baseline;
+ const barTop = Math.min(y, baseline);
+ const barHeight = Math.abs(y - baseline);
+ const active = activeIndex === index;
+ let colorStrength = 100;
+ if (variant === "subtle") {
+ colorStrength = active ? 60 : 30;
+ }
+ if (activeIndex !== undefined && !active) {
+ colorStrength = variant === "subtle" ? 15 : 20;
+ }
+ const fill =
+ colorStrength === 100
+ ? barColor
+ : `color-mix(in srgb, ${barColor} ${colorStrength}%, hsl(var(--background)))`;
+ return (
+ <g key={index}>
+ {datum.value !== null &&
+ Number.isFinite(datum.value) ? (
+ <rect
+ x={x}
+ y={barTop}
+ width={xScale.bandwidth()}
+ height={Math.max(1, barHeight)}
+ rx={Math.min(4, barHeight / 2)}
+ fill={fill}
+ role="graphics-symbol"
+ tabIndex={0}
+ aria-label={`${datum.label}: ${valueFormatter(datum.value)}`}
+ className="outline-hidden transition-[fill] duration-150 focus-visible:outline-2 focus-visible:outline-offset-2"
+ {...getReferenceProps({
+ type: "primary",
+ index,
+ label: datum.label,
+ value: valueFormatter(datum.value),
+ color: hasDistinctColors
+ ? barColor
+ : undefined,
+ })}
+ />
+ ) : null}
+ </g>
+ );
+ })}
+ </CartesianChart>
+ )}
+ </ChartTooltip>
+ );
+ }}
+ </CartesianLayout>
+ )}
+ </ChartContainer>
+ </div>
+ {legend?.items.length ? <ChartLegend items={legend.items} /> : null}
+ </div>
+ );
+}
diff --git a/web/src/components/design-system/charts/ChartLegend.tsx b/web/src/components/design-system/charts/ChartLegend.tsx
index 7457cae08b..64f07e01e2 100644
--- a/web/src/components/design-system/charts/ChartLegend.tsx
+++ b/web/src/components/design-system/charts/ChartLegend.tsx
@@ -1,250 +1,4 @@
-"use client";
-
-import {
- useCallback,
- useLayoutEffect,
- useRef,
- useState,
- type ReactNode,
-} from "react";
-
-import { DropdownMenu } from "@/src/components/design-system/DropdownMenu/DropdownMenu";
-import { getPlainTextFromReactNode } from "@/src/utils/react-node-plain-text";
-import { cn } from "@/src/utils/tailwind";
-
-export type ChartLegendItem = {
- id: string;
- label: ReactNode;
- color: string;
- value?: { label: string; value: ReactNode };
- muted?: boolean;
- action?: {
- label: string;
- pressed: boolean;
- onClick: () => void;
- };
-};
-
-const LEGEND_ITEM_GAP = 16;
-
-function LegendItem({ item }: { item: ChartLegendItem }) {
- const plainTextLabel =
- typeof item.label === "string"
- ? item.label
- : getPlainTextFromReactNode(item.label);
- const plainTextValue = item.value
- ? getPlainTextFromReactNode(item.value.value)
- : undefined;
- const title = `${plainTextLabel ?? ""}${
- item.value && plainTextValue
- ? ` (${item.value.label}: ${plainTextValue})`
- : ""
- }`;
- const content = (
- <>
- <div
- className="h-2 w-2 shrink-0 rounded-[2px]"
- style={{ backgroundColor: item.color }}
- />
- <span
- className="text-muted-foreground truncate"
- title={title || undefined}
- >
- {item.label}
- {item.value !== undefined ? (
- <>
- {" "}
- ({item.value.label}: {item.value.value})
- </>
- ) : null}
- </span>
- </>
- );
- const className = cn(
- "flex max-w-full min-w-0 items-center gap-1.5 text-xs whitespace-nowrap transition-opacity",
- item.muted && "opacity-40",
- );
-
- return item.action ? (
- <button
- type="button"
- onClick={item.action.onClick}
- className={cn(className, "cursor-pointer hover:opacity-80")}
- aria-pressed={item.action.pressed}
- aria-label={item.action.label}
- >
- {content}
- </button>
- ) : (
- <div className={className}>{content}</div>
- );
-}
-
-export function ChartLegend({
- items,
- selectionActions,
-}: {
- items: ChartLegendItem[];
- selectionActions?: {
- allSelected: boolean;
- onSelectAll: () => void;
- onDeselectAll: () => void;
- };
-}) {
- const containerRef = useRef<HTMLDivElement>(null);
- const itemRefs = useRef<Array<HTMLDivElement | null>>([]);
- const overflowTriggerRefs = useRef<Array<HTMLSpanElement | null>>([]);
- const itemCountRef = useRef(items.length);
- const [visibleItemCount, setVisibleItemCount] = useState(0);
- itemCountRef.current = items.length;
-
- const measurementKey = items
- .map(
- (item) =>
- `${item.id}|${getPlainTextFromReactNode(item.label) ?? ""}|${item.value?.label ?? ""}|${getPlainTextFromReactNode(item.value?.value) ?? ""}`,
- )
- .join(";");
-
- const updateVisibleItemCount = useCallback(() => {
- const availableWidth = containerRef.current?.clientWidth ?? 0;
- const itemCount = itemCountRef.current;
- const itemWidths = Array.from(
- { length: itemCount },
- (_, index) => itemRefs.current[index]?.getBoundingClientRect().width ?? 0,
- );
- const allItemsWidth =
- itemWidths.reduce((total, width) => total + width, 0) +
- Math.max(0, itemCount - 1) * LEGEND_ITEM_GAP;
- if (allItemsWidth <= availableWidth) {
- setVisibleItemCount(itemCount);
- return;
- }
-
- let visibleWidth = 0;
- let nextVisibleItemCount = 0;
- for (let index = 0; index < itemCount; index += 1) {
- const hiddenItemCount = itemCount - index - 1;
- if (hiddenItemCount === 0) break;
- const triggerWidth =
- overflowTriggerRefs.current[
- hiddenItemCount - 1
- ]?.getBoundingClientRect().width ?? 0;
- const nextWidth =
- visibleWidth +
- itemWidths[index] +
- triggerWidth +
- (index > 0 ? 2 : 1) * LEGEND_ITEM_GAP;
- if (nextWidth > availableWidth) break;
- visibleWidth += itemWidths[index] + (index > 0 ? LEGEND_ITEM_GAP : 0);
- nextVisibleItemCount = index + 1;
- }
- setVisibleItemCount(nextVisibleItemCount);
- }, []);
-
- useLayoutEffect(() => {
- const container = containerRef.current;
- if (!container) return;
- const observer = new ResizeObserver(updateVisibleItemCount);
- observer.observe(container);
- return () => observer.disconnect();
- }, [updateVisibleItemCount]);
-
- useLayoutEffect(() => {
- updateVisibleItemCount();
- }, [measurementKey, updateVisibleItemCount]);
-
- const visibleItems = items.slice(0, visibleItemCount);
- const hiddenItems = items.slice(visibleItemCount);
-
- return (
- <div className="relative min-w-0 shrink-0 px-4 py-2">
- <div
- ref={containerRef}
- className="flex min-w-0 items-center justify-center gap-4 overflow-hidden"
- >
- {visibleItems.map((item) => (
- <LegendItem key={item.id} item={item} />
- ))}
- {hiddenItems.length > 0 ? (
- <DropdownMenu
- title="Additional series"
- items={[
- ...(selectionActions
- ? [
- {
- id: "all-series",
- type: "item" as const,
- title: selectionActions.allSelected
- ? "Deselect all"
- : "Select all",
- onClick: selectionActions.allSelected
- ? selectionActions.onDeselectAll
- : selectionActions.onSelectAll,
- },
- { id: "all-series-separator", type: "separator" as const },
- ]
- : []),
- ...hiddenItems.map((item) => ({
- id: item.id,
- type: "item" as const,
- title: `${
- typeof item.label === "string"
- ? item.label
- : (item.action?.label ?? item.id)
- }${
- item.value &&
- (typeof item.value.value === "string" ||
- typeof item.value.value === "number")
- ? ` (${item.value.label}: ${item.value.value})`
- : ""
- }`,
- disabled: item.action
- ? undefined
- : { reason: "This legend item is not interactive" },
- onClick: item.action?.onClick ?? (() => undefined),
- })),
- ]}
- >
- {({ getTriggerProps }) => (
- <button
- type="button"
- className="text-muted-foreground hover:text-foreground shrink-0 text-xs"
- aria-label={`Show ${hiddenItems.length} additional series`}
- {...getTriggerProps()}
- >
- +{hiddenItems.length}
- </button>
- )}
- </DropdownMenu>
- ) : null}
- </div>
-
- <div
- aria-hidden="true"
- className="invisible absolute top-0 left-0 flex h-0 items-center gap-4 overflow-hidden whitespace-nowrap"
- >
- {items.map((item, index) => (
- <div
- key={item.id}
- ref={(element) => {
- itemRefs.current[index] = element;
- }}
- >
- <LegendItem item={item} />
- </div>
- ))}
- {items.map((_, index) => (
- <span
- key={index}
- ref={(element) => {
- overflowTriggerRefs.current[index] = element;
- }}
- className="text-xs"
- >
- +{index + 1}
- </span>
- ))}
- </div>
- </div>
- );
-}
+export {
+ ChartLegend,
+ type ChartLegendItem,
+} from "@/src/components/design-system/internal/charts/ChartLegend";
diff --git a/web/src/components/design-system/charts/ChartTooltip.stories.tsx b/web/src/components/design-system/charts/ChartTooltip.stories.tsx
index b7913c2065..b3efb03475 100644
--- a/web/src/components/design-system/charts/ChartTooltip.stories.tsx
+++ b/web/src/components/design-system/charts/ChartTooltip.stories.tsx
@@ -2,7 +2,7 @@ import { type ComponentProps } from "react";
import preview from "../../../../.storybook/preview";
import { expect, userEvent, within } from "storybook/test";
-import { ChartTooltip } from "./ChartTooltip";
+import { ChartTooltip } from "../internal/charts/ChartTooltip";
type ChartTooltipController = Parameters<
ComponentProps<typeof ChartTooltip>["children"]
diff --git a/web/src/components/design-system/charts/LineChart/LineChart.stories.tsx b/web/src/components/design-system/charts/LineChart/LineChart.stories.tsx
index 0512b9e9e3..9be7b64a67 100644
--- a/web/src/components/design-system/charts/LineChart/LineChart.stories.tsx
+++ b/web/src/components/design-system/charts/LineChart/LineChart.stories.tsx
@@ -15,6 +15,7 @@ type LineChartStoryProps = {
| "empty"
| "many-lines"
| "boundary-points"
+ | "negative-values"
| "category-short-labels"
| "category-long-labels"
| "category-hidden-labels";
@@ -49,6 +50,7 @@ const LineChartDemo = (props: LineChartStoryProps) => {
}> = data;
if (props.variant === "many-lines") chartData = manyLinesData;
if (props.variant === "boundary-points") chartData = boundaryPointData;
+ if (props.variant === "negative-values") chartData = negativeData;
if (props.variant === "empty") chartData = [];
const chartSeries = props.variant === "many-lines" ? manyLinesSeries : series;
@@ -91,6 +93,11 @@ const boundaryPointData = [
{ x: new Date(Date.UTC(2026, 8, 2)), values: { api: 100, worker: null } },
];
+const negativeData = [
+ { x: new Date(Date.UTC(2026, 8, 1)), values: { api: -8, worker: null } },
+ { x: new Date(Date.UTC(2026, 8, 2)), values: { api: -3, worker: null } },
+];
+
const manyLinesSeries: LineChartSeries[] = Array.from(
{ length: 24 },
(_, index) => ({
@@ -152,14 +159,25 @@ export const BoundaryPoints = meta.story({
await expect(points).toHaveLength(2);
for (const point of points) {
const y = Number(point.getAttribute("cy"));
- await expect(y).toBeGreaterThanOrEqual(15);
- await expect(y).toBeLessThanOrEqual(
- (point.ownerSVGElement?.height.baseVal.value ?? 0) - 37,
+ const radius = Number(point.getAttribute("r"));
+ await expect(y).toBeGreaterThanOrEqual(radius);
+ await expect(y + radius).toBeLessThanOrEqual(
+ point.ownerSVGElement?.height.baseVal.value ?? 0,
);
}
},
});
+export const NegativeValues = meta.story({
+ name: "(Test) Negative Values",
+ args: { variant: "negative-values" },
+ play: async ({ canvasElement }) => {
+ await expect(
+ canvasElement.querySelector("[data-zero-baseline]"),
+ ).toBeInTheDocument();
+ },
+});
+
export const Empty = meta.story({
name: "(Test) Empty",
args: { variant: "empty" },
@@ -265,6 +283,7 @@ export const CategoryLongLabels = meta.story({
"tooltip",
);
await expect(tooltip).toHaveTextContent(categoryData[0]?.x ?? "");
+ await expect(tooltip.querySelector("svg")).toBeNull();
},
});
diff --git a/web/src/components/design-system/charts/LineChart/LineChart.tsx b/web/src/components/design-system/charts/LineChart/LineChart.tsx
index bfd59409ab..51a22e7635 100644
--- a/web/src/components/design-system/charts/LineChart/LineChart.tsx
+++ b/web/src/components/design-system/charts/LineChart/LineChart.tsx
@@ -1,12 +1,14 @@
"use client";
-import { useId, useMemo, useState, type PointerEvent } from "react";
+import { useMemo, useState, type PointerEvent } from "react";
import { scaleLinear, scalePoint, scaleUtc } from "d3-scale";
import { line } from "d3-shape";
import { ChartContainer } from "@/src/components/design-system/charts/ChartContainer";
-import { ChartLegend } from "@/src/components/design-system/charts/ChartLegend";
-import { ChartTooltip } from "@/src/components/design-system/charts/ChartTooltip";
+import { CartesianChart } from "@/src/components/design-system/internal/charts/CartesianChart";
+import { CartesianLayout } from "@/src/components/design-system/internal/charts/CartesianLayout";
+import { ChartLegend } from "@/src/components/design-system/internal/charts/ChartLegend";
+import { ChartTooltip } from "@/src/components/design-system/internal/charts/ChartTooltip";
type LineChartValues = {
values: Record<string, number | null>;
@@ -84,14 +86,8 @@ type NormalizedDatum = LineChartValues & {
x: Date | string;
};
-const LEFT_MARGIN = 64;
-const TOP_MARGIN = 10;
-const RIGHT_MARGIN = 16;
const APPROX_TIME_TICK_WIDTH = 64;
-const APPROX_CHARACTER_WIDTH = 7;
const CATEGORY_TICK_GAP = 16;
-const APPROX_Y_TICK_HEIGHT = 28;
-const DEFAULT_Y_TICK_COUNT = 5;
const SERIES_HOVER_DISTANCE = 10;
const MAX_VISIBLE_POINT_RADIUS = 5;
const defaultValueFormatter = (value: number) => value.toLocaleString();
@@ -253,18 +249,19 @@ const normalizeLineChartData = (
const getThresholdRegions = (
threshold: LineChartThreshold,
y: number,
+ top: number,
plotHeight: number,
) => {
const epsilon = Math.max(plotHeight * 0.01, 2);
- if (threshold.region === "above") return [[TOP_MARGIN, y - TOP_MARGIN]];
+ if (threshold.region === "above") return [[top, y - top]];
if (threshold.region === "below") {
- return [[y, TOP_MARGIN + plotHeight - y]];
+ return [[y, top + plotHeight - y]];
}
if (threshold.region === "equal") return [[y - epsilon, epsilon * 2]];
if (threshold.region === "not-equal") {
return [
- [TOP_MARGIN, y - epsilon - TOP_MARGIN],
- [y + epsilon, TOP_MARGIN + plotHeight - y - epsilon],
+ [top, y - epsilon - top],
+ [y + epsilon, top + plotHeight - y - epsilon],
];
}
return [];
@@ -296,13 +293,25 @@ export function LineChart(props: LineChartProps) {
<div className="min-h-0 flex-1">
<ChartContainer>
{({ width, height }) => (
- <LineChartContent
- {...props}
- series={configuredSeries}
- onActiveSeriesChange={setActiveSeriesId}
+ <CartesianLayout
width={width}
height={height}
- />
+ showXAxisLabels={
+ props.xAxis.type !== "category" ||
+ props.xAxis.labels !== "hidden"
+ }
+ >
+ {(layout) => (
+ <LineChartContent
+ {...props}
+ {...layout}
+ series={configuredSeries}
+ onActiveSeriesChange={setActiveSeriesId}
+ width={width}
+ height={height}
+ />
+ )}
+ </CartesianLayout>
)}
</ChartContainer>
</div>
@@ -367,6 +376,14 @@ function LineChartContent(
onActiveSeriesChange: (seriesId: string | undefined) => void;
width: number;
height: number;
+ measuredPlot: { left: number; top: number; width: number; height: number };
+ maxYTicks: number;
+ plotForTicks: (labels: string[]) => {
+ left: number;
+ top: number;
+ width: number;
+ height: number;
+ };
},
) {
const {
@@ -381,32 +398,73 @@ function LineChartContent(
width,
height,
xAxis,
+ measuredPlot,
+ maxYTicks,
+ plotForTicks,
} = props;
const [hoveredIndex, setHoveredIndex] = useState<number>();
const [hoveredSeriesId, setHoveredSeriesId] = useState<string>();
- const activeLabelGradientId = useId();
- const bottomMargin =
- xAxis.type === "category" && xAxis.labels === "hidden" ? 12 : 32;
- const plotWidth = Math.max(0, width - LEFT_MARGIN - RIGHT_MARGIN);
- const plotHeight = Math.max(0, height - TOP_MARGIN - bottomMargin);
+ const showXAxisLabels =
+ xAxis.type !== "category" || xAxis.labels !== "hidden";
+ const plotHeight = measuredPlot.height;
const yRangePadding = Math.min(MAX_VISIBLE_POINT_RADIUS, plotHeight / 2);
- const maxYTicks = Math.min(
- DEFAULT_Y_TICK_COUNT,
- Math.max(3, Math.floor(plotHeight / APPROX_Y_TICK_HEIGHT)),
- );
const data = useMemo<NormalizedDatum[]>(
() => normalizeLineChartData(props.data, props.xAxis.type),
[props.data, props.xAxis.type],
);
+ const yScale = useMemo(() => {
+ const values = data.flatMap((datum) =>
+ series.flatMap((item) => {
+ const value = datum.values[item.id];
+ return typeof value === "number" && Number.isFinite(value)
+ ? [value]
+ : [];
+ }),
+ );
+ values.push(...thresholds.map((threshold) => threshold.value));
+ let min = Math.min(...values);
+ let max = Math.max(...values);
+ if (!Number.isFinite(min) || !Number.isFinite(max)) {
+ min = 0;
+ max = 1;
+ } else if (min === max) {
+ const padding = Math.max(Math.abs(min) * 0.1, 1);
+ min -= padding;
+ max += padding;
+ }
+ if (min < 0) max = Math.max(0, max);
+ return scaleLinear()
+ .domain([min, max])
+ .nice(maxYTicks)
+ .range([
+ measuredPlot.top + plotHeight - yRangePadding,
+ measuredPlot.top + yRangePadding,
+ ]);
+ }, [
+ data,
+ maxYTicks,
+ measuredPlot.top,
+ plotHeight,
+ series,
+ thresholds,
+ yRangePadding,
+ ]);
+
+ const yTicks = yScale.ticks(maxYTicks);
+ const plot = plotForTicks(yTicks.map(valueFormatter));
+ const LEFT_MARGIN = plot.left;
+ const TOP_MARGIN = plot.top;
+ const plotWidth = plot.width;
+
const categoryScale = useMemo(
() =>
scalePoint<string>()
.domain(data.map((datum) => datum.key))
.range([LEFT_MARGIN, LEFT_MARGIN + plotWidth])
.padding(data.length > 1 ? 0 : 0.5),
- [data, plotWidth],
+ [LEFT_MARGIN, data, plotWidth],
);
const timeScale = useMemo(() => {
const timestamps = data.map((datum) =>
@@ -421,7 +479,7 @@ function LineChartContent(
return scaleUtc()
.domain([new Date(min), new Date(max)])
.range([LEFT_MARGIN, LEFT_MARGIN + plotWidth]);
- }, [data, plotWidth]);
+ }, [LEFT_MARGIN, data, plotWidth]);
const getX = (datum: NormalizedDatum) =>
datum.x instanceof Date
? timeScale(datum.x)
@@ -431,36 +489,6 @@ function LineChartContent(
? timeScale(new Date(Number(key)))
: (categoryScale(key) ?? LEFT_MARGIN);
- const yScale = useMemo(() => {
- const values = data.flatMap((datum) =>
- series.flatMap((item) => {
- const value = datum.values[item.id];
- return typeof value === "number" && Number.isFinite(value)
- ? [value]
- : [];
- }),
- );
- values.push(...thresholds.map((threshold) => threshold.value));
- let min = Math.min(...values);
- let max = Math.max(...values);
- if (!Number.isFinite(min) || !Number.isFinite(max)) {
- min = 0;
- max = 1;
- } else if (min === max) {
- const padding = Math.max(Math.abs(min) * 0.1, 1);
- min -= padding;
- max += padding;
- }
- return scaleLinear()
- .domain([min, max])
- .nice(maxYTicks)
- .range([
- TOP_MARGIN + plotHeight - yRangePadding,
- TOP_MARGIN + yRangePadding,
- ]);
- }, [data, maxYTicks, plotHeight, series, thresholds, yRangePadding]);
-
- const yTicks = yScale.ticks(maxYTicks);
const maxXTicks = Math.max(2, Math.floor(plotWidth / APPROX_TIME_TICK_WIDTH));
const firstX = data[0]?.x;
const lastX = data[data.length - 1]?.x;
@@ -489,24 +517,12 @@ function LineChartContent(
x: timeScale(value),
label: xAxis.tickFormatter?.(value) ?? value.toLocaleDateString(),
}))
- : data.map((datum) => {
- const label =
- xAxis.tickFormatter?.(String(datum.x)) ?? String(datum.x);
- const availableWidth =
- plotWidth / Math.max(1, data.length) - CATEGORY_TICK_GAP;
- const maxCharacters = Math.max(
- 1,
- Math.floor(availableWidth / APPROX_CHARACTER_WIDTH),
- );
- return {
- key: datum.key,
- x: getX(datum),
- label:
- label.length > maxCharacters
- ? `${label.slice(0, Math.max(0, maxCharacters - 1))}…`
- : label,
- };
- });
+ : data.map((datum) => ({
+ key: datum.key,
+ x: getX(datum),
+ label: xAxis.tickFormatter?.(String(datum.x)) ?? String(datum.x),
+ maxWidth: plotWidth / Math.max(1, data.length) - CATEGORY_TICK_GAP,
+ }));
const activeKey =
hoveredIndex === undefined ? sync?.activeKey : data[hoveredIndex]?.key;
const activeDatum = data.find((datum) => datum.key === activeKey);
@@ -529,7 +545,7 @@ function LineChartContent(
const visibleXTicks = activeXAxisTick
? [
...xTicks.filter((tick) => tick.key !== activeXAxisTick.key),
- activeXAxisTick,
+ { ...activeXAxisTick, maxWidth: undefined },
].sort((left, right) => left.x - right.x)
: xTicks;
const formatXTooltip = (datum: NormalizedDatum) => {
@@ -577,6 +593,9 @@ function LineChartContent(
setHoveredSeriesId(nearestSeriesId);
if (!hasConfiguredEmphasis) onActiveSeriesChange(nearestSeriesId);
};
+ const hasDistinctColors = series.some(
+ (item) => item.color !== series[0]?.color,
+ );
const hasConfiguredEmphasis = series.some(
(item) => item.emphasis && item.emphasis !== "default",
);
@@ -597,74 +616,41 @@ function LineChartContent(
return (
<ChartTooltip>
{({ activeIndex, getReferenceProps }) => (
- <svg
+ <CartesianChart
width={width}
height={height}
- role="group"
- aria-label={ariaLabel}
- className="block overflow-visible"
+ ariaLabel={ariaLabel}
+ plot={plot}
+ yTicks={yTicks}
+ y={yScale}
+ valueFormatter={valueFormatter}
+ categoryBoundaries={xAxis.type === "category"}
+ zeroY={
+ yScale.domain()[1] >= 0 &&
+ data.some((datum) =>
+ series.some((item) => (datum.values[item.id] ?? 0) < 0),
+ )
+ ? yScale(0)
+ : undefined
+ }
+ xAxis={
+ showXAxisLabels
+ ? {
+ ticks: visibleXTicks,
+ activeKey,
+ showCategoryTicks: xAxis.type === "category",
+ }
+ : undefined
+ }
>
- <defs>
- <linearGradient id={activeLabelGradientId} x1="0" x2="1">
- <stop
- offset="0"
- stopColor="hsl(var(--background))"
- stopOpacity="0"
- />
- <stop offset="0.2" stopColor="hsl(var(--background))" />
- <stop offset="0.8" stopColor="hsl(var(--background))" />
- <stop
- offset="1"
- stopColor="hsl(var(--background))"
- stopOpacity="0"
- />
- </linearGradient>
- </defs>
- {/* Point endpoint labels into the plot so their centered text boxes
- do not overflow its top or bottom edge. */}
- {yTicks.map((tick: number, index) => (
- <g key={tick}>
- <line
- x1={LEFT_MARGIN}
- x2={LEFT_MARGIN + plotWidth}
- y1={yScale(tick)}
- y2={yScale(tick)}
- stroke="hsl(var(--chart-grid))"
- />
- <text
- x={LEFT_MARGIN - 8}
- y={yScale(tick)}
- textAnchor="end"
- dominantBaseline={(() => {
- if (yTicks.length === 1) return "middle";
- if (index === 0) return "text-after-edge";
- if (index === yTicks.length - 1) return "text-before-edge";
- return "middle";
- })()}
- fill="hsl(var(--muted-foreground))"
- fontSize={12}
- >
- {valueFormatter(tick)}
- </text>
- </g>
- ))}
-
- {xAxis.type === "category"
- ? [LEFT_MARGIN, LEFT_MARGIN + plotWidth].map((x) => (
- <line
- key={`boundary-${x}`}
- x1={x}
- x2={x}
- y1={TOP_MARGIN}
- y2={TOP_MARGIN + plotHeight}
- stroke="hsl(var(--chart-grid))"
- />
- ))
- : null}
-
{thresholds.map((threshold, index) => {
const y = yScale(threshold.value);
- const regions = getThresholdRegions(threshold, y, plotHeight);
+ const regions = getThresholdRegions(
+ threshold,
+ y,
+ TOP_MARGIN,
+ plotHeight,
+ );
return (
<g key={`${threshold.value}-${index}`}>
{regions.map(([regionY, regionHeight], regionIndex) => (
@@ -782,83 +768,6 @@ function LineChartContent(
/>
) : null}
- {xAxis.type === "category" && xAxis.labels !== "hidden"
- ? data.map((datum) => (
- <line
- key={`category-tick-${datum.key}`}
- data-category-tick=""
- x1={getX(datum)}
- x2={getX(datum)}
- y1={TOP_MARGIN + plotHeight}
- y2={TOP_MARGIN + plotHeight + 4}
- stroke="hsl(var(--muted-foreground))"
- aria-hidden="true"
- />
- ))
- : null}
-
- {!(xAxis.type === "category" && xAxis.labels === "hidden")
- ? visibleXTicks
- .map((tick, index) => ({ tick, index }))
- .sort(
- (left, right) =>
- Number(left.tick.key === activeKey) -
- Number(right.tick.key === activeKey),
- )
- .map(({ tick, index }) => {
- const active = tick.key === activeKey;
- // Point endpoint labels into the plot so their text boxes do
- // not overflow the chart's left or right edge.
- let textAnchor: "start" | "middle" | "end" = "middle";
- if (visibleXTicks.length > 1 && index === 0) {
- textAnchor = "start";
- } else if (
- visibleXTicks.length > 1 &&
- index === visibleXTicks.length - 1
- ) {
- textAnchor = "end";
- }
- const activeLabelWidth =
- tick.label.length * APPROX_CHARACTER_WIDTH + 40;
- let activeLabelX = tick.x - activeLabelWidth / 2;
- if (textAnchor === "start") activeLabelX = tick.x - 20;
- if (textAnchor === "end") {
- activeLabelX = tick.x - activeLabelWidth + 20;
- }
- return (
- <g key={tick.key}>
- {active ? (
- <rect
- data-active-x-axis-label-background=""
- x={activeLabelX}
- y={TOP_MARGIN + plotHeight + 4}
- width={activeLabelWidth}
- height={17}
- rx={2}
- fill={`url(#${activeLabelGradientId})`}
- />
- ) : null}
- <text
- data-x-axis-label=""
- data-active-x-axis-label={active ? "" : undefined}
- x={tick.x}
- y={TOP_MARGIN + plotHeight + 16}
- textAnchor={textAnchor}
- fill={
- active
- ? "hsl(var(--foreground))"
- : "hsl(var(--muted-foreground))"
- }
- fontSize={12}
- fontWeight={active ? 700 : undefined}
- >
- {tick.label}
- </text>
- </g>
- );
- })
- : null}
-
{data.map((datum, index) => {
const currentX = getX(datum);
const left =
@@ -882,7 +791,7 @@ function LineChartContent(
id: item.id,
label: item.label,
value: valueFormatter(value),
- color: item.color,
+ color: hasDistinctColors ? item.color : undefined,
}));
const referenceProps = getReferenceProps({
type: "items",
@@ -967,7 +876,7 @@ function LineChartContent(
</g>
);
})}
- </svg>
+ </CartesianChart>
)}
</ChartTooltip>
);
diff --git a/web/src/components/design-system/charts/PieChart/PieChart.tsx b/web/src/components/design-system/charts/PieChart/PieChart.tsx
index 2db628a502..1653efa634 100644
--- a/web/src/components/design-system/charts/PieChart/PieChart.tsx
+++ b/web/src/components/design-system/charts/PieChart/PieChart.tsx
@@ -5,7 +5,7 @@ import { scaleOrdinal } from "d3-scale";
import { arc, pie, type PieArcDatum } from "d3-shape";
import { ChartContainer } from "@/src/components/design-system/charts/ChartContainer";
-import { ChartTooltip } from "@/src/components/design-system/charts/ChartTooltip";
+import { ChartTooltip } from "@/src/components/design-system/internal/charts/ChartTooltip";
import { chartColors } from "@/src/components/design-system/charts/chartColors";
import { cn } from "@/src/utils/tailwind";
diff --git a/web/src/components/design-system/internal/charts/CartesianChart.tsx b/web/src/components/design-system/internal/charts/CartesianChart.tsx
new file mode 100644
index 0000000000..aef03322a5
--- /dev/null
+++ b/web/src/components/design-system/internal/charts/CartesianChart.tsx
@@ -0,0 +1,305 @@
+"use client";
+
+import { useId, type ReactNode } from "react";
+
+import type { CartesianPlot } from "@/src/components/design-system/internal/charts/CartesianLayout";
+
+function ChartGrid({
+ yTicks,
+ y,
+ left,
+ top,
+ width,
+ height,
+ categoryBoundaries = false,
+}: {
+ yTicks: number[];
+ y: (value: number) => number;
+ left: number;
+ top: number;
+ width: number;
+ height: number;
+ categoryBoundaries?: boolean;
+}) {
+ return (
+ <g aria-hidden="true">
+ {yTicks.map((tick) => (
+ <line
+ key={tick}
+ x1={left}
+ x2={left + width}
+ y1={y(tick)}
+ y2={y(tick)}
+ stroke="hsl(var(--chart-grid))"
+ />
+ ))}
+ {categoryBoundaries
+ ? [left, left + width].map((x) => (
+ <line
+ key={x}
+ x1={x}
+ x2={x}
+ y1={top}
+ y2={top + height}
+ stroke="hsl(var(--chart-grid))"
+ />
+ ))
+ : null}
+ </g>
+ );
+}
+
+function ChartXAxis({
+ ticks,
+ activeKey,
+ y,
+ width,
+ showCategoryTicks = false,
+ alignment = "endpoints",
+}: {
+ ticks: { key: string; x: number; label: string; maxWidth?: number }[];
+ activeKey?: string;
+ y: number;
+ width: number;
+ showCategoryTicks?: boolean;
+ alignment?: "endpoints" | "center";
+}) {
+ const gradientId = useId();
+ const characterWidth = 7;
+ const hideLabels =
+ ticks.length > 0 &&
+ ticks.every(
+ (tick) =>
+ tick.maxWidth !== undefined &&
+ Math.floor(tick.maxWidth / characterWidth) <= 1 &&
+ tick.label.length > 1,
+ );
+ return (
+ <g>
+ <defs>
+ <linearGradient id={gradientId} x1="0" x2="1">
+ <stop offset="0" stopColor="hsl(var(--background))" stopOpacity="0" />
+ <stop offset="0.12" stopColor="hsl(var(--background))" />
+ <stop offset="0.88" stopColor="hsl(var(--background))" />
+ <stop offset="1" stopColor="hsl(var(--background))" stopOpacity="0" />
+ </linearGradient>
+ </defs>
+ {showCategoryTicks
+ ? ticks.map((tick) => (
+ <line
+ key={`category-tick-${tick.key}`}
+ data-category-tick=""
+ x1={tick.x}
+ x2={tick.x}
+ y1={y}
+ y2={y + 4}
+ stroke="hsl(var(--muted-foreground))"
+ aria-hidden="true"
+ />
+ ))
+ : null}
+ {!hideLabels &&
+ ticks
+ .map((tick, index) => ({ tick, index }))
+ .sort(
+ (left, right) =>
+ Number(left.tick.key === activeKey) -
+ Number(right.tick.key === activeKey),
+ )
+ .map(({ tick, index }) => {
+ const active = tick.key === activeKey;
+ let textAnchor: "start" | "middle" | "end" = "middle";
+ if (alignment === "endpoints") {
+ if (ticks.length > 1 && index === 0) textAnchor = "start";
+ else if (ticks.length > 1 && index === ticks.length - 1)
+ textAnchor = "end";
+ }
+ const maxCharacters = tick.maxWidth
+ ? Math.max(1, Math.floor(tick.maxWidth / characterWidth))
+ : undefined;
+ const label =
+ !active && maxCharacters && tick.label.length > maxCharacters
+ ? `${tick.label.slice(0, Math.max(0, maxCharacters - 1))}…`
+ : tick.label;
+ const activeLabelWidth = Math.min(
+ width - 16,
+ tick.label.length * characterWidth + 96,
+ );
+ const activeLabelX = Math.max(
+ 8,
+ Math.min(
+ width - 8 - activeLabelWidth,
+ tick.x - activeLabelWidth / 2,
+ ),
+ );
+ const activeTextWidth = Math.min(
+ width - 32,
+ tick.label.length * characterWidth,
+ );
+ const activeTextX = Math.max(
+ 16 + activeTextWidth / 2,
+ Math.min(width - 16 - activeTextWidth / 2, tick.x),
+ );
+
+ return (
+ <g key={tick.key}>
+ {active ? (
+ <rect
+ data-active-x-axis-label-background=""
+ x={activeLabelX}
+ y={y + 4}
+ width={activeLabelWidth}
+ height={17}
+ rx={2}
+ fill={`url(#${gradientId})`}
+ />
+ ) : null}
+ <text
+ data-x-axis-label=""
+ data-active-x-axis-label={active ? "" : undefined}
+ x={active ? activeTextX : tick.x}
+ y={y + 16}
+ textAnchor={active ? "middle" : textAnchor}
+ textLength={
+ active &&
+ tick.label.length * characterWidth > activeTextWidth
+ ? activeTextWidth
+ : undefined
+ }
+ lengthAdjust="spacingAndGlyphs"
+ fill={
+ active
+ ? "hsl(var(--foreground))"
+ : "hsl(var(--muted-foreground))"
+ }
+ fontSize={12}
+ fontWeight={active ? 700 : undefined}
+ >
+ {label}
+ </text>
+ </g>
+ );
+ })}
+ </g>
+ );
+}
+
+function ChartYAxis({
+ ticks,
+ y,
+ left,
+ valueFormatter,
+}: {
+ ticks: number[];
+ y: (value: number) => number;
+ left: number;
+ valueFormatter: (value: number) => string;
+}) {
+ return ticks.map((tick, index) => {
+ let dominantBaseline: "middle" | "text-after-edge" | "text-before-edge" =
+ "middle";
+ if (index === 0) dominantBaseline = "text-after-edge";
+ else if (index === ticks.length - 1) dominantBaseline = "text-before-edge";
+
+ return (
+ <text
+ key={tick}
+ x={left - 8}
+ y={y(tick)}
+ textAnchor="end"
+ dominantBaseline={dominantBaseline}
+ fill="hsl(var(--muted-foreground))"
+ fontSize={12}
+ >
+ {valueFormatter(tick)}
+ </text>
+ );
+ });
+}
+
+export function CartesianChart({
+ width,
+ height,
+ ariaLabel,
+ overflow = "visible",
+ plot,
+ yTicks,
+ y,
+ valueFormatter,
+ categoryBoundaries = false,
+ zeroY,
+ xAxis,
+ children,
+}: {
+ width: number;
+ height: number;
+ ariaLabel: string;
+ overflow?: "visible" | "hidden";
+ plot: CartesianPlot;
+ yTicks: number[];
+ y: (value: number) => number;
+ valueFormatter: (value: number) => string;
+ categoryBoundaries?: boolean;
+ zeroY?: number;
+ xAxis?: {
+ ticks: { key: string; x: number; label: string; maxWidth?: number }[];
+ activeKey?: string;
+ showCategoryTicks?: boolean;
+ alignment?: "endpoints" | "center";
+ };
+ children: ReactNode;
+}) {
+ return (
+ <svg
+ width={width}
+ height={height}
+ role="group"
+ aria-label={ariaLabel}
+ className={
+ overflow === "hidden"
+ ? "block overflow-hidden"
+ : "block overflow-visible"
+ }
+ >
+ <ChartGrid
+ yTicks={yTicks}
+ y={y}
+ left={plot.left}
+ top={plot.top}
+ width={plot.width}
+ height={plot.height}
+ categoryBoundaries={categoryBoundaries}
+ />
+ {zeroY !== undefined ? (
+ <line
+ data-zero-baseline=""
+ x1={plot.left}
+ x2={plot.left + plot.width}
+ y1={zeroY}
+ y2={zeroY}
+ stroke="hsl(var(--foreground))"
+ strokeWidth={1.5}
+ opacity={0.6}
+ aria-hidden="true"
+ />
+ ) : null}
+ <ChartYAxis
+ ticks={yTicks}
+ y={y}
+ left={plot.left}
+ valueFormatter={valueFormatter}
+ />
+ {children}
+ {xAxis ? (
+ <ChartXAxis
+ ticks={xAxis.ticks}
+ activeKey={xAxis.activeKey}
+ y={plot.top + plot.height}
+ width={width}
+ showCategoryTicks={xAxis.showCategoryTicks}
+ alignment={xAxis.alignment}
+ />
+ ) : null}
+ </svg>
+ );
+}
diff --git a/web/src/components/design-system/internal/charts/CartesianLayout.tsx b/web/src/components/design-system/internal/charts/CartesianLayout.tsx
new file mode 100644
index 0000000000..c9e4c2e30e
--- /dev/null
+++ b/web/src/components/design-system/internal/charts/CartesianLayout.tsx
@@ -0,0 +1,74 @@
+import type { ReactNode } from "react";
+
+const TOP = 10;
+const RIGHT = 16;
+const BOTTOM_WITH_LABELS = 26;
+const BOTTOM_WITHOUT_LABELS = 12;
+const Y_TICK_HEIGHT = 28;
+
+function getCartesianPlotHeight(height: number, showXAxisLabels: boolean) {
+ return Math.max(
+ 0,
+ height -
+ TOP -
+ (showXAxisLabels ? BOTTOM_WITH_LABELS : BOTTOM_WITHOUT_LABELS),
+ );
+}
+
+function getCartesianTickCount(plotHeight: number) {
+ return Math.min(5, Math.max(3, Math.floor(plotHeight / Y_TICK_HEIGHT)));
+}
+
+function getCartesianLayout({
+ width,
+ height,
+ showXAxisLabels,
+ yTickLabels,
+}: {
+ width: number;
+ height: number;
+ showXAxisLabels: boolean;
+ yTickLabels: string[];
+}) {
+ const left = Math.max(
+ 64,
+ ...yTickLabels.map((label) => label.length * 7 + 16),
+ );
+ return {
+ left,
+ top: TOP,
+ width: Math.max(0, width - left - RIGHT),
+ height: getCartesianPlotHeight(height, showXAxisLabels),
+ };
+}
+
+export type CartesianPlot = ReturnType<typeof getCartesianLayout>;
+
+export function CartesianLayout({
+ width,
+ height,
+ showXAxisLabels,
+ children,
+}: {
+ width: number;
+ height: number;
+ showXAxisLabels: boolean;
+ children: (layout: {
+ measuredPlot: CartesianPlot;
+ maxYTicks: number;
+ plotForTicks: (labels: string[]) => CartesianPlot;
+ }) => ReactNode;
+}) {
+ const measuredPlot = getCartesianLayout({
+ width,
+ height,
+ showXAxisLabels,
+ yTickLabels: [],
+ });
+ return children({
+ measuredPlot,
+ maxYTicks: getCartesianTickCount(measuredPlot.height),
+ plotForTicks: (yTickLabels) =>
+ getCartesianLayout({ width, height, showXAxisLabels, yTickLabels }),
+ });
+}
diff --git a/web/src/components/design-system/internal/charts/ChartLegend.tsx b/web/src/components/design-system/internal/charts/ChartLegend.tsx
new file mode 100644
index 0000000000..c563c2ac6a
--- /dev/null
+++ b/web/src/components/design-system/internal/charts/ChartLegend.tsx
@@ -0,0 +1,251 @@
+"use client";
+
+import {
+ useCallback,
+ useLayoutEffect,
+ useRef,
+ useState,
+ type ReactNode,
+} from "react";
+
+import { DropdownMenu } from "@/src/components/design-system/DropdownMenu/DropdownMenu";
+import { getPlainTextFromReactNode } from "@/src/utils/react-node-plain-text";
+import { cn } from "@/src/utils/tailwind";
+
+export type ChartLegendItem = {
+ id: string;
+ label: ReactNode;
+ color: string;
+ value?: { label: string; value: ReactNode };
+ muted?: boolean;
+ action?: {
+ label: string;
+ pressed: boolean;
+ onClick: () => void;
+ };
+};
+
+const LEGEND_ITEM_GAP = 16;
+const LEGEND_PADDING = "min-w-0 shrink-0 px-4 py-2";
+
+function LegendItem({ item }: { item: ChartLegendItem }) {
+ const plainTextLabel =
+ typeof item.label === "string"
+ ? item.label
+ : getPlainTextFromReactNode(item.label);
+ const plainTextValue = item.value
+ ? getPlainTextFromReactNode(item.value.value)
+ : undefined;
+ const title = `${plainTextLabel ?? ""}${
+ item.value && plainTextValue
+ ? ` (${item.value.label}: ${plainTextValue})`
+ : ""
+ }`;
+ const content = (
+ <>
+ <div
+ className="h-2 w-2 shrink-0 rounded-[2px]"
+ style={{ backgroundColor: item.color }}
+ />
+ <span
+ className="text-muted-foreground truncate"
+ title={title || undefined}
+ >
+ {item.label}
+ {item.value !== undefined ? (
+ <>
+ {" "}
+ ({item.value.label}: {item.value.value})
+ </>
+ ) : null}
+ </span>
+ </>
+ );
+ const className = cn(
+ "flex max-w-full min-w-0 items-center gap-1.5 text-xs whitespace-nowrap transition-opacity",
+ item.muted && "opacity-40",
+ );
+
+ return item.action ? (
+ <button
+ type="button"
+ onClick={item.action.onClick}
+ className={cn(className, "cursor-pointer hover:opacity-80")}
+ aria-pressed={item.action.pressed}
+ aria-label={item.action.label}
+ >
+ {content}
+ </button>
+ ) : (
+ <div className={className}>{content}</div>
+ );
+}
+
+export function ChartLegend({
+ items,
+ selectionActions,
+}: {
+ items: ChartLegendItem[];
+ selectionActions?: {
+ allSelected: boolean;
+ onSelectAll: () => void;
+ onDeselectAll: () => void;
+ };
+}) {
+ const containerRef = useRef<HTMLDivElement>(null);
+ const itemRefs = useRef<Array<HTMLDivElement | null>>([]);
+ const overflowTriggerRefs = useRef<Array<HTMLSpanElement | null>>([]);
+ const itemCountRef = useRef(items.length);
+ const [visibleItemCount, setVisibleItemCount] = useState(0);
+ itemCountRef.current = items.length;
+
+ const measurementKey = items
+ .map(
+ (item) =>
+ `${item.id}|${getPlainTextFromReactNode(item.label) ?? ""}|${item.value?.label ?? ""}|${getPlainTextFromReactNode(item.value?.value) ?? ""}`,
+ )
+ .join(";");
+
+ const updateVisibleItemCount = useCallback(() => {
+ const availableWidth = containerRef.current?.clientWidth ?? 0;
+ const itemCount = itemCountRef.current;
+ const itemWidths = Array.from(
+ { length: itemCount },
+ (_, index) => itemRefs.current[index]?.getBoundingClientRect().width ?? 0,
+ );
+ const allItemsWidth =
+ itemWidths.reduce((total, width) => total + width, 0) +
+ Math.max(0, itemCount - 1) * LEGEND_ITEM_GAP;
+ if (allItemsWidth <= availableWidth) {
+ setVisibleItemCount(itemCount);
+ return;
+ }
+
+ let visibleWidth = 0;
+ let nextVisibleItemCount = 0;
+ for (let index = 0; index < itemCount; index += 1) {
+ const hiddenItemCount = itemCount - index - 1;
+ if (hiddenItemCount === 0) break;
+ const triggerWidth =
+ overflowTriggerRefs.current[
+ hiddenItemCount - 1
+ ]?.getBoundingClientRect().width ?? 0;
+ const nextWidth =
+ visibleWidth +
+ itemWidths[index] +
+ triggerWidth +
+ (index > 0 ? 2 : 1) * LEGEND_ITEM_GAP;
+ if (nextWidth > availableWidth) break;
+ visibleWidth += itemWidths[index] + (index > 0 ? LEGEND_ITEM_GAP : 0);
+ nextVisibleItemCount = index + 1;
+ }
+ setVisibleItemCount(nextVisibleItemCount);
+ }, []);
+
+ useLayoutEffect(() => {
+ const container = containerRef.current;
+ if (!container) return;
+ const observer = new ResizeObserver(updateVisibleItemCount);
+ observer.observe(container);
+ return () => observer.disconnect();
+ }, [updateVisibleItemCount]);
+
+ useLayoutEffect(() => {
+ updateVisibleItemCount();
+ }, [measurementKey, updateVisibleItemCount]);
+
+ const visibleItems = items.slice(0, visibleItemCount);
+ const hiddenItems = items.slice(visibleItemCount);
+
+ return (
+ <div className={cn(LEGEND_PADDING, "relative")}>
+ <div
+ ref={containerRef}
+ className="flex min-w-0 items-center justify-center gap-4 overflow-hidden"
+ >
+ {visibleItems.map((item) => (
+ <LegendItem key={item.id} item={item} />
+ ))}
+ {hiddenItems.length > 0 ? (
+ <DropdownMenu
+ title="Additional series"
+ items={[
+ ...(selectionActions
+ ? [
+ {
+ id: "all-series",
+ type: "item" as const,
+ title: selectionActions.allSelected
+ ? "Deselect all"
+ : "Select all",
+ onClick: selectionActions.allSelected
+ ? selectionActions.onDeselectAll
+ : selectionActions.onSelectAll,
+ },
+ { id: "all-series-separator", type: "separator" as const },
+ ]
+ : []),
+ ...hiddenItems.map((item) => ({
+ id: item.id,
+ type: "item" as const,
+ title: `${
+ typeof item.label === "string"
+ ? item.label
+ : (item.action?.label ?? item.id)
+ }${
+ item.value &&
+ (typeof item.value.value === "string" ||
+ typeof item.value.value === "number")
+ ? ` (${item.value.label}: ${item.value.value})`
+ : ""
+ }`,
+ disabled: item.action
+ ? undefined
+ : { reason: "This legend item is not interactive" },
+ onClick: item.action?.onClick ?? (() => undefined),
+ })),
+ ]}
+ >
+ {({ getTriggerProps }) => (
+ <button
+ type="button"
+ className="text-muted-foreground hover:text-foreground shrink-0 text-xs"
+ aria-label={`Show ${hiddenItems.length} additional series`}
+ {...getTriggerProps()}
+ >
+ +{hiddenItems.length}
+ </button>
+ )}
+ </DropdownMenu>
+ ) : null}
+ </div>
+
+ <div
+ aria-hidden="true"
+ className="invisible absolute top-0 left-0 flex h-0 items-center gap-4 overflow-hidden whitespace-nowrap"
+ >
+ {items.map((item, index) => (
+ <div
+ key={item.id}
+ ref={(element) => {
+ itemRefs.current[index] = element;
+ }}
+ >
+ <LegendItem item={item} />
+ </div>
+ ))}
+ {items.map((_, index) => (
+ <span
+ key={index}
+ ref={(element) => {
+ overflowTriggerRefs.current[index] = element;
+ }}
+ className="text-xs"
+ >
+ +{index + 1}
+ </span>
+ ))}
+ </div>
+ </div>
+ );
+}
diff --git a/web/src/components/design-system/charts/ChartTooltip.tsx b/web/src/components/design-system/internal/charts/ChartTooltip.tsx
similarity index 96%
rename from web/src/components/design-system/charts/ChartTooltip.tsx
rename to web/src/components/design-system/internal/charts/ChartTooltip.tsx
index 211cf1f2f1..7455dec8aa 100644
--- a/web/src/components/design-system/charts/ChartTooltip.tsx
+++ b/web/src/components/design-system/internal/charts/ChartTooltip.tsx
@@ -33,7 +33,7 @@ type TooltipData = {
} & (
| {
type: "items";
- items: Array<TooltipItem & { id: string; color: string }>;
+ items: Array<TooltipItem & { id: string }>;
emphasizedItemId?: string;
label?: never;
value?: never;
@@ -45,7 +45,7 @@ type TooltipData = {
items?: never;
label: string;
value: string;
- color: string;
+ color?: string;
details?: Array<Omit<TooltipItem, "color">>;
emphasizedItemId?: never;
}
@@ -206,7 +206,7 @@ export function ChartTooltip({
<div
className={`flex min-w-0 items-center gap-2 leading-tight transition-opacity duration-150 ${item.emphasis === "dimmed" ? "opacity-30" : "opacity-100"}`}
>
- {item.kind !== "detail" ? (
+ {item.kind !== "detail" && item.color ? (
<svg
viewBox="0 0 10 10"
className="size-2.5 shrink-0"
@@ -214,9 +214,10 @@ export function ChartTooltip({
>
<rect width="10" height="10" rx="2" fill={item.color} />
</svg>
- ) : (
+ ) : null}
+ {item.kind === "detail" ? (
<span className="w-2.5 shrink-0" />
- )}
+ ) : null}
<div className="flex min-w-0 flex-1 items-center justify-between gap-x-3">
<span
className={`${item.emphasis === "emphasized" ? "text-foreground" : "text-muted-foreground"} truncate`}
diff --git a/web/src/features/experiments/components/ExperimentMetricStrip.tsx b/web/src/features/experiments/components/ExperimentMetricStrip.tsx
index 79cbded369..fbc2e27c95 100644
--- a/web/src/features/experiments/components/ExperimentMetricStrip.tsx
+++ b/web/src/features/experiments/components/ExperimentMetricStrip.tsx
@@ -42,26 +42,22 @@ import { chartMetricChangedProps } from "@/src/features/experiments/lib/analytic
const EMPTY_PLOT = <MetricStripMessage message="No values for this metric" />;
/**
- * The band's shared plot height plus one 20px row for the bar legend beneath
- * it. Constant, because the chart always draws exactly one row there — the
- * per-experiment legend, or the "hover a bar" note when there are more
- * experiments than the palette can tell apart — so the plot itself stays the
- * band's 63px and still lines up with the events and scores strips instead of
- * being squeezed to make room.
+ * Leave room for the experiment names on the x-axis without shrinking the
+ * plot below the neighboring strips' height.
*/
-const PLOT_WITH_LEGEND_HEIGHT_CLASS = "h-[83px]";
+const PLOT_WITH_LABELS_HEIGHT_CLASS = "h-[100px]";
/**
* What this strip's ready content occupies, for the band's loading and empty
* box: the 13px header row (a `leading-none` 13px trigger), the 6px gap under
- * it, and the plot with its legend. Taller than the band's default, and a
+ * it, and the plot with its labels. Taller than the band's default, and a
* placeholder of the wrong height drops the table by the difference the moment
* the data arrives.
*/
-const CONTENT_HEIGHT_CLASS = "h-[102px]";
+const CONTENT_HEIGHT_CLASS = "h-[119px]";
const AXIS_EXPLANATION =
- "One bar per experiment in view, oldest on the left and newest on the right, so a metric that improved over time climbs. The bars are a set of runs in start order, not a timeline — nothing is implied between two of them. The table below stays newest-first; filtering it changes which experiments are plotted, not their left-to-right order. Experiments with no value for this metric are left out. The legend below names each bar; past eight experiments the chart palette would give two bars the same colour, so the bars go one colour and hovering one names it. Which metric opens by default is data-driven: the numeric score recorded on the most items across these experiments, with ties settled by name, falling back to cost only when none of them carry a score. Pick any metric from the dropdown and that choice is kept instead.";
+ "One bar per experiment in view, oldest on the left and newest on the right, so a metric that improved over time climbs. The bars are a set of runs in start order, not a timeline — nothing is implied between two of them. The table below stays newest-first; filtering it changes which experiments are plotted, not their left-to-right order. Experiments with no value for this metric are left out. Experiment names appear on the x-axis; hovering a bar reveals its full name. Which metric opens by default is data-driven: the numeric score recorded on the most items across these experiments, with ties settled by name, falling back to cost only when none of them carry a score. Pick any metric from the dropdown and that choice is kept instead.";
/**
* Which columns carry the experiment, keyed by the chart's entity dimension.
@@ -351,7 +347,7 @@ export function ExperimentMetricStrip({
}
>
<div
- className={cn("mt-1.5 flex flex-col", PLOT_WITH_LEGEND_HEIGHT_CLASS)}
+ className={cn("mt-1.5 flex flex-col", PLOT_WITH_LABELS_HEIGHT_CLASS)}
>
{query && widgetConfig && (
<WidgetContent
@@ -370,12 +366,8 @@ export function ExperimentMetricStrip({
// The band is 63px: the chart's own "No data" card is taller than
// that and clips its own text inside it.
emptyState={EMPTY_PLOT}
- // Experiment names are far too long for the axis of a 63px band
- // (angled category labels cost ~60px of it). Identity moves to the
- // legend below the plot, which fits in the space the events strip
- // spends on tick labels, so the band's height is unchanged; the
- // tooltip carries the exact name either way.
- hideXAxisLabels
+ // The axis shows shortened names; hover restores the full name.
+ legendPosition="none"
colorBarsByCategory
// Bars are compared by length, so they have to start at zero.
zeroBaseline
diff --git a/web/src/features/widgets/chart-library/Chart.clienttest.tsx b/web/src/features/widgets/chart-library/Chart.clienttest.tsx
index 65cd34af9f..175de1b5f7 100644
--- a/web/src/features/widgets/chart-library/Chart.clienttest.tsx
+++ b/web/src/features/widgets/chart-library/Chart.clienttest.tsx
@@ -109,6 +109,12 @@ it("renders a compact bar chart whose values cross zero", () => {
/>,
);
- expect(container.querySelectorAll(".recharts-bar-rectangle")).toHaveLength(2);
+ expect(container.querySelectorAll('[role="graphics-symbol"]')).toHaveLength(
+ 2,
+ );
+ expect(container.querySelector("[data-zero-baseline]")).toHaveAttribute(
+ "stroke-width",
+ "1.5",
+ );
expect(screen.getByText("0")).toBeInTheDocument();
});
diff --git a/web/src/features/widgets/chart-library/Chart.tsx b/web/src/features/widgets/chart-library/Chart.tsx
index 420ba8f6f0..3e3501bb6e 100644
--- a/web/src/features/widgets/chart-library/Chart.tsx
+++ b/web/src/features/widgets/chart-library/Chart.tsx
@@ -105,8 +105,7 @@ const ChartComponent = ({
/**
* Hide x-axis tick labels on a categorical (entity-name) axis; the full name
* stays in the hover tooltip. Off by default. Consumed by the time-series
- * charts and forwarded to `prepareTimeAxis`. Used by the experiments /
- * dataset-compare charts.
+ * charts and forwarded to `prepareTimeAxis`. Used by dataset-compare charts.
*/
hideXAxisLabels?: boolean;
/**
@@ -249,6 +248,7 @@ const ChartComponent = ({
subtleFill={chartConfig?.subtle_fill}
hideXAxisLabels={hideXAxisLabels}
colorBarsByCategory={colorBarsByCategory}
+ legendPosition={legendPosition}
zeroBaseline={zeroBaseline}
/>
);
diff --git a/web/src/features/widgets/chart-library/VerticalBarChart.tsx b/web/src/features/widgets/chart-library/VerticalBarChart.tsx
index 2ac56d8e85..13993de181 100644
--- a/web/src/features/widgets/chart-library/VerticalBarChart.tsx
+++ b/web/src/features/widgets/chart-library/VerticalBarChart.tsx
@@ -1,169 +1,58 @@
-import React, { useMemo } from "react";
-import {
- ChartContainer,
- ChartTooltip,
- ChartTooltipContent,
-} from "@/src/components/ui/chart";
-import { Bar, BarChart, XAxis, YAxis } from "recharts";
+import { useMemo } from "react";
+
+import { BarChart as DesignSystemBarChart } from "@/src/components/design-system/charts/BarChart/BarChart";
import { type ChartProps } from "@/src/features/widgets/chart-library/chart-props";
+import { prepareCategoryBars } from "@/src/features/widgets/chart-library/prepareCategoryBars";
import {
formatMetric,
toFullMetricString,
} from "@/src/features/widgets/chart-library/utils";
-import { useChartTickBudget } from "@/src/features/widgets/chart-library/useChartTickBudget";
-import {
- prepareCategoryBars,
- type CategoryBarLegendItem,
-} from "@/src/features/widgets/chart-library/prepareCategoryBars";
-import { cn } from "@/src/utils/tailwind";
-/**
- * Names every bar, in bar order, in ONE row that never wraps. This legend is
- * built for a table strip's 63px band, where the wrapping/scrolling legend the
- * time-series charts use would crowd out the plot it is explaining. Names share
- * the row and ellipsize (full name in `title`), which still identifies runs
- * whose names differ early — as model/prompt variants do.
- */
-function CategoryBarLegend({ items }: { items: CategoryBarLegendItem[] }) {
- return (
- <div className="mt-1 flex h-4 min-w-0 shrink-0 items-center gap-x-3 overflow-hidden">
- {items.map((item) => (
- <div key={item.category} className="flex min-w-0 items-center gap-1.5">
- <div
- className="h-2 w-2 shrink-0 rounded-[2px]"
- style={{ backgroundColor: item.color }}
- />
- <span
- className="text-muted-foreground truncate text-xs leading-4"
- title={item.category}
- >
- {item.category}
- </span>
- </div>
- ))}
- </div>
- );
-}
-
-/**
- * VerticalBarChart component
- * @param data - Data to be displayed. Expects an array of objects with dimension and metric properties.
- * @param config - Configuration object for the chart. Can include theme settings for light and dark modes.
- * @param accessibilityLayer - Boolean to enable or disable the accessibility layer. Default is true.
- */
-export const VerticalBarChart: React.FC<ChartProps> = ({
+export function VerticalBarChart({
data,
- config = {
- metric: {
- theme: {
- light: "hsl(var(--chart-1))",
- dark: "hsl(var(--chart-1))",
- },
- },
- },
- accessibilityLayer = true,
- metricFormatter = (value, options) => formatMetric(value, options),
+ config,
+ metricFormatter = formatMetric,
subtleFill = false,
hideXAxisLabels = false,
colorBarsByCategory = false,
+ legendPosition,
zeroBaseline = false,
-}) => {
- const { ref: containerRef, maxYTicks } = useChartTickBudget();
-
+}: ChartProps) {
const categoryBars = useMemo(
() => (colorBarsByCategory ? prepareCategoryBars(data) : null),
[colorBarsByCategory, data],
);
- const rows = categoryBars?.rows ?? data;
- const legend = categoryBars?.legend ?? [];
-
+ const chartData = useMemo(
+ () =>
+ (categoryBars?.rows ?? data).map((row, index) => ({
+ label: row.dimension ?? "Unknown",
+ value: typeof row.metric === "number" ? row.metric : null,
+ color: categoryBars?.rows[index]?.fill,
+ })),
+ [categoryBars, data],
+ );
const formatValue = (value: number) =>
toFullMetricString(metricFormatter(value, { style: "compact" }));
return (
- <div className="flex h-full w-full min-w-0 flex-col">
- <ChartContainer
- ref={containerRef}
- config={config}
- className="min-h-0 flex-1 [&_.recharts-bar-rectangle:hover]:opacity-30 dark:[&_.recharts-bar-rectangle:hover]:opacity-100 dark:[&_.recharts-bar-rectangle:hover]:brightness-[3]"
- >
- <BarChart accessibilityLayer={accessibilityLayer} data={rows}>
- <XAxis
- type="category"
- dataKey="dimension"
- stroke="hsl(var(--chart-grid))"
- fontSize={12}
- tickLine={false}
- axisLine={false}
- niceTicks="auto"
- // Same treatment prepareTimeAxis gives a hidden categorical axis:
- // every tick drawn, label-less, on a slim axis. The category stays
- // in the legend and the tooltip.
- {...(hideXAxisLabels
- ? { interval: 0, tickFormatter: () => "", height: 8 }
- : {})}
- />
- <YAxis
- type="number"
- stroke="hsl(var(--chart-grid))"
- fontSize={12}
- tickLine={false}
- axisLine={false}
- niceTicks="auto"
- // `min(0, dataMin)` rather than a flat 0 so a negative series (a
- // delta) still fits, and the max keeps `"auto"`, which is what lets
- // niceTicks round the top of the scale.
- {...(zeroBaseline
- ? {
- domain: [
- (dataMin: number) => Math.min(0, dataMin),
- "auto" as const,
- ] as const,
- }
- : {})}
- // Ask for only as many ticks as the measured height fits, so
- // recharts never has to drop colliding labels — and so the zero
- // tick, the one that says where a bar is measured from, survives in
- // a short band.
- tickCount={maxYTicks}
- tickFormatter={(value) => formatValue(Number(value))}
- />
- <Bar
- dataKey="metric"
- radius={[4, 4, 0, 0]}
- // A CSS `fill` beats the per-row `fill` attribute the preparer set,
- // so the single-colour class only applies when there are no
- // per-category colours.
- className={cn(legend.length === 0 && "fill-(--color-metric)")}
- fillOpacity={subtleFill ? 0.3 : 1}
- isAnimationActive={false}
- />
- <ChartTooltip
- cursor={false}
- contentStyle={{ backgroundColor: "hsl(var(--background))" }}
- content={({ active, payload, label }) => (
- <ChartTooltipContent
- active={active}
- payload={payload}
- label={label}
- valueFormatter={(v) => formatValue(Number(v))}
- />
- )}
- />
- </BarChart>
- </ChartContainer>
- {legend.length > 0 ? (
- <CategoryBarLegend items={legend} />
- ) : (
- // No legend and no axis labels: say where identity lives rather than
- // leaving anonymous bars (manifesto principle 8).
- colorBarsByCategory &&
- hideXAxisLabels && (
- <div className="text-muted-foreground mt-1 h-4 shrink-0 text-right text-[11px] leading-4">
- Hover a bar to name it
- </div>
- )
- )}
- </div>
+ <DesignSystemBarChart
+ data={chartData}
+ color={config?.metric?.color ?? "hsl(var(--chart-1))"}
+ valueFormatter={formatValue}
+ variant={subtleFill ? "subtle" : "default"}
+ hideXAxisLabels={hideXAxisLabels}
+ zeroBaseline={zeroBaseline}
+ legend={
+ colorBarsByCategory && legendPosition !== "none"
+ ? {
+ items: (categoryBars?.legend ?? []).map((item) => ({
+ id: item.category,
+ label: item.category,
+ color: item.color,
+ })),
+ }
+ : undefined
+ }
+ />
);
-};
+}
diff --git a/web/src/features/widgets/chart-library/chart-props.ts b/web/src/features/widgets/chart-library/chart-props.ts
index f8af522c78..92da9fc536 100644
--- a/web/src/features/widgets/chart-library/chart-props.ts
+++ b/web/src/features/widgets/chart-library/chart-props.ts
@@ -158,14 +158,14 @@ export interface ChartProps {
* Give each bar of a categorical (entity) axis its own palette colour, plus a
* legend below the plot that names it. Off by default: a dashboard bar chart
* shows its categories on the axis and needs neither. Opt in where the axis
- * labels are hidden and the bars are entities rather than buckets — the
- * experiments strip, one bar per run. Colours and legend both come from
+ * bars are entities rather than buckets — the experiments strip, one bar
+ * per run. Colours and the optional legend both come from
* `prepareCategoryBars`, which also decides when there are too many bars for
* the bounded palette to identify any of them.
*/
colorBarsByCategory?: boolean;
/**
- * Measure the bars from zero instead of from recharts' fitted domain. A bar
+ * Measure the bars from zero instead of from a fitted domain. A bar
* encodes its value as a length, so this is what makes two bars comparable at
* all — on a fitted domain 0.80/0.87/1.00 draw as short/medium/full.
*
diff --git a/web/src/features/widgets/chart-library/prepareCategoryBars.ts b/web/src/features/widgets/chart-library/prepareCategoryBars.ts
index 45c3dfcbb4..73254c20c8 100644
--- a/web/src/features/widgets/chart-library/prepareCategoryBars.ts
+++ b/web/src/features/widgets/chart-library/prepareCategoryBars.ts
@@ -13,17 +13,14 @@ export const CATEGORY_COLOR_LIMIT = 8;
type CategoryBarRow = DataPoint & { fill?: string };
-export type CategoryBarLegendItem = { category: string; color: string };
-
export type CategoryBars = {
/**
- * Rows for recharts, each carrying its own `fill` when colour can identify.
- * A per-row `fill` is the recharts idiom the tooltip already reads back for
- * its swatch (see `getFillColor`), so bar, legend and tooltip cannot diverge.
+ * Rows carrying a `fill` when colour can identify. The widget adapter passes
+ * the same colour to the bar and tooltip, so they match the legend.
*/
rows: CategoryBarRow[];
/** One entry per bar, in bar order — empty when colour cannot identify. */
- legend: CategoryBarLegendItem[];
+ legend: { category: string; color: string }[];
/** Distinct categories, so a caller can say so when there is no legend. */
total: number;
};
diff --git a/web/src/features/widgets/components/InlineWidget.tsx b/web/src/features/widgets/components/InlineWidget.tsx
index 096637bf5f..88eaa3d9da 100644
--- a/web/src/features/widgets/components/InlineWidget.tsx
+++ b/web/src/features/widgets/components/InlineWidget.tsx
@@ -10,6 +10,7 @@ import {
} from "@langfuse/shared/query";
import { useScheduledDashboardExecuteQuery } from "@/src/features/dashboard/hooks/useDashboardQueryScheduler";
import { Chart } from "@/src/features/widgets/chart-library/Chart";
+import { type LegendPosition } from "@/src/features/widgets/chart-library/chart-props";
import { ChartLoadingState } from "@/src/features/widgets/chart-library/ChartLoadingState";
import {
getChartLoadingProgress,
@@ -80,16 +81,16 @@ export interface WidgetContentProps {
/**
* Hide x-axis tick labels on a categorical (entity-name) axis; the full name
* stays in the hover tooltip. Off by default. Opt in on entity-dimension
- * charts (experiments) whose long names clutter the axis.
+ * charts whose long names clutter the axis.
*/
hideXAxisLabels?: boolean;
/**
- * Colour each bar of a categorical (entity) axis and name it in a legend
- * below the plot. Off by default; opt in on an entity-dimension bar chart
- * whose axis labels are hidden (the experiments strip). See
+ * Colour each bar of a categorical (entity) axis. Off by default; opt in on
+ * entity-dimension bar charts such as the experiments strip. See
* `prepareCategoryBars`.
*/
colorBarsByCategory?: boolean;
+ legendPosition?: LegendPosition;
/**
* Measure bars from zero rather than from a fitted domain. Off by default;
* see `ChartProps.zeroBaseline`.
@@ -147,6 +148,7 @@ export function WidgetContent({
entityDimensionLabelMap,
hideXAxisLabels,
colorBarsByCategory,
+ legendPosition,
zeroBaseline,
emptyState,
}: WidgetContentProps) {
@@ -427,6 +429,7 @@ export function WidgetContent({
missingValue={getWidgetMissingBucketValue(metrics[0]?.agg ?? "count")}
hideXAxisLabels={hideXAxisLabels}
colorBarsByCategory={colorBarsByCategory}
+ legendPosition={legendPosition}
zeroBaseline={zeroBaseline}
emptyState={emptyState}
/>