🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.
TypeScript analyticsautogenevaluationlangchainlarge-language-modelsllama-indexllmllm-evaluationllm-observabilityllmopsmonitoringobservabilityopen-sourceopenaiplaygroundprompt-engineeringprompt-managementself-hostedycombinator
refactor(web): Create design-system HorizontalBarChart (#17848)
Ben Bachem09b652b671b7
diff --git a/web/src/components/design-system/charts/BarChart/BarChart.stories.tsx b/web/src/components/design-system/charts/BarChart/BarChart.stories.tsxindex 62ec4ac7d3..6f4f468478 100644--- a/web/src/components/design-system/charts/BarChart/BarChart.stories.tsx+++ b/web/src/components/design-system/charts/BarChart/BarChart.stories.tsx@@ -1,5 +1,5 @@import preview from "../../../../../.storybook/preview";-import { expect, userEvent, within } from "storybook/test";+import { expect, spyOn, userEvent, within } from "storybook/test";import { BarChart } from "./BarChart";@@ -45,7 +45,22 @@ export const KeyboardFocus = meta.story({);await expect(tooltip).toHaveTextContent("Alpha");await expect(tooltip).toHaveTextContent("12");- await expect(tooltip.querySelector("svg")).toBeNull();+ await expect(tooltip).toHaveTextContent(+ "Click or press Enter to copy label",+ );+ const copy = spyOn(navigator.clipboard, "writeText").mockResolvedValue();+ try {+ await userEvent.click(firstBar);+ await expect(copy).toHaveBeenCalledWith("Alpha");+ firstBar.focus();+ await userEvent.keyboard("{Enter}");+ await expect(copy).toHaveBeenCalledTimes(2);+ } finally {+ copy.mockRestore();+ }+ await expect(+ tooltip.querySelector("svg.lucide-check")?.parentElement,+ ).toHaveClass("visible");await expect(firstBar).toHaveAttribute("fill", "hsl(var(--chart-1))");await expect(canvas.getByRole("graphics-symbol", { name: "Beta: 24" }),@@ -57,6 +72,34 @@ export const KeyboardFocus = meta.story({},});+export const CategoryHoverArea = meta.story({+ name: "(Test) Category Hover Area",+ play: async ({ canvasElement }) => {+ const area = canvasElement.querySelector<SVGRectElement>(+ "[data-bar-hover-area]",+ );+ const bar = within(canvasElement).getByRole("graphics-symbol", {+ name: "Alpha: 12",+ });+ if (!area) throw new Error("Hover area not found");+ await expect(Number(area.getAttribute("height"))).toBeGreaterThan(+ Number(bar.getAttribute("height")),+ );+ await userEvent.hover(area);+ const tooltip = await within(canvasElement.ownerDocument.body).findByRole(+ "tooltip",+ );+ await expect(tooltip).toHaveTextContent("Alpha");+ const copy = spyOn(navigator.clipboard, "writeText").mockResolvedValue();+ try {+ await userEvent.click(area);+ await expect(copy).toHaveBeenCalledWith("Alpha");+ } finally {+ copy.mockRestore();+ }+ },+});+export const CategoryColors = meta.story({args: {data: data.map((item, index) => ({diff --git a/web/src/components/design-system/charts/ChartTooltip.stories.tsx b/web/src/components/design-system/charts/ChartTooltip.stories.tsxindex b3efb03475..1f76714255 100644--- a/web/src/components/design-system/charts/ChartTooltip.stories.tsx+++ b/web/src/components/design-system/charts/ChartTooltip.stories.tsx@@ -1,6 +1,6 @@import { type ComponentProps } from "react";import preview from "../../../../.storybook/preview";-import { expect, userEvent, within } from "storybook/test";+import { expect, spyOn, userEvent, within } from "storybook/test";import { ChartTooltip } from "../internal/charts/ChartTooltip";@@ -152,6 +152,9 @@ export const Primary = meta.story({const tooltip = await focusTooltip(canvasElement);await expect(tooltip).toHaveTextContent("Claude Sonnet");await expect(tooltip).toHaveTextContent("31 (31%)");+ await expect(within(tooltip).getByText("Claude Sonnet")).toHaveClass(+ "text-foreground",+ );},});@@ -180,6 +183,52 @@ export const PrimaryWithDetails = meta.story({},});+export const WithCopyHint = meta.story({+ name: "(Test) With Copy Hint",+ args: {+ data: {+ type: "primary",+ index: 0,+ label: "Alpha",+ value: "12",+ copyLabel: "Alpha",+ hint: "Click or press Enter to copy label",+ },+ },+ play: async ({ canvasElement }) => {+ const tooltip = await focusTooltip(canvasElement);+ const hint = within(tooltip).getByText(+ "Click or press Enter to copy label",+ );+ await expect(hint).toBeVisible();+ await expect(hint.parentElement).toHaveClass(+ "border-t",+ "text-muted-foreground/70",+ );+ await expect(+ Number.parseFloat(getComputedStyle(hint).fontSize),+ ).toBeLessThan(Number.parseFloat(getComputedStyle(tooltip).fontSize));+ const widthBeforeCopy = tooltip.getBoundingClientRect().width;+ const copy = spyOn(navigator.clipboard, "writeText").mockResolvedValue();+ try {+ await userEvent.click(+ within(canvasElement).getByLabelText("Tooltip trigger"),+ );+ await expect(copy).toHaveBeenCalledWith("Alpha");+ await expect(hint).not.toBeVisible();+ await expect(+ within(tooltip).getByText("Label copied to clipboard"),+ ).toBeVisible();+ await expect(tooltip.getBoundingClientRect().width).toBeCloseTo(+ widthBeforeCopy,+ 0,+ );+ } finally {+ copy.mockRestore();+ }+ },+});+export const LongContent = meta.story({name: "(Test) Long Content",args: {diff --git a/web/src/components/design-system/charts/HorizontalBarChart/HorizontalBarChart.stories.tsx b/web/src/components/design-system/charts/HorizontalBarChart/HorizontalBarChart.stories.tsxnew file mode 100644index 0000000000..2d5fac743f--- /dev/null+++ b/web/src/components/design-system/charts/HorizontalBarChart/HorizontalBarChart.stories.tsx@@ -0,0 +1,332 @@+import preview from "../../../../../.storybook/preview";+import { expect, spyOn, userEvent, waitFor, within } from "storybook/test";++import { HorizontalBarChart } from "./HorizontalBarChart";++const meta = preview.meta({+ component: HorizontalBarChart,+ parameters: { layout: "fullscreen" },+ args: {+ data: [+ { label: "Alpha", value: 12 },+ { label: "Beta", value: -24 },+ { label: "Gamma", value: 6 },+ ],+ },+ decorators: [+ (Story) => (+ <div className="h-dvh w-full">+ <Story />+ </div>+ ),+ ],+});++export const Default = meta.story({});++export const FillsAvailableHeight = meta.story({+ name: "(Test) Fills Available Height",+ play: async ({ canvasElement }) => {+ const bars =+ canvasElement.querySelectorAll<SVGRectElement>("[data-bar-fill]");+ const svg = canvasElement.querySelector(+ "svg[aria-label='Horizontal bar chart']",+ );+ const first = bars[0];+ const last = bars[bars.length - 1];+ if (!first || !last || !svg) throw new Error("Chart bars not found");+ await expect(first.getAttribute("height")).toBe(+ last.getAttribute("height"),+ );+ const topGap = Number(first.getAttribute("y")) - 26;+ const bottomGap =+ Number(svg.getAttribute("height")) -+ 12 -+ Number(last.getAttribute("y")) -+ Number(last.getAttribute("height"));+ await expect(topGap).toBeGreaterThan(1);+ await expect(bottomGap).toBeCloseTo(topGap, 0);+ if (Number(svg.getAttribute("height")) >= 600) {+ await expect(topGap).toBeGreaterThan(12);+ }+ },+});++export const LayoutAndCopy = meta.story({+ name: "(Test) Layout and Copy",+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);+ const bars =+ canvasElement.querySelectorAll<SVGRectElement>("[data-bar-fill]");+ const widths = Array.from(bars, (bar) => Number(bar.getAttribute("width")));+ await expect(widths[0]).toBeCloseTo((widths[1] ?? 0) / 2);+ await expect(widths[2]).toBeCloseTo((widths[1] ?? 0) / 4);+ const rightTick = canvasElement.querySelector<SVGLineElement>(+ "[data-axis-tick]:last-child line",+ );+ const plotRight = Number(rightTick?.getAttribute("x1"));+ await expect(plotRight).toBeGreaterThan(+ Number(bars[1]?.getAttribute("width")),+ );+ const values = canvasElement.querySelectorAll<SVGTextElement>(+ 'text[text-anchor="end"]',+ );+ await expect(values[0]?.getAttribute("x")).toBe(+ values[1]?.getAttribute("x"),+ );++ const bar = canvas.getByRole("graphics-symbol", { name: "Beta: -24" });+ const hoverArea = bar.parentElement?.querySelector<SVGRectElement>(+ "rect[fill='transparent'][aria-hidden='true']",+ );+ if (!hoverArea) throw new Error("Row hover area not found");+ await expect(Number(hoverArea.getAttribute("width"))).toBeGreaterThan(+ Number(bar.getAttribute("width")),+ );+ await userEvent.hover(hoverArea);+ const hoveredTooltip = await within(+ canvasElement.ownerDocument.body,+ ).findByRole("tooltip");+ await expect(hoveredTooltip).toHaveTextContent("Beta");+ bar.focus();+ const tooltip = await within(canvasElement.ownerDocument.body).findByRole(+ "tooltip",+ );+ await expect(tooltip).toHaveTextContent("Beta");+ await expect(tooltip).toHaveTextContent(+ "Click or press Enter to copy label",+ );+ await expect(+ tooltip.querySelector("svg.lucide-check")?.parentElement,+ ).toHaveClass("invisible");+ await expect(bars[0]).toHaveAttribute(+ "fill",+ expect.stringContaining("20%"),+ );++ const copy = spyOn(navigator.clipboard, "writeText").mockResolvedValue();+ try {+ await userEvent.click(bar);+ await expect(copy).toHaveBeenCalledWith("Beta");+ await expect(+ within(tooltip).getByText("Label copied to clipboard"),+ ).toBeVisible();+ bar.focus();+ await userEvent.keyboard("{Enter}");+ await expect(copy).toHaveBeenCalledTimes(2);+ await userEvent.click(hoverArea);+ await expect(copy).toHaveBeenCalledTimes(3);+ } finally {+ copy.mockRestore();+ }+ },+});++export const CategoryColors = meta.story({+ name: "(Test) Category Colors",+ args: {+ data: [+ { label: "Alpha", value: 12, color: "#3a3dee" },+ { label: "Beta", value: 24, color: "#07b9d5" },+ ],+ },+ play: async ({ canvasElement }) => {+ within(canvasElement)+ .getByRole("graphics-symbol", { name: "Beta: 24" })+ .focus();+ const tooltip = await within(canvasElement.ownerDocument.body).findByRole(+ "tooltip",+ );+ await expect(tooltip.querySelector("svg rect")).toHaveAttribute(+ "fill",+ "#07b9d5",+ );+ },+});++export const NarrowWithLongValues = meta.story({+ name: "(Test) Narrow With Long Values",+ args: {+ data: [+ { label: "Maximum", value: 1234567 },+ { label: "Small", value: 12345 },+ { label: "Nothing", value: 0 },+ ],+ valueFormatter: (value: number) => `${value.toLocaleString()} units`,+ },+ decorators: [+ (Story) => (+ <div className="h-40 w-[320px]">+ <Story />+ </div>+ ),+ ],+ play: async ({ canvasElement }) => {+ const ticks = Array.from(+ canvasElement.querySelectorAll<SVGTextElement>("[data-axis-tick] text"),+ );+ await expect(ticks.length).toBeGreaterThan(1);+ for (let index = 1; index < ticks.length; index++) {+ const previous = ticks[index - 1];+ const current = ticks[index];+ if (!previous || !current) throw new Error("Axis tick not found");+ await expect(current.getBoundingClientRect().left).toBeGreaterThanOrEqual(+ previous.getBoundingClientRect().right,+ );+ }+ const value = within(canvasElement).getByText("1,234,567 units");+ await expect(value.getBoundingClientRect().right).toBeLessThanOrEqual(+ canvasElement.getBoundingClientRect().right,+ );+ },+});++export const ZeroNegativeAndMissing = meta.story({+ name: "(Test) Zero, Negative and Missing",+ args: {+ data: [+ { label: "Positive", value: 8 },+ { label: "Negative", value: -4 },+ { label: "Zero", value: 0 },+ { label: "Missing", value: null },+ ],+ },+ play: async ({ canvasElement }) => {+ const fills =+ canvasElement.querySelectorAll<SVGRectElement>("[data-bar-fill]");+ await expect(Number(fills[1]?.getAttribute("width"))).toBeCloseTo(+ Number(fills[0]?.getAttribute("width")) / 2,+ );+ await expect(fills[2]).toHaveAttribute("width", "0");+ const zero = within(canvasElement).getByRole("graphics-symbol", {+ name: "Zero: 0",+ });+ await expect(Number(zero.getAttribute("width"))).toBeGreaterThanOrEqual(24);+ within(canvasElement)+ .getByRole("graphics-symbol", { name: "Missing: 0" })+ .focus();+ const tooltip = await within(canvasElement.ownerDocument.body).findByRole(+ "tooltip",+ );+ await expect(tooltip).toHaveTextContent("Missing");+ },+});++export const LongAndDuplicateLabels = meta.story({+ name: "(Test) Long and Duplicate Labels",+ args: {+ data: [+ { label: "production-evaluation-run-with-a-very-long-name", value: 10 },+ { label: "Repeated label", value: 7 },+ { label: "Repeated label", value: 3 },+ ],+ },+ decorators: [+ (Story) => (+ <div className="h-40 w-[280px]">+ <Story />+ </div>+ ),+ ],+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);+ await expect(+ canvas.getAllByRole("graphics-symbol", { name: /Repeated label:/ }),+ ).toHaveLength(2);+ canvas+ .getByRole("graphics-symbol", {+ name: "production-evaluation-run-with-a-very-long-name: 10",+ })+ .focus();+ const tooltip = await within(canvasElement.ownerDocument.body).findByRole(+ "tooltip",+ );+ await expect(tooltip).toHaveTextContent(+ "production-evaluation-run-with-a-very-long-name",+ );+ },+});++export const TinyBarsBesideOutlier = meta.story({+ name: "(Test) Tiny Bars Beside Outlier",+ args: {+ data: [+ { label: "n/a", value: 101.21 },+ ...Array.from({ length: 19 }, (_, index) => ({+ label: `User ${index + 1}`,+ value: 0.31 - index * 0.004,+ })),+ ],+ valueFormatter: (value: number) => `$${value.toFixed(value < 1 ? 6 : 2)}`,+ },+ decorators: [+ (Story) => (+ <div className="h-[600px] w-[440px]">+ <Story />+ </div>+ ),+ ],+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);+ const small = canvas.getByRole("graphics-symbol", {+ name: "User 1: $0.310000",+ });+ const row = small.parentElement;+ if (!row) throw new Error("Bar row not found");+ const bar = row.querySelector<SVGRectElement>("[data-bar-fill]");+ const label = within(row).getByText("User 1");+ const value = within(row).getByText("$0.310000");+ const leader = row.querySelector<SVGLineElement>("[data-leader-line]");+ if (!bar || !leader) throw new Error("Bar or leader not found");+ await expect(label.getBoundingClientRect().left).toBeGreaterThanOrEqual(+ bar.getBoundingClientRect().right,+ );+ await expect(leader.getBoundingClientRect().left).toBeGreaterThanOrEqual(+ label.getBoundingClientRect().right,+ );+ await expect(leader.getBoundingClientRect().right).toBeLessThanOrEqual(+ value.getBoundingClientRect().left,+ );+ const large = canvas.getByRole("graphics-symbol", { name: "n/a: $101.21" });+ large.focus();+ await waitFor(() => {+ expect(label).toHaveAttribute("fill", expect.stringContaining("40%"));+ expect(value).toHaveAttribute("fill", expect.stringContaining("40%"));+ });+ },+});++export const ManyRows = meta.story({+ name: "(Test) Many Rows",+ args: {+ data: Array.from({ length: 30 }, (_, index) => ({+ label: `Category ${index + 1}`,+ value: 30 - index,+ })),+ },+ decorators: [+ (Story) => (+ <div className="h-40 w-[360px]">+ <Story />+ </div>+ ),+ ],+ play: async ({ canvasElement }) => {+ const chart = canvasElement.querySelector<HTMLElement>(+ "[data-testid='top-list-chart']",+ );+ if (!chart) throw new Error("Chart not found");+ await expect(chart.scrollHeight).toBeGreaterThan(chart.clientHeight);+ const lastBar = within(canvasElement).getByRole("graphics-symbol", {+ name: "Category 30: 1",+ });+ await expect(Number(lastBar.getAttribute("height"))).toBeCloseTo(14, 0);+ lastBar.focus();+ const tooltip = await within(canvasElement.ownerDocument.body).findByRole(+ "tooltip",+ );+ await expect(tooltip).toHaveTextContent("Category 30");+ },+});++export const Empty = meta.story({ args: { data: [] } });diff --git a/web/src/components/design-system/charts/HorizontalBarChart/HorizontalBarChart.tsx b/web/src/components/design-system/charts/HorizontalBarChart/HorizontalBarChart.tsxnew file mode 100644index 0000000000..a884efc93a--- /dev/null+++ b/web/src/components/design-system/charts/HorizontalBarChart/HorizontalBarChart.tsx@@ -0,0 +1,267 @@+"use client";++import { scaleLinear } from "d3-scale";++import { ChartContainer } from "@/src/components/design-system/charts/ChartContainer";+import type { BarChartDatum } from "@/src/components/design-system/internal/charts/BarChartCore";+import { CARTESIAN_CHART_INSETS } from "@/src/components/design-system/internal/charts/CartesianLayout";+import { ChartTooltip } from "@/src/components/design-system/internal/charts/ChartTooltip";++const MIN_ROW_PX = 14;+const CHARACTER_WIDTH = 7;++export function HorizontalBarChart({+ data,+ valueFormatter = (value) => value.toLocaleString(),+ color = "hsl(var(--chart-1))",+}: {+ data: BarChartDatum[];+ valueFormatter?: (value: number) => string;+ color?: string;+}) {+ const maxMagnitude = Math.max(+ ...data.map((datum) => Math.abs(datum.value ?? 0)),+ 0,+ );+ const scale = scaleLinear()+ .domain([0, maxMagnitude || 1])+ .nice(4);+ const rightTick = scale.domain()[1] ?? 1;+ const ticks = scale.ticks(4);+ if (ticks.at(-1) !== rightTick) ticks.push(rightTick);+ const firstColor = data[0]?.color ?? color;+ const hasDistinctColors = data.some(+ (datum) => (datum.color ?? color) !== firstColor,+ );++ return (+ <ChartContainer>+ {({ width, height }) => {+ const left = CARTESIAN_CHART_INSETS.top;+ const top = CARTESIAN_CHART_INSETS.bottomWithLabels;+ const right = CARTESIAN_CHART_INSETS.right;+ const bottom = CARTESIAN_CHART_INSETS.bottomWithoutLabels;+ const valueChars = Math.max(+ 2,+ ...data.map((datum) => valueFormatter(datum.value ?? 0).length),+ );+ const plotWidth = Math.max(+ 0,+ width - left - right - valueChars * CHARACTER_WIDTH - 8,+ );+ const plotHeight = Math.max(0, height - top - bottom);+ const gap = Math.min(+ 32,+ Math.max(1, (plotHeight / Math.max(1, data.length)) * 0.12),+ );+ const rowHeight = Math.max(+ MIN_ROW_PX,+ (plotHeight - gap * (data.length + 1)) / Math.max(1, data.length),+ );+ const contentHeight = Math.max(+ height,+ top + bottom + data.length * rowHeight + gap * (data.length + 1),+ );+ const valueRight = width - right;+ const rightTickLeft =+ plotWidth - (valueFormatter(rightTick).length * CHARACTER_WIDTH) / 2;+ let previousTickEnd = -Infinity;+ const visibleTicks = ticks.filter((tick, index) => {+ if (tick === rightTick) return true;+ const labelWidth = valueFormatter(tick).length * CHARACTER_WIDTH;+ const tickLeft =+ index === 0 ? 0 : scale(tick) * plotWidth - labelWidth / 2;+ if (+ tickLeft < previousTickEnd + 8 ||+ tickLeft + labelWidth + 8 > rightTickLeft+ ) {+ return false;+ }+ previousTickEnd = tickLeft + labelWidth;+ return true;+ });++ return (+ <ChartTooltip>+ {({ activeIndex, getReferenceProps }) => (+ <div+ className="size-full overflow-x-hidden overflow-y-auto"+ data-testid="top-list-chart"+ >+ <svg+ width={width}+ height={contentHeight}+ role="group"+ aria-label="Horizontal bar chart"+ className="block"+ >+ <g aria-hidden="true">+ {visibleTicks.map((tick) => {+ const x = left + scale(tick) * plotWidth;+ return (+ <g key={tick} data-axis-tick="">+ <line+ x1={x}+ x2={x}+ y1={top}+ y2={contentHeight - bottom}+ stroke="hsl(var(--chart-grid))"+ />+ <text+ x={x}+ y={top - 8}+ textAnchor={tick === 0 ? "start" : "middle"}+ fill="hsl(var(--muted-foreground))"+ fontSize={12}+ >+ {valueFormatter(tick)}+ </text>+ </g>+ );+ })}+ </g>+ {data.map((datum, index) => {+ const value = datum.value ?? 0;+ const formattedValue = valueFormatter(value);+ const barWidth =+ maxMagnitude > 0 ? scale(Math.abs(value)) * plotWidth : 0;+ const y = top + gap + index * (rowHeight + gap);+ const outsideLabelWidth = Math.min(+ datum.label.length * CHARACTER_WIDTH + 8,+ Math.max(0, plotWidth - barWidth - 16),+ );+ const labelOutside =+ barWidth < datum.label.length * CHARACTER_WIDTH + 16 &&+ outsideLabelWidth >= 16;+ const labelRoom = labelOutside+ ? outsideLabelWidth - 8+ : Math.max(0, barWidth - 16);+ const maxCharacters = Math.floor(+ labelRoom / CHARACTER_WIDTH,+ );+ let visibleLabel = datum.label;+ if (maxCharacters < 1) visibleLabel = "";+ else if (datum.label.length > maxCharacters) {+ visibleLabel = `${datum.label.slice(0, Math.max(0, maxCharacters - 1))}…`;+ }+ const labelX = left + barWidth + 8;+ const leaderStart = labelOutside+ ? labelX + outsideLabelWidth + 8+ : labelX;+ const leaderEnd =+ valueRight - formattedValue.length * CHARACTER_WIDTH - 8;+ const inactive =+ activeIndex !== undefined && activeIndex !== index;+ const inactiveTextColor = inactive+ ? "color-mix(in srgb, hsl(var(--foreground)) 40%, hsl(var(--background)))"+ : "hsl(var(--foreground))";+ const tooltipData = {+ type: "primary" as const,+ index,+ label: datum.label,+ value: formattedValue,+ color: hasDistinctColors+ ? (datum.color ?? color)+ : undefined,+ hint: "Click or press Enter to copy label",+ copyLabel: datum.label,+ };+ const { onPointerLeave, ...referenceProps } =+ getReferenceProps(tooltipData);++ return (+ <g+ key={`${datum.label}-${index}`}+ onPointerLeave={onPointerLeave}+ >+ <rect+ x={left}+ y={y}+ width={Math.max(0, width - left - right)}+ height={rowHeight}+ fill="transparent"+ aria-hidden="true"+ {...referenceProps}+ />+ <rect+ data-bar-fill=""+ x={left}+ y={y}+ width={barWidth}+ height={rowHeight}+ rx={Math.min(4, rowHeight / 2)}+ fill={+ inactive+ ? `color-mix(in srgb, ${datum.color ?? color} 20%, hsl(var(--background)))`+ : (datum.color ?? color)+ }+ pointerEvents="none"+ aria-hidden="true"+ />+ <rect+ x={left}+ y={y}+ width={Math.min(plotWidth, Math.max(24, barWidth))}+ height={rowHeight}+ fill="transparent"+ role="graphics-symbol"+ tabIndex={0}+ aria-label={`${datum.label}: ${formattedValue}`}+ className="outline-hidden focus-visible:outline-2 focus-visible:outline-offset-2"+ {...getReferenceProps(tooltipData)}+ onPointerLeave={undefined}+ />+ <text+ x={labelOutside ? labelX : left + 8}+ y={y + rowHeight / 2}+ dominantBaseline="middle"+ fontSize={12}+ fill={+ labelOutside || inactive+ ? inactiveTextColor+ : undefined+ }+ className={+ labelOutside || inactive+ ? "pointer-events-none"+ : "pointer-events-none fill-white dark:fill-black"+ }+ >+ {visibleLabel}+ </text>+ {leaderEnd - leaderStart > 24 ? (+ <line+ data-leader-line=""+ x1={leaderStart}+ x2={leaderEnd}+ y1={y + rowHeight / 2}+ y2={y + rowHeight / 2}+ stroke="hsl(var(--muted-foreground))"+ strokeOpacity={inactive ? 0.2 : 0.4}+ strokeDasharray="3 3"+ aria-hidden="true"+ />+ ) : null}+ <text+ x={valueRight}+ y={y + rowHeight / 2}+ textAnchor="end"+ dominantBaseline="middle"+ fontSize={12}+ fill={inactiveTextColor}+ {...referenceProps}+ >+ {formattedValue}+ </text>+ </g>+ );+ })}+ </svg>+ </div>+ )}+ </ChartTooltip>+ );+ }}+ </ChartContainer>+ );+}diff --git a/web/src/components/design-system/charts/PieChart/PieChart.stories.tsx b/web/src/components/design-system/charts/PieChart/PieChart.stories.tsxindex 2f7f76a084..8ce5bb7701 100644--- a/web/src/components/design-system/charts/PieChart/PieChart.stories.tsx+++ b/web/src/components/design-system/charts/PieChart/PieChart.stories.tsx@@ -1,5 +1,5 @@import preview from "../../../../../.storybook/preview";-import { expect, within } from "storybook/test";+import { expect, spyOn, userEvent, within } from "storybook/test";import { PieChart } from "./PieChart";const data = [@@ -60,6 +60,19 @@ export const KeyboardFocus = meta.story({);await expect(tooltip).toHaveTextContent("Claude Sonnet");await expect(tooltip).toHaveTextContent("31");+ await expect(tooltip).toHaveTextContent(+ "Click or press Enter to copy label",+ );+ const copy = spyOn(navigator.clipboard, "writeText").mockResolvedValue();+ try {+ await userEvent.click(slice);+ await expect(copy).toHaveBeenCalledWith("Claude Sonnet");+ slice.focus();+ await userEvent.keyboard("{Enter}");+ await expect(copy).toHaveBeenCalledTimes(2);+ } finally {+ copy.mockRestore();+ }},});diff --git a/web/src/components/design-system/charts/PieChart/PieChart.tsx b/web/src/components/design-system/charts/PieChart/PieChart.tsxindex 1653efa634..8587d40f09 100644--- a/web/src/components/design-system/charts/PieChart/PieChart.tsx+++ b/web/src/components/design-system/charts/PieChart/PieChart.tsx@@ -192,6 +192,8 @@ function PieChartContent({label: slice.data.label,value: `${valueFormatter(slice.data.value)} (${percentageFormatter.format(slice.data.value / totalValue)})`,color,+ copyLabel: slice.data.label,+ hint: "Click or press Enter to copy label",details: slice.data.details?.map((datum) => ({label: datum.label,value: `${valueFormatter(datum.value)} (${percentageFormatter.format(datum.value / totalValue)})`,diff --git a/web/src/components/design-system/internal/charts/BarChartCore.tsx b/web/src/components/design-system/internal/charts/BarChartCore.tsxindex 4dd6daa5b8..744396d20f 100644--- a/web/src/components/design-system/internal/charts/BarChartCore.tsx+++ b/web/src/components/design-system/internal/charts/BarChartCore.tsx@@ -175,38 +175,68 @@ export function BarChartCore({colorStrength === 100? barColor: `color-mix(in srgb, ${barColor} ${colorStrength}%, hsl(var(--background)))`;+ const previousX = xScale(index - 1);+ const nextX = xScale(index + 1);+ const centerX = x + xScale.bandwidth() / 2;+ const hoverLeft =+ previousX === undefined+ ? plot.left+ : (previousX + xScale.bandwidth() / 2 + centerX) /+ 2;+ const hoverRight =+ nextX === undefined+ ? plot.left + plot.width+ : (centerX + nextX + xScale.bandwidth() / 2) / 2;+ const tooltipData = {+ type: "primary" as const,+ index,+ label: tooltipValueLabel ?? datum.label,+ value: valueFormatter(datum.value ?? 0),+ heading: tooltipHeading?.(datum.label),+ color: hasDistinctColors ? barColor : undefined,+ hint: "Click or press Enter to copy label",+ copyLabel: datum.label,+ };+ const { onPointerLeave, ...referenceProps } =+ getReferenceProps(tooltipData);return (- <g key={index}>+ <g key={index} onPointerLeave={onPointerLeave}>{datum.value !== null &&Number.isFinite(datum.value) ? (- <rect- x={x + histogramInset}- y={barTop}- width={- xScale.bandwidth() - histogramInset * 2- }- height={Math.max(1, barHeight)}- rx={- barSpacing === "histogram"- ? 0- : 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: tooltipValueLabel ?? datum.label,- value: valueFormatter(datum.value),- heading: tooltipHeading?.(datum.label),- color: hasDistinctColors- ? barColor- : undefined,- })}- />+ <>+ {barSpacing === "default" ? (+ <rect+ data-bar-hover-area=""+ x={hoverLeft}+ y={plot.top}+ width={hoverRight - hoverLeft}+ height={plot.height}+ fill="transparent"+ aria-hidden="true"+ {...referenceProps}+ />+ ) : null}+ <rect+ x={x + histogramInset}+ y={barTop}+ width={+ xScale.bandwidth() - histogramInset * 2+ }+ height={Math.max(1, barHeight)}+ rx={+ barSpacing === "histogram"+ ? 0+ : 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(tooltipData)}+ onPointerLeave={undefined}+ />+ </>) : null}</g>);diff --git a/web/src/components/design-system/internal/charts/CartesianLayout.tsx b/web/src/components/design-system/internal/charts/CartesianLayout.tsxindex c9e4c2e30e..6eabb2caab 100644--- a/web/src/components/design-system/internal/charts/CartesianLayout.tsx+++ b/web/src/components/design-system/internal/charts/CartesianLayout.tsx@@ -1,17 +1,23 @@import type { ReactNode } from "react";-const TOP = 10;-const RIGHT = 16;-const BOTTOM_WITH_LABELS = 26;-const BOTTOM_WITHOUT_LABELS = 12;+export const CARTESIAN_CHART_INSETS = {+ top: 10,+ right: 16,+ bottomWithLabels: 26,+ bottomWithoutLabels: 12,+ minLeft: 64,+};+const Y_TICK_HEIGHT = 28;function getCartesianPlotHeight(height: number, showXAxisLabels: boolean) {return Math.max(0,height -- TOP -- (showXAxisLabels ? BOTTOM_WITH_LABELS : BOTTOM_WITHOUT_LABELS),+ CARTESIAN_CHART_INSETS.top -+ (showXAxisLabels+ ? CARTESIAN_CHART_INSETS.bottomWithLabels+ : CARTESIAN_CHART_INSETS.bottomWithoutLabels),);}@@ -31,13 +37,13 @@ function getCartesianLayout({yTickLabels: string[];}) {const left = Math.max(- 64,+ CARTESIAN_CHART_INSETS.minLeft,...yTickLabels.map((label) => label.length * 7 + 16),);return {left,- top: TOP,- width: Math.max(0, width - left - RIGHT),+ top: CARTESIAN_CHART_INSETS.top,+ width: Math.max(0, width - left - CARTESIAN_CHART_INSETS.right),height: getCartesianPlotHeight(height, showXAxisLabels),};}diff --git a/web/src/components/design-system/internal/charts/ChartTooltip.tsx b/web/src/components/design-system/internal/charts/ChartTooltip.tsxindex 7455dec8aa..2c4bec16cf 100644--- a/web/src/components/design-system/internal/charts/ChartTooltip.tsx+++ b/web/src/components/design-system/internal/charts/ChartTooltip.tsx@@ -9,16 +9,21 @@ import {useClientPoint,useFloating,} from "@floating-ui/react";+import { Check } from "lucide-react";import {Fragment,+ useEffect,useLayoutEffect,+ useRef,useState,type FocusEvent,+ type KeyboardEvent,type PointerEvent,type ReactNode,} from "react";import { useLayerContainer } from "@/src/context/LayerContext/LayerContext";+import { copyTextToClipboard } from "@/src/utils/clipboard";type TooltipItem = {label: string;@@ -29,6 +34,8 @@ type TooltipItem = {type TooltipData = {index: number;heading?: string;+ hint?: string;+ copyLabel?: string;focusPoint?: { x: number; y: number };} & (| {@@ -57,21 +64,47 @@ export function ChartTooltip({children: (controller: {activeIndex: number | undefined;getReferenceProps: (data: TooltipData) => {- onPointerEnter: (event: PointerEvent<SVGElement>) => void;- onPointerMove: (event: PointerEvent<SVGElement>) => void;+ onPointerEnter: (event: PointerEvent<SVGElement | HTMLElement>) => void;+ onPointerMove: (event: PointerEvent<SVGElement | HTMLElement>) => void;onPointerLeave: () => void;- onFocus: (event: FocusEvent<SVGElement>) => void;+ onFocus: (event: FocusEvent<SVGElement | HTMLElement>) => void;onBlur: () => void;+ onClick: (() => Promise<void>) | undefined;+ onKeyDown:+ | ((event: KeyboardEvent<SVGElement | HTMLElement>) => Promise<void>)+ | undefined;};}) => ReactNode;}) {const [activeTooltip, setActiveTooltip] = useState<TooltipData & {- reference: SVGElement;+ reference: SVGElement | HTMLElement;clientPoint?: { x: number; y: number };placement: "left" | "right";}>();+ const [copyFeedback, setCopyFeedback] = useState<{+ index: number;+ status: "copied" | "error";+ }>();+ const feedbackTimeout = useRef<ReturnType<typeof setTimeout>>(undefined);++ useEffect(() => () => clearTimeout(feedbackTimeout.current), []);++ const copyLabel = async (index: number, label: string) => {+ try {+ await copyTextToClipboard(label);+ setCopyFeedback({ index, status: "copied" });+ } catch (error) {+ console.error("Unable to copy to clipboard", error);+ setCopyFeedback({ index, status: "error" });+ }+ clearTimeout(feedbackTimeout.current);+ feedbackTimeout.current = setTimeout(+ () => setCopyFeedback(undefined),+ 1500,+ );+ };useLayoutEffect(() => {if (activeTooltip && !activeTooltip.reference.isConnected) {@@ -95,10 +128,13 @@ export function ChartTooltip({});const getReferenceProps = (data: TooltipData) => {- const showAtPointer = (event: PointerEvent<SVGElement>) => {+ const labelToCopy = data.copyLabel;+ const showAtPointer = (event: PointerEvent<SVGElement | HTMLElement>) => {const { clientX, clientY, currentTarget } = event;const chartBounds =- currentTarget.ownerSVGElement?.getBoundingClientRect();+ currentTarget instanceof SVGElement+ ? currentTarget.ownerSVGElement?.getBoundingClientRect()+ : currentTarget.parentElement?.getBoundingClientRect();setActiveTooltip({...data,reference: currentTarget,@@ -114,10 +150,15 @@ export function ChartTooltip({onPointerEnter: showAtPointer,onPointerMove: showAtPointer,onPointerLeave: () => setActiveTooltip(undefined),- onFocus: (event: FocusEvent<SVGElement>) => {+ onFocus: (event: FocusEvent<SVGElement | HTMLElement>) => {const sliceBounds = event.currentTarget.getBoundingClientRect();- const svg = event.currentTarget.ownerSVGElement;- const chartBounds = svg?.getBoundingClientRect();+ const svg =+ event.currentTarget instanceof SVGElement+ ? event.currentTarget.ownerSVGElement+ : undefined;+ const chartBounds =+ svg?.getBoundingClientRect() ??+ event.currentTarget.parentElement?.getBoundingClientRect();const focusPoint = svg?.createSVGPoint();if (focusPoint && data.focusPoint) {focusPoint.x = data.focusPoint.x;@@ -143,6 +184,19 @@ export function ChartTooltip({});},onBlur: () => setActiveTooltip(undefined),+ onClick:+ labelToCopy === undefined+ ? undefined+ : async () => copyLabel(data.index, labelToCopy),+ onKeyDown:+ labelToCopy === undefined+ ? undefined+ : async (event: KeyboardEvent<SVGElement | HTMLElement>) => {+ if (event.currentTarget instanceof HTMLElement) return;+ if (event.key !== "Enter" && event.key !== " ") return;+ event.preventDefault();+ await copyLabel(data.index, labelToCopy);+ },};};@@ -181,9 +235,17 @@ export function ChartTooltip({);}+ const activeCopyStatus =+ copyFeedback?.index === activeTooltip?.index+ ? copyFeedback?.status+ : undefined;+return (<>- {children({ activeIndex: activeTooltip?.index, getReferenceProps })}+ {children({+ activeIndex: activeTooltip?.index,+ getReferenceProps,+ })}{activeTooltip ? (<FloatingPortal root={layerContainer}><div@@ -220,7 +282,7 @@ export function ChartTooltip({) : 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`}+ className={`${item.kind === "primary" || item.emphasis === "emphasized" ? "text-foreground" : "text-muted-foreground"} truncate`}title={item.label}>{item.label}@@ -234,6 +296,29 @@ export function ChartTooltip({</div></Fragment>))}+ {activeTooltip.hint ? (+ <div+ className="border-border/50 text-muted-foreground/70 grid border-t pt-1.5 text-[10px]"+ role="status"+ >+ <span+ className={`[grid-area:1/1] ${activeCopyStatus ? "invisible" : "visible"}`}+ >+ {activeTooltip.hint}+ </span>+ <span+ className={`flex items-center gap-1 [grid-area:1/1] ${activeCopyStatus === "copied" ? "visible" : "invisible"}`}+ >+ Label copied to clipboard{" "}+ <Check className="size-3" aria-hidden="true" />+ </span>+ <span+ className={`[grid-area:1/1] ${activeCopyStatus === "error" ? "visible" : "invisible"}`}+ >+ Could not copy label+ </span>+ </div>+ ) : null}</div></FloatingPortal>) : null}diff --git a/web/src/features/widgets/chart-library/Chart.tsx b/web/src/features/widgets/chart-library/Chart.tsxindex 3e3501bb6e..d20870b0b6 100644--- a/web/src/features/widgets/chart-library/Chart.tsx+++ b/web/src/features/widgets/chart-library/Chart.tsx@@ -236,7 +236,6 @@ const ChartComponent = ({data={renderedData.slice(0, rowLimit)}config={resolvedConfig}metricFormatter={metricFormatter}- subtleFill={chartConfig?.subtle_fill}/>);case "VERTICAL_BAR":diff --git a/web/src/features/widgets/chart-library/TopListChart.tsx b/web/src/features/widgets/chart-library/TopListChart.tsxindex 8888eab8c2..9f8642e9a2 100644--- a/web/src/features/widgets/chart-library/TopListChart.tsx+++ b/web/src/features/widgets/chart-library/TopListChart.tsx@@ -1,144 +1,26 @@-import React, { useCallback, useMemo, useState } from "react";-import { Check, Copy } from "lucide-react";-import { copyTextToClipboard } from "@/src/utils/clipboard";+import { HorizontalBarChart } from "@/src/components/design-system/charts/HorizontalBarChart/HorizontalBarChart";import { type ChartProps } from "@/src/features/widgets/chart-library/chart-props";import {formatMetric,toFullMetricString,} from "@/src/features/widgets/chart-library/utils";-// Row rhythm: rows lay out top-aligned at up to MAX_ROW_PX each, shrink evenly-// down to MIN_ROW_PX when the tile is tight, and scroll below that. Done with-// flex-basis/min-height only, so the component never measures its container-// (charts must stay a pure function of their box — see BarListChartArea).-const MAX_ROW_PX = 56;-const MIN_ROW_PX = 20;-const ROW_GAP_PX = 1;-// Label/value text steps through the type scale with the row height (each-// row is a size container): text-xs by default, text-sm from 36px rows,-// text-base from 48px — never anything off-scale, capped at base.-const ROW_TEXT_STEPS =- "text-xs [@container(min-height:36px)]:text-sm [@container(min-height:48px)]:text-base";--const CopyDimensionButton: React.FC<{ value: string }> = ({ value }) => {- const [copied, setCopied] = useState(false);- return (- <button- type="button"- aria-label={`Copy "${value}"`}- title={`Copy "${value}"`}- className="text-muted-foreground hover:bg-background/60 hover:text-foreground pointer-events-auto shrink-0 rounded p-1 opacity-0 transition-opacity group-hover/row:opacity-100 focus-visible:opacity-100"- onClick={async (e) => {- e.stopPropagation();- try {- // Shared util: falls back to execCommand on non-secure contexts- // (plain-HTTP self-hosted deployments).- await copyTextToClipboard(value);- setCopied(true);- setTimeout(() => setCopied(false), 1200);- } catch (error) {- console.error("Unable to copy to clipboard", error);- }- }}- >- {copied ? (- <Check className="h-3.5 w-3.5" />- ) : (- <Copy className="h-3.5 w-3.5" />- )}- </button>- );-};--/**- * TopListChart: the HORIZONTAL_BAR visualiser. A ranked list where each row- * shows the metric value in a left column and the dimension label on top of a- * subtle proportional bar (top-list pattern à la Datadog). Rows keep a- * readable rhythm regardless of how few or many there are — few rows sit- * top-aligned instead of being spread across the tile — and the- * dimension name is copyable on hover.- */-export const TopListChart: React.FC<ChartProps> = ({+export function TopListChart({data,- metricFormatter = (value, options) => formatMetric(value, options),- subtleFill = false,-}) => {- const formatValue = useCallback(- (value: number) =>- toFullMetricString(metricFormatter(value, { style: "compact" })),- [metricFormatter],- );-- const rows = useMemo(- () =>- (data ?? []).map((d) => ({- dimension: d.dimension ?? "n/a",- value: typeof d.metric === "number" ? d.metric : Number(d.metric ?? 0),- })),- [data],- );-- // Bars encode magnitude relative to the largest |value|; the signed value- // in the adjacent column carries the sign. This keeps negative metrics- // (e.g. an averaged -1..1 score) visually ranked instead of collapsing- // every bar to zero width.- const maxMagnitude = useMemo(- () => Math.max(...rows.map((r) => Math.abs(r.value)), 0),- [rows],- );-- // Size the value column to the longest formatted value so bars align.- const valueColumnCh = useMemo(- () => Math.max(...rows.map((r) => formatValue(r.value).length), 2),- [rows, formatValue],- );-+ config,+ metricFormatter = formatMetric,+}: ChartProps) {return (- <div- // :has() dims every row except the hovered one, so the hovered row (and- // its copy affordance) reads as the single focused item.- className="flex h-full min-h-0 w-full flex-col overflow-x-hidden overflow-y-auto [&:has(>div:hover)>div:not(:hover)]:opacity-40"- style={{ gap: ROW_GAP_PX }}- data-testid="top-list-chart"- >- {rows.map((row, i) => (- <div- key={`${row.dimension}-${i}`}- className="group/row hover:bg-accent/60 flex items-center gap-2 rounded-sm transition-opacity"- style={{- flex: `0 1 ${MAX_ROW_PX}px`,- minHeight: MIN_ROW_PX,- // Each row is a size container so ROW_TEXT_STEPS can step the- // type scale by row height.- containerType: "size",- }}- title={`${row.dimension}: ${formatValue(row.value)}`}- >- <div- className={`shrink-0 text-right font-bold tabular-nums ${ROW_TEXT_STEPS}`}- style={{ width: `${valueColumnCh}ch` }}- >- {formatValue(row.value)}- </div>- <div className="relative h-full min-w-0 flex-1">- <div- className="h-full rounded-sm"- style={{- width: `${maxMagnitude > 0 ? (Math.abs(row.value) / maxMagnitude) * 100 : 0}%`,- backgroundColor: `hsl(var(--chart-1) / ${subtleFill ? 0.15 : 0.3})`,- }}- />- <div- className={`absolute inset-y-0 left-2 flex max-w-full min-w-0 items-center gap-1 pr-2 ${ROW_TEXT_STEPS}`}- >- <span className="text-foreground truncate" title={row.dimension}>- {row.dimension}- </span>- <CopyDimensionButton value={row.dimension} />- </div>- </div>- </div>- ))}- </div>+ <HorizontalBarChart+ data={(data ?? []).map((row) => ({+ label: row.dimension ?? "n/a",+ value:+ typeof row.metric === "number" ? row.metric : Number(row.metric ?? 0),+ }))}+ valueFormatter={(value) =>+ toFullMetricString(metricFormatter(value, { style: "compact" }))+ }+ color={config?.metric?.color ?? "hsl(var(--chart-1))"}+ />);-};+}