Skip to content

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

refactor(web): Create design-system StackedBarChart (#17865)

Ben Bacheme3c7b90d13c9
diff --git a/web/src/components/design-system/charts/StackedBarChart/StackedBarChart.stories.tsx b/web/src/components/design-system/charts/StackedBarChart/StackedBarChart.stories.tsx
new file mode 100644
index 0000000000..69d06ad9e5
--- /dev/null
+++ b/web/src/components/design-system/charts/StackedBarChart/StackedBarChart.stories.tsx
@@ -0,0 +1,304 @@
+import preview from "../../../../../.storybook/preview";
+import { expect, userEvent, within } from "storybook/test";
+
+import { StackedBarChart } from "./StackedBarChart";
+
+const meta = preview.meta({
+ component: StackedBarChart,
+ parameters: { layout: "fullscreen" },
+ args: {
+ data: [
+ { key: "Monday", values: { api: 12, worker: 8 } },
+ { key: "Tuesday", values: { api: 18, worker: null } },
+ { key: "Wednesday", values: { api: 10, worker: 15 } },
+ ],
+ series: [
+ { id: "api", label: "API", color: "hsl(var(--chart-1))" },
+ { id: "worker", label: "Worker", color: "hsl(var(--chart-2))" },
+ ],
+ },
+ decorators: [
+ (Story) => (
+ <div className="h-dvh w-full">
+ <Story />
+ </div>
+ ),
+ ],
+});
+
+export const Default = meta.story({});
+
+export const StackingAndTooltip = meta.story({
+ name: "(Test) Stacking and Tooltip",
+ play: async ({ canvasElement }) => {
+ const canvas = within(canvasElement);
+ const api = canvas.getAllByRole("graphics-symbol", { name: "API: 12" })[0];
+ const worker = canvas.getByRole("graphics-symbol", { name: "Worker: 8" });
+ if (!api) throw new Error("API bar missing");
+ await expect(
+ Number(worker.getAttribute("y")) + Number(worker.getAttribute("height")),
+ ).toBeCloseTo(Number(api.getAttribute("y")), 0);
+ worker.focus();
+ const tooltip = await within(canvasElement.ownerDocument.body).findByRole(
+ "tooltip",
+ );
+ await expect(tooltip).toHaveTextContent("Monday");
+ await expect(tooltip).toHaveTextContent("API");
+ await expect(tooltip).toHaveTextContent("Worker");
+ await expect(canvas.getAllByRole("graphics-symbol")).toHaveLength(5);
+ },
+});
+
+export const NegativeValues = meta.story({
+ name: "(Test) Negative Values",
+ args: {
+ data: [{ key: "Monday", values: { api: -12, worker: 8 } }],
+ },
+ play: async ({ canvasElement }) => {
+ await expect(
+ canvasElement.querySelector("[data-zero-baseline]"),
+ ).toBeInTheDocument();
+ },
+});
+
+export const LegendToggle = meta.story({
+ name: "(Test) Legend Toggle and Summary",
+ args: {
+ legend: {
+ visibility: "visible",
+ interaction: "toggle",
+ summary: "sum",
+ maxVisibleSeries: 1,
+ },
+ },
+ play: async ({ canvasElement }) => {
+ const canvas = within(canvasElement);
+ await expect(
+ canvas.queryAllByRole("graphics-symbol", { name: /Worker:/ }),
+ ).toHaveLength(0);
+ await expect(
+ canvas.getByRole("button", { name: "Show Worker" }),
+ ).toHaveTextContent("Sum: 23");
+ await userEvent.click(canvas.getByRole("button", { name: "Show Worker" }));
+ await expect(
+ canvas.getAllByRole("graphics-symbol", { name: /Worker:/ }),
+ ).toHaveLength(2);
+ await userEvent.click(canvas.getByRole("button", { name: "Hide API" }));
+ await expect(
+ canvas.queryAllByRole("graphics-symbol", { name: /API:/ }),
+ ).toHaveLength(0);
+ },
+});
+
+export const LegendHighlight = meta.story({
+ name: "(Test) Legend Highlight",
+ args: {
+ legend: {
+ visibility: "visible",
+ interaction: "highlight",
+ summary: "none",
+ },
+ },
+ play: async ({ canvasElement }) => {
+ const canvas = within(canvasElement);
+ const api = canvas.getByRole("graphics-symbol", { name: "API: 12" });
+ const worker = canvas.getByRole("graphics-symbol", { name: "Worker: 8" });
+ await userEvent.click(
+ canvas.getByRole("button", { name: "Show only Worker" }),
+ );
+ await expect(api).toHaveAttribute(
+ "fill",
+ "color-mix(in srgb, hsl(var(--chart-1)) 20%, hsl(var(--background)))",
+ );
+ await expect(worker).toHaveAttribute("fill", "hsl(var(--chart-2))");
+ await expect(canvas.getAllByRole("graphics-symbol")).toHaveLength(5);
+ await userEvent.click(
+ canvas.getByRole("button", { name: "Show all series" }),
+ );
+ await expect(api).toHaveAttribute("fill", "hsl(var(--chart-1))");
+ },
+});
+
+export const Empty = meta.story({
+ args: { data: [] },
+});
+
+export const SingleSeriesAutoLegend = meta.story({
+ name: "(Test) Single Series Auto Legend",
+ args: {
+ series: [{ id: "api", label: "API", color: "hsl(var(--chart-1))" }],
+ legend: { visibility: "auto", interaction: "highlight", summary: "none" },
+ },
+ play: async ({ canvasElement }) => {
+ const canvas = within(canvasElement);
+ await expect(
+ canvas.queryByRole("button", { name: "Show only API" }),
+ ).toBeNull();
+ await expect(canvas.getAllByRole("graphics-symbol")).toHaveLength(3);
+ },
+});
+
+export const SingleSeriesInitiallyHidden = meta.story({
+ name: "(Test) Single Series Initially Hidden",
+ args: {
+ series: [{ id: "api", label: "API", color: "hsl(var(--chart-1))" }],
+ legend: {
+ visibility: "auto",
+ interaction: "toggle",
+ summary: "none",
+ maxVisibleSeries: 0,
+ },
+ },
+ play: async ({ canvasElement }) => {
+ const canvas = within(canvasElement);
+ await expect(canvas.queryAllByRole("graphics-symbol")).toHaveLength(0);
+ await userEvent.click(canvas.getByRole("button", { name: "Show API" }));
+ await expect(canvas.getAllByRole("graphics-symbol")).toHaveLength(3);
+ },
+});
+
+export const MissingBuckets = meta.story({
+ name: "(Test) Missing Buckets",
+ args: {
+ data: [
+ { key: "Monday", values: { api: null, worker: null } },
+ { key: "Tuesday", values: { api: 0, worker: null } },
+ { key: "Wednesday", values: { api: 10, worker: 5 } },
+ ],
+ legend: { visibility: "visible", interaction: "toggle", summary: "sum" },
+ },
+ play: async ({ canvasElement }) => {
+ const canvas = within(canvasElement);
+ await expect(canvas.getAllByRole("graphics-symbol")).toHaveLength(3);
+ const zero = canvas.getByRole("graphics-symbol", { name: "API: 0" });
+ await expect(zero).not.toHaveAttribute("clip-path");
+ await expect(zero).toHaveAttribute("height", "1");
+ await expect(
+ canvas.getByRole("button", { name: "Hide API" }),
+ ).toHaveTextContent("Sum: 10");
+ await expect(
+ canvas.getByRole("button", { name: "Hide Worker" }),
+ ).toHaveTextContent("Sum: 5");
+ },
+});
+
+export const NegativeStack = meta.story({
+ name: "(Test) Negative Stack",
+ args: {
+ data: [{ key: "Monday", values: { api: -12, worker: -8 } }],
+ },
+ play: async ({ canvasElement }) => {
+ const canvas = within(canvasElement);
+ const api = canvas.getByRole("graphics-symbol", { name: "API: -12" });
+ const worker = canvas.getByRole("graphics-symbol", { name: "Worker: -8" });
+ await expect(Number(worker.getAttribute("y"))).toBeCloseTo(
+ Number(api.getAttribute("y")) + Number(api.getAttribute("height")),
+ 0,
+ );
+ await expect(
+ canvasElement.querySelector("[data-zero-baseline]"),
+ ).toBeInTheDocument();
+ },
+});
+
+export const ManyBuckets = meta.story({
+ name: "(Test) Many Buckets",
+ args: {
+ data: Array.from({ length: 60 }, (_, index) => ({
+ key: `Bucket ${index + 1}`,
+ values: { api: index + 1, worker: index % 3 === 0 ? null : 10 },
+ })),
+ },
+ decorators: [
+ (Story) => (
+ <div className="h-40 w-[320px]">
+ <Story />
+ </div>
+ ),
+ ],
+ play: async ({ canvasElement }) => {
+ const labels = Array.from(
+ canvasElement.querySelectorAll<SVGTextElement>("[data-x-axis-label]"),
+ );
+ await expect(labels.length).toBeGreaterThan(1);
+ for (let index = 1; index < labels.length; index++) {
+ const previous = labels[index - 1];
+ const current = labels[index];
+ if (!previous || !current) throw new Error("Axis label missing");
+ await expect(current.getBoundingClientRect().left).toBeGreaterThanOrEqual(
+ previous.getBoundingClientRect().right,
+ );
+ }
+ await expect(labels.at(-1)).toHaveTextContent("Bucket 60");
+ },
+});
+
+export const SyncedBucket = meta.story({
+ name: "(Test) Synced Bucket",
+ args: {
+ sync: { activeKey: "Tuesday", onActiveKeyChange: () => undefined },
+ },
+ play: async ({ canvasElement }) => {
+ const line = canvasElement.querySelector("[data-active-reference-line]");
+ const bar = within(canvasElement).getByRole("graphics-symbol", {
+ name: "API: 18",
+ });
+ if (!line) throw new Error("Active reference line missing");
+ await expect(Number(line.getAttribute("x1"))).toBeCloseTo(
+ Number(bar.getAttribute("x")) + Number(bar.getAttribute("width")) / 2,
+ );
+ },
+});
+
+export const LongCategoryLabels = meta.story({
+ name: "(Test) Long category labels",
+ args: {
+ data: Array.from({ length: 12 }, (_, index) => ({
+ key: `dataset-run-${index + 1}-transcription`,
+ values: { api: index + 1 },
+ })),
+ tickFormatter: (key) => `${key.slice(0, 23)}…`,
+ categoryXAxisLabels: true,
+ },
+ decorators: [
+ (Story) => (
+ <div className="h-48 w-[320px]">
+ <Story />
+ </div>
+ ),
+ ],
+ play: async ({ canvasElement }) => {
+ const labels = canvasElement.querySelectorAll<SVGTextElement>(
+ "[data-x-axis-label]",
+ );
+ await expect(labels.length).toBeGreaterThan(0);
+ for (const label of labels) {
+ await expect(label).not.toHaveAttribute("transform");
+ await expect(label.getBoundingClientRect().left).toBeGreaterThanOrEqual(
+ 0,
+ );
+ }
+ },
+});
+
+export const NarrowTemporalTicks = meta.story({
+ name: "(Test) Narrow temporal tick spacing",
+ args: {
+ data: Array.from({ length: 24 }, (_, index) => ({
+ key: `2026-09-${String(index + 1).padStart(2, "0")}`,
+ values: { api: index + 1 },
+ })),
+ tickFormatter: (key) => key.slice(5),
+ },
+ decorators: [
+ (Story) => (
+ <div className="h-40 w-[320px]">
+ <Story />
+ </div>
+ ),
+ ],
+ play: async ({ canvasElement }) => {
+ const labels = canvasElement.querySelectorAll("[data-x-axis-label]");
+ await expect(labels.length).toBeLessThanOrEqual(5);
+ },
+});
diff --git a/web/src/components/design-system/charts/StackedBarChart/StackedBarChart.tsx b/web/src/components/design-system/charts/StackedBarChart/StackedBarChart.tsx
new file mode 100644
index 0000000000..4f735cd0a6
--- /dev/null
+++ b/web/src/components/design-system/charts/StackedBarChart/StackedBarChart.tsx
@@ -0,0 +1,492 @@
+"use client";
+
+import { useId, useState } from "react";
+import { scaleLinear } from "d3-scale";
+
+import { ChartContainer } from "@/src/components/design-system/charts/ChartContainer";
+import { ChartLegend } from "@/src/components/design-system/internal/charts/ChartLegend";
+import { CartesianChart } from "@/src/components/design-system/internal/charts/CartesianChart";
+import { CartesianLayout } from "@/src/components/design-system/internal/charts/CartesianLayout";
+import { ChartTooltip } from "@/src/components/design-system/internal/charts/ChartTooltip";
+import { createBarBandScale } from "@/src/components/design-system/internal/charts/fns/createBarBandScale";
+
+import type { LineChartLegend } from "@/src/components/design-system/charts/LineChart/LineChart";
+
+export function StackedBarChart({
+ data,
+ series,
+ valueFormatter = (value) => value.toLocaleString(),
+ tickFormatter = (value) => value,
+ categoryXAxisLabels = false,
+ tooltipFormatter = (value) => value,
+ hideXAxisLabels = false,
+ sync,
+ legend,
+}: {
+ data: { key: string; values: Record<string, number | null> }[];
+ series: { id: string; label: string; color: string }[];
+ valueFormatter?: (value: number) => string;
+ tickFormatter?: (value: string) => string;
+ categoryXAxisLabels?: boolean;
+ tooltipFormatter?: (value: string) => string;
+ hideXAxisLabels?: boolean;
+ sync?: {
+ activeKey: string | undefined;
+ onActiveKeyChange: (key: string | undefined) => void;
+ };
+ legend?: LineChartLegend;
+}) {
+ const [hoveredIndex, setHoveredIndex] = useState<number>();
+ const clipId = useId();
+ const summaries = new Map(
+ series.map((item) => {
+ const values = data.flatMap((datum) => {
+ const value = datum.values[item.id];
+ return typeof value === "number" && Number.isFinite(value)
+ ? [value]
+ : [];
+ });
+ return [
+ item.id,
+ values.length ? values.reduce((sum, value) => sum + value, 0) : null,
+ ] as const;
+ }),
+ );
+ const initialHidden = new Set<string>();
+ if (
+ legend?.visibility !== "hidden" &&
+ legend?.interaction === "toggle" &&
+ legend.maxVisibleSeries !== undefined
+ ) {
+ const keep = new Set(
+ [...series]
+ .sort(
+ (left, right) =>
+ (summaries.get(right.id) ?? -Infinity) -
+ (summaries.get(left.id) ?? -Infinity),
+ )
+ .slice(0, Math.max(0, legend.maxVisibleSeries))
+ .map((item) => item.id),
+ );
+ for (const item of series)
+ if (!keep.has(item.id)) initialHidden.add(item.id);
+ }
+ const seedKey = `${legend?.visibility ?? "hidden"}|${legend?.visibility !== "hidden" ? legend?.interaction : ""}|${legend?.visibility !== "hidden" && legend?.interaction === "toggle" ? (legend.maxVisibleSeries ?? "") : ""}|${JSON.stringify(series.map((item) => item.id).sort())}`;
+ const [legendState, setLegendState] = useState({
+ seedKey,
+ highlightedId: undefined as string | undefined,
+ visibilityOverrides: new Map<string, boolean>(),
+ });
+ const effectiveState =
+ legendState.seedKey === seedKey
+ ? legendState
+ : {
+ seedKey,
+ highlightedId: undefined,
+ visibilityOverrides: new Map<string, boolean>(),
+ };
+ const { highlightedId, visibilityOverrides } = effectiveState;
+ const hiddenIds = new Set(initialHidden);
+ for (const [id, hidden] of visibilityOverrides) {
+ if (hidden) hiddenIds.add(id);
+ else hiddenIds.delete(id);
+ }
+ const visibleSeries = series.filter((item) => !hiddenIds.has(item.id));
+ const showLegend =
+ legend?.visibility === "visible" ||
+ (legend?.visibility === "auto" &&
+ (series.length > 1 || hiddenIds.size > 0));
+ const totals = data.map((datum) => {
+ let positive = 0;
+ let negative = 0;
+ for (const item of visibleSeries) {
+ const value = datum.values[item.id];
+ if (typeof value !== "number" || !Number.isFinite(value)) continue;
+ if (value >= 0) positive += value;
+ else negative += value;
+ }
+ return { positive, negative };
+ });
+ const min = Math.min(0, ...totals.map((total) => total.negative));
+ const max = Math.max(1, ...totals.map((total) => total.positive));
+
+ return (
+ <div className="flex size-full min-w-0 flex-col">
+ <div className="min-h-0 flex-1">
+ <ChartContainer>
+ {({ width, height }) => (
+ <CartesianLayout
+ width={width}
+ height={height}
+ showXAxisLabels={!hideXAxisLabels}
+ >
+ {({ measuredPlot, maxYTicks, plotForTicks }) => {
+ const y = scaleLinear()
+ .domain([min, max])
+ .nice(maxYTicks)
+ .range([
+ measuredPlot.top + measuredPlot.height,
+ measuredPlot.top,
+ ]);
+ const yTicks = y.ticks(maxYTicks);
+ const plot = plotForTicks(yTicks.map(valueFormatter));
+ const x = createBarBandScale(
+ data.length,
+ plot.left,
+ plot.width,
+ "default",
+ );
+ const syncedIndex = data.findIndex(
+ (datum) => datum.key === sync?.activeKey,
+ );
+ const activeIndex = hoveredIndex ?? syncedIndex;
+ let previousTickRight = -Infinity;
+ const xTicks: {
+ key: string;
+ x: number;
+ label: string;
+ textAnchor?: "end";
+ }[] = [];
+ data.forEach((datum, index) => {
+ const label = tickFormatter(datum.key);
+ const center = (x(index) ?? plot.left) + x.bandwidth() / 2;
+ const labelWidth = label.length * 7;
+ if (categoryXAxisLabels) {
+ const right = Math.min(width - 8, center);
+ const left = right - labelWidth;
+ if (left >= 8 && left >= previousTickRight + 16) {
+ xTicks.push({
+ key: datum.key,
+ x: right,
+ label,
+ textAnchor: "end",
+ });
+ previousTickRight = right;
+ }
+ return;
+ }
+ if (index === data.length - 1) {
+ const right = Math.min(width - 8, center + labelWidth / 2);
+ const left = right - labelWidth;
+ while (xTicks.length > 0 && left < previousTickRight + 16) {
+ xTicks.pop();
+ const previous = xTicks.at(-1);
+ previousTickRight = previous
+ ? previous.x + previous.label.length * 3.5
+ : -Infinity;
+ }
+ if (left >= 8) {
+ xTicks.push({
+ key: datum.key,
+ x: right,
+ label,
+ textAnchor: "end",
+ });
+ }
+ return;
+ }
+ const left = center - labelWidth / 2;
+ if (
+ left < previousTickRight + 16 ||
+ center + labelWidth / 2 > width - 8
+ ) {
+ return;
+ }
+ previousTickRight = center + labelWidth / 2;
+ xTicks.push({ key: datum.key, x: center, label });
+ });
+
+ if (
+ width <= 0 ||
+ height <= 0 ||
+ plot.width <= 0 ||
+ plot.height <= 0
+ ) {
+ return (
+ <svg width={width} height={height} aria-hidden="true" />
+ );
+ }
+
+ return (
+ <ChartTooltip>
+ {({ activeIndex: tooltipIndex, getReferenceProps }) => (
+ <CartesianChart
+ width={width}
+ height={height}
+ ariaLabel="Stacked bar chart"
+ plot={plot}
+ yTicks={yTicks}
+ y={y}
+ valueFormatter={valueFormatter}
+ zeroY={min < 0 ? y(0) : undefined}
+ xAxis={
+ hideXAxisLabels
+ ? undefined
+ : {
+ ticks: xTicks,
+ activeKey:
+ activeIndex >= 0
+ ? data[activeIndex]?.key
+ : undefined,
+ alignment: "center",
+ }
+ }
+ >
+ {activeIndex >= 0 && activeIndex < data.length ? (
+ <line
+ data-active-reference-line=""
+ x1={
+ (x(activeIndex) ?? plot.left) + x.bandwidth() / 2
+ }
+ x2={
+ (x(activeIndex) ?? plot.left) + x.bandwidth() / 2
+ }
+ y1={plot.top}
+ y2={plot.top + plot.height}
+ stroke="hsl(var(--muted-foreground))"
+ strokeDasharray="3 3"
+ aria-hidden="true"
+ />
+ ) : null}
+ {data.map((datum, index) => {
+ const left = x(index);
+ if (left === undefined) return null;
+ let positive = 0;
+ let negative = 0;
+ const items = visibleSeries.flatMap((item) => {
+ const value = datum.values[item.id];
+ return typeof value === "number" &&
+ Number.isFinite(value)
+ ? [
+ {
+ id: item.id,
+ label: item.label,
+ value: valueFormatter(value),
+ color: item.color,
+ },
+ ]
+ : [];
+ });
+ const referenceProps = getReferenceProps({
+ type: "items",
+ index,
+ heading: tooltipFormatter(datum.key),
+ items: items.sort(
+ (a, b) =>
+ (datum.values[b.id] ?? 0) -
+ (datum.values[a.id] ?? 0),
+ ),
+ });
+ return (
+ <g key={`${datum.key}-${index}`}>
+ <defs>
+ <clipPath id={`${clipId}-positive-${index}`}>
+ <rect
+ x={left}
+ y={y(totals[index]?.positive ?? 0)}
+ width={x.bandwidth()}
+ height={
+ y(0) - y(totals[index]?.positive ?? 0)
+ }
+ rx={4}
+ />
+ </clipPath>
+ <clipPath id={`${clipId}-negative-${index}`}>
+ <rect
+ x={left}
+ y={y(0)}
+ width={x.bandwidth()}
+ height={
+ y(totals[index]?.negative ?? 0) - y(0)
+ }
+ rx={4}
+ />
+ </clipPath>
+ </defs>
+ <rect
+ x={left}
+ y={plot.top}
+ width={x.bandwidth()}
+ height={plot.height}
+ fill="transparent"
+ aria-hidden="true"
+ {...referenceProps}
+ onPointerEnter={(event) => {
+ referenceProps.onPointerEnter(event);
+ setHoveredIndex(index);
+ sync?.onActiveKeyChange(datum.key);
+ }}
+ onPointerMove={(event) => {
+ referenceProps.onPointerMove(event);
+ setHoveredIndex(index);
+ sync?.onActiveKeyChange(datum.key);
+ }}
+ onPointerLeave={() => {
+ referenceProps.onPointerLeave();
+ setHoveredIndex(undefined);
+ sync?.onActiveKeyChange(undefined);
+ }}
+ />
+ {visibleSeries.map((item) => {
+ const value = datum.values[item.id];
+ if (
+ typeof value !== "number" ||
+ !Number.isFinite(value)
+ )
+ return null;
+ const start = value >= 0 ? positive : negative;
+ if (value >= 0) positive += value;
+ else negative += value;
+ const top =
+ value === 0
+ ? y(start) - 1
+ : Math.min(y(start), y(start + value));
+ const barHeight = Math.max(
+ 1,
+ Math.abs(y(start) - y(start + value)),
+ );
+ let colorStrength = 100;
+ if (
+ highlightedId !== undefined &&
+ item.id !== highlightedId
+ )
+ colorStrength = 20;
+ else if (
+ tooltipIndex !== undefined &&
+ tooltipIndex !== index
+ )
+ colorStrength = 30;
+ const fill =
+ colorStrength === 100
+ ? item.color
+ : `color-mix(in srgb, ${item.color} ${colorStrength}%, hsl(var(--background)))`;
+ return (
+ <rect
+ key={item.id}
+ x={left}
+ y={top}
+ width={x.bandwidth()}
+ height={barHeight}
+ clipPath={
+ value === 0
+ ? undefined
+ : `url(#${clipId}-${value >= 0 ? "positive" : "negative"}-${index})`
+ }
+ fill={fill}
+ role="graphics-symbol"
+ tabIndex={0}
+ aria-label={`${item.label}: ${valueFormatter(value)}`}
+ className="outline-hidden transition-[fill] duration-150 focus-visible:outline-2 focus-visible:outline-offset-2"
+ {...referenceProps}
+ onPointerEnter={(event) => {
+ referenceProps.onPointerEnter(event);
+ setHoveredIndex(index);
+ sync?.onActiveKeyChange(datum.key);
+ }}
+ onPointerMove={(event) => {
+ referenceProps.onPointerMove(event);
+ setHoveredIndex(index);
+ sync?.onActiveKeyChange(datum.key);
+ }}
+ onFocus={(event) => {
+ referenceProps.onFocus(event);
+ setHoveredIndex(index);
+ sync?.onActiveKeyChange(datum.key);
+ }}
+ onPointerLeave={() => {
+ referenceProps.onPointerLeave();
+ setHoveredIndex(undefined);
+ sync?.onActiveKeyChange(undefined);
+ }}
+ onBlur={() => {
+ referenceProps.onBlur();
+ setHoveredIndex(undefined);
+ sync?.onActiveKeyChange(undefined);
+ }}
+ />
+ );
+ })}
+ </g>
+ );
+ })}
+ </CartesianChart>
+ )}
+ </ChartTooltip>
+ );
+ }}
+ </CartesianLayout>
+ )}
+ </ChartContainer>
+ </div>
+ {showLegend ? (
+ <ChartLegend
+ selectionActions={
+ legend.interaction === "toggle"
+ ? {
+ allSelected: hiddenIds.size === 0,
+ onSelectAll: () =>
+ setLegendState({
+ ...effectiveState,
+ visibilityOverrides: new Map(
+ series.map((item) => [item.id, false]),
+ ),
+ }),
+ onDeselectAll: () =>
+ setLegendState({
+ ...effectiveState,
+ visibilityOverrides: new Map(
+ series.map((item) => [item.id, true]),
+ ),
+ }),
+ }
+ : undefined
+ }
+ items={series.map((item) => {
+ const hidden = hiddenIds.has(item.id);
+ const focused = highlightedId === item.id;
+ let label = `Show only ${item.label}`;
+ if (legend.interaction === "toggle")
+ label = hidden ? `Show ${item.label}` : `Hide ${item.label}`;
+ else if (focused) label = "Show all series";
+ const summary = summaries.get(item.id);
+ return {
+ id: item.id,
+ label: item.label,
+ color: item.color,
+ value:
+ legend.summary === "sum" &&
+ summary !== null &&
+ summary !== undefined
+ ? { label: "Sum", value: valueFormatter(summary) }
+ : undefined,
+ muted:
+ hidden ||
+ (legend.interaction === "highlight" &&
+ highlightedId !== undefined &&
+ !focused),
+ action: {
+ label,
+ pressed: legend.interaction === "toggle" ? !hidden : focused,
+ onClick: () => {
+ if (legend.interaction === "toggle") {
+ const next = new Map(visibilityOverrides);
+ next.set(item.id, !hidden);
+ setLegendState({
+ ...effectiveState,
+ visibilityOverrides: next,
+ });
+ return;
+ }
+ setLegendState({
+ ...effectiveState,
+ highlightedId: focused ? undefined : item.id,
+ });
+ },
+ },
+ };
+ })}
+ />
+ ) : null}
+ </div>
+ );
+}
diff --git a/web/src/components/design-system/internal/charts/BarChartCore.tsx b/web/src/components/design-system/internal/charts/BarChartCore.tsx
index 744396d20f..90b9f588c4 100644
--- a/web/src/components/design-system/internal/charts/BarChartCore.tsx
+++ b/web/src/components/design-system/internal/charts/BarChartCore.tsx
@@ -1,6 +1,6 @@
"use client";
-import { scaleBand, scaleLinear } from "d3-scale";
+import { scaleLinear } from "d3-scale";
import { ChartContainer } from "@/src/components/design-system/charts/ChartContainer";
import { CartesianChart } from "@/src/components/design-system/internal/charts/CartesianChart";
@@ -10,6 +10,7 @@ import {
type ChartLegendItem,
} from "@/src/components/design-system/internal/charts/ChartLegend";
import { ChartTooltip } from "@/src/components/design-system/internal/charts/ChartTooltip";
+import { createBarBandScale } from "@/src/components/design-system/internal/charts/fns/createBarBandScale";
export type BarChartDatum = {
label: string;
@@ -89,11 +90,12 @@ export function BarChartCore({
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(barSpacing === "histogram" ? 0 : 0.2)
- .paddingOuter(barSpacing === "histogram" ? 0 : 0.1);
+ const xScale = createBarBandScale(
+ data.length,
+ leftMargin,
+ plotWidth,
+ barSpacing,
+ );
const baseline = yScale(
zeroBaseline || min < 0 ? 0 : (yScale.domain()[0] ?? 0),
);
diff --git a/web/src/components/design-system/internal/charts/CartesianChart.tsx b/web/src/components/design-system/internal/charts/CartesianChart.tsx
index aef03322a5..144a5c0900 100644
--- a/web/src/components/design-system/internal/charts/CartesianChart.tsx
+++ b/web/src/components/design-system/internal/charts/CartesianChart.tsx
@@ -57,7 +57,13 @@ function ChartXAxis({
showCategoryTicks = false,
alignment = "endpoints",
}: {
- ticks: { key: string; x: number; label: string; maxWidth?: number }[];
+ ticks: {
+ key: string;
+ x: number;
+ label: string;
+ maxWidth?: number;
+ textAnchor?: "end";
+ }[];
activeKey?: string;
y: number;
width: number;
@@ -159,7 +165,9 @@ function ChartXAxis({
data-active-x-axis-label={active ? "" : undefined}
x={active ? activeTextX : tick.x}
y={y + 16}
- textAnchor={active ? "middle" : textAnchor}
+ textAnchor={
+ active ? "middle" : (tick.textAnchor ?? textAnchor)
+ }
textLength={
active &&
tick.label.length * characterWidth > activeTextWidth
@@ -242,7 +250,13 @@ export function CartesianChart({
categoryBoundaries?: boolean;
zeroY?: number;
xAxis?: {
- ticks: { key: string; x: number; label: string; maxWidth?: number }[];
+ ticks: {
+ key: string;
+ x: number;
+ label: string;
+ maxWidth?: number;
+ textAnchor?: "end";
+ }[];
activeKey?: string;
showCategoryTicks?: boolean;
alignment?: "endpoints" | "center";
diff --git a/web/src/components/design-system/internal/charts/CartesianLayout.tsx b/web/src/components/design-system/internal/charts/CartesianLayout.tsx
index 6eabb2caab..0ddcf5f9a7 100644
--- a/web/src/components/design-system/internal/charts/CartesianLayout.tsx
+++ b/web/src/components/design-system/internal/charts/CartesianLayout.tsx
@@ -75,6 +75,11 @@ export function CartesianLayout({
measuredPlot,
maxYTicks: getCartesianTickCount(measuredPlot.height),
plotForTicks: (yTickLabels) =>
- getCartesianLayout({ width, height, showXAxisLabels, yTickLabels }),
+ getCartesianLayout({
+ width,
+ height,
+ showXAxisLabels,
+ yTickLabels,
+ }),
});
}
diff --git a/web/src/components/design-system/internal/charts/fns/createBarBandScale.ts b/web/src/components/design-system/internal/charts/fns/createBarBandScale.ts
new file mode 100644
index 0000000000..c49e8a2761
--- /dev/null
+++ b/web/src/components/design-system/internal/charts/fns/createBarBandScale.ts
@@ -0,0 +1,15 @@
+/* eslint-disable check-file/folder-naming-convention -- Internal chart functions live in the requested fns directory. */
+import { scaleBand } from "d3-scale";
+
+export function createBarBandScale(
+ count: number,
+ left: number,
+ width: number,
+ spacing: "default" | "histogram",
+) {
+ return scaleBand<number>()
+ .domain(Array.from({ length: count }, (_, index) => index))
+ .range([left, left + width])
+ .paddingInner(spacing === "histogram" ? 0 : 0.2)
+ .paddingOuter(spacing === "histogram" ? 0 : 0.1);
+}
diff --git a/web/src/features/dashboard/components/ChartScores.tsx b/web/src/features/dashboard/components/ChartScores.tsx
index 72ed2f11a9..9e2929e6c0 100644
--- a/web/src/features/dashboard/components/ChartScores.tsx
+++ b/web/src/features/dashboard/components/ChartScores.tsx
@@ -38,6 +38,10 @@ export function ChartScores(props: {
metricsVersion: ViewVersion;
schedulerId?: string;
syncId?: string;
+ sync?: {
+ activeKey: string | undefined;
+ onActiveKeyChange: (key: string | undefined) => void;
+ };
}) {
const scoresQuery: QueryType = {
view: "scores-numeric",
@@ -129,6 +133,7 @@ export function ChartScores(props: {
rowLimit={100}
chartConfig={SCORES_CHART_CONFIG}
syncId={props.syncId}
+ sync={props.sync}
/>
</div>
) : (
diff --git a/web/src/features/dashboard/components/DashboardLineTimeSeriesChart.tsx b/web/src/features/dashboard/components/DashboardLineTimeSeriesChart.tsx
index ee5a4ad2e4..0e3b49a264 100644
--- a/web/src/features/dashboard/components/DashboardLineTimeSeriesChart.tsx
+++ b/web/src/features/dashboard/components/DashboardLineTimeSeriesChart.tsx
@@ -25,6 +25,7 @@ export const DashboardLineTimeSeriesChart = React.memo(
unit,
legendSummary,
syncId,
+ sync,
missingValue,
}: {
data: TimeSeriesChartDataPoint[];
@@ -32,6 +33,10 @@ export const DashboardLineTimeSeriesChart = React.memo(
unit?: string;
legendSummary?: LegendSummaryMode;
syncId?: string;
+ sync?: {
+ activeKey: string | undefined;
+ onActiveKeyChange: (key: string | undefined) => void;
+ };
/** See {@link MissingBucketValue}. Defaults to `"gap"`. */
missingValue?: MissingBucketValue;
}) {
@@ -58,6 +63,7 @@ export const DashboardLineTimeSeriesChart = React.memo(
chartConfig={chartConfig}
legendSummary={legendSummary}
syncId={syncId}
+ sync={sync}
missingValue={missingValue}
/>
);
diff --git a/web/src/features/dashboard/components/LatencyChart.tsx b/web/src/features/dashboard/components/LatencyChart.tsx
index 77a184187f..6e00cccb23 100644
--- a/web/src/features/dashboard/components/LatencyChart.tsx
+++ b/web/src/features/dashboard/components/LatencyChart.tsx
@@ -34,6 +34,7 @@ export const GenerationLatencyChart = ({
metricsVersion,
schedulerId,
syncId,
+ sync,
}: {
className?: string;
projectId: string;
@@ -45,6 +46,10 @@ export const GenerationLatencyChart = ({
metricsVersion: ViewVersion;
schedulerId?: string;
syncId?: string;
+ sync?: {
+ activeKey: string | undefined;
+ onActiveKeyChange: (key: string | undefined) => void;
+ };
}) => {
const { allModels, selectedModels, setSelectedModels } = useModelSelection(
projectId,
@@ -178,6 +183,7 @@ export const GenerationLatencyChart = ({
label="Latency"
unit="millisecond"
syncId={syncId}
+ sync={sync}
missingValue="gap"
/>
</div>
diff --git a/web/src/features/dashboard/components/ModelUsageChart.tsx b/web/src/features/dashboard/components/ModelUsageChart.tsx
index ce71c32ee3..fb70c49a2a 100644
--- a/web/src/features/dashboard/components/ModelUsageChart.tsx
+++ b/web/src/features/dashboard/components/ModelUsageChart.tsx
@@ -38,6 +38,7 @@ export const ModelUsageChart = ({
metricsVersion,
schedulerId,
syncId,
+ sync,
}: {
className?: string;
projectId: string;
@@ -50,6 +51,10 @@ export const ModelUsageChart = ({
metricsVersion: ViewVersion;
schedulerId?: string;
syncId?: string;
+ sync?: {
+ activeKey: string | undefined;
+ onActiveKeyChange: (key: string | undefined) => void;
+ };
}) => {
const { allModels, selectedModels, setSelectedModels } = useModelSelection(
projectId,
@@ -392,6 +397,7 @@ export const ModelUsageChart = ({
// Token/cost totals are additive sums. (LFE-10498)
legendSummary="sum"
syncId={syncId}
+ sync={sync}
// Additive sums: a bucket without data honestly sums to 0. (LFE-10694)
missingValue="zero"
/>
diff --git a/web/src/features/dashboard/components/TracesTimeSeriesChart.tsx b/web/src/features/dashboard/components/TracesTimeSeriesChart.tsx
index 1cdd64e265..896617b987 100644
--- a/web/src/features/dashboard/components/TracesTimeSeriesChart.tsx
+++ b/web/src/features/dashboard/components/TracesTimeSeriesChart.tsx
@@ -27,6 +27,7 @@ export const TracesAndObservationsTimeSeriesChart = ({
metricsVersion,
schedulerId,
syncId,
+ sync,
}: {
className?: string;
projectId: string;
@@ -38,6 +39,10 @@ export const TracesAndObservationsTimeSeriesChart = ({
metricsVersion: ViewVersion;
schedulerId?: string;
syncId?: string;
+ sync?: {
+ activeKey: string | undefined;
+ onActiveKeyChange: (key: string | undefined) => void;
+ };
}) => {
const isV2 = metricsVersion === "v2";
@@ -220,6 +225,7 @@ export const TracesAndObservationsTimeSeriesChart = ({
// the card headline. (LFE-10498)
legendSummary="sum"
syncId={syncId}
+ sync={sync}
// Additive counts: a bucket without data honestly counts 0. (LFE-10694)
missingValue="zero"
/>
diff --git a/web/src/features/dashboard/components/home-preset-registry.tsx b/web/src/features/dashboard/components/home-preset-registry.tsx
index 91f7e7862c..a82d01c46d 100644
--- a/web/src/features/dashboard/components/home-preset-registry.tsx
+++ b/web/src/features/dashboard/components/home-preset-registry.tsx
@@ -35,8 +35,12 @@ export interface PresetWidgetContext {
isLoading: boolean;
metricsVersion: ViewVersion;
schedulerId?: string;
- /** Shared recharts syncId so time-series tiles move their crosshairs together. */
+ /** Recharts sync group for legacy preset charts. */
syncId: string;
+ sync: {
+ activeKey: string | undefined;
+ onActiveKeyChange: (key: string | undefined) => void;
+ };
className: string;
}
@@ -95,6 +99,7 @@ const HOME_PRESETS: Record<
metricsVersion={ctx.metricsVersion}
schedulerId={ctx.schedulerId}
syncId={ctx.syncId}
+ sync={ctx.sync}
/>
),
"home-model-usage": (ctx) => (
@@ -110,6 +115,7 @@ const HOME_PRESETS: Record<
metricsVersion={ctx.metricsVersion}
schedulerId={ctx.schedulerId}
syncId={ctx.syncId}
+ sync={ctx.sync}
/>
),
"home-users": (ctx) => (
@@ -136,6 +142,7 @@ const HOME_PRESETS: Record<
metricsVersion={ctx.metricsVersion}
schedulerId={ctx.schedulerId}
syncId={ctx.syncId}
+ sync={ctx.sync}
/>
),
"home-latency-table-traces": (ctx) => (
@@ -189,6 +196,7 @@ const HOME_PRESETS: Record<
metricsVersion={ctx.metricsVersion}
schedulerId={ctx.schedulerId}
syncId={ctx.syncId}
+ sync={ctx.sync}
/>
),
"home-score-analytics": (ctx) => (
@@ -203,6 +211,7 @@ const HOME_PRESETS: Record<
metricsVersion={ctx.metricsVersion}
schedulerId={ctx.schedulerId}
syncId={ctx.syncId}
+ sync={ctx.sync}
/>
),
};
diff --git a/web/src/features/dashboard/components/score-analytics/NumericScoreTimeSeriesChart.tsx b/web/src/features/dashboard/components/score-analytics/NumericScoreTimeSeriesChart.tsx
index 9dc843a849..eca931450b 100644
--- a/web/src/features/dashboard/components/score-analytics/NumericScoreTimeSeriesChart.tsx
+++ b/web/src/features/dashboard/components/score-analytics/NumericScoreTimeSeriesChart.tsx
@@ -34,6 +34,10 @@ export function NumericScoreTimeSeriesChart(props: {
schedulerId?: string;
/** Shared hover-sync group so this chart joins the dashboard crosshair. */
syncId?: string;
+ sync?: {
+ activeKey: string | undefined;
+ onActiveKeyChange: (key: string | undefined) => void;
+ };
}) {
const scoresQuery: QueryType = {
view: "scores-numeric",
@@ -113,6 +117,7 @@ export function NumericScoreTimeSeriesChart(props: {
<DashboardLineTimeSeriesChart
data={extractedScores}
syncId={props.syncId}
+ sync={props.sync}
/>
</div>
) : (
diff --git a/web/src/features/dashboard/components/score-analytics/ScoreAnalytics.tsx b/web/src/features/dashboard/components/score-analytics/ScoreAnalytics.tsx
index 4c2b801970..e76c9f4731 100644
--- a/web/src/features/dashboard/components/score-analytics/ScoreAnalytics.tsx
+++ b/web/src/features/dashboard/components/score-analytics/ScoreAnalytics.tsx
@@ -34,6 +34,10 @@ export function ScoreAnalytics(props: {
schedulerId?: string;
/** Shared hover-sync group so the per-score line charts join the dashboard crosshair. */
syncId?: string;
+ sync?: {
+ activeKey: string | undefined;
+ onActiveKeyChange: (key: string | undefined) => void;
+ };
}) {
// Stale score selections in localStorage are ignored as we only show scores that exist in scoreAnalyticsOptions
const [selectedDashboardScoreKeys, setSelectedDashboardScoreKeys] =
@@ -203,6 +207,7 @@ export function ScoreAnalytics(props: {
metricsVersion={props.metricsVersion}
schedulerId={props.schedulerId}
syncId={props.syncId}
+ sync={props.sync}
/>
)}
</div>
diff --git a/web/src/features/widgets/chart-library/Chart.tsx b/web/src/features/widgets/chart-library/Chart.tsx
index d20870b0b6..8d0654651d 100644
--- a/web/src/features/widgets/chart-library/Chart.tsx
+++ b/web/src/features/widgets/chart-library/Chart.tsx
@@ -226,7 +226,6 @@ const ChartComponent = ({
maxVisibleSeries={maxVisibleSeries}
syncId={syncId}
sync={sync}
- subtleFill={chartConfig?.subtle_fill}
hideXAxisLabels={hideXAxisLabels}
/>
);
diff --git a/web/src/features/widgets/chart-library/VerticalBarChartTimeSeries.tsx b/web/src/features/widgets/chart-library/VerticalBarChartTimeSeries.tsx
index 024ad97656..06f2427c88 100644
--- a/web/src/features/widgets/chart-library/VerticalBarChartTimeSeries.tsx
+++ b/web/src/features/widgets/chart-library/VerticalBarChartTimeSeries.tsx
@@ -1,13 +1,7 @@
-/* eslint-disable no-nested-ternary */
-import React, { useMemo, useRef, useState } from "react";
-import {
- ChartActiveReferenceLine,
- ChartContainer,
- ChartTooltip,
- ChartTooltipContent,
- ChartTooltipPortal,
-} from "@/src/components/ui/chart";
-import { Bar, BarChart, CartesianGrid, XAxis, YAxis } from "recharts";
+import { useMemo } from "react";
+
+import { StackedBarChart } from "@/src/components/design-system/charts/StackedBarChart/StackedBarChart";
+import type { LineChartLegend } from "@/src/components/design-system/charts/LineChart/LineChart";
import { type ChartProps } from "@/src/features/widgets/chart-library/chart-props";
import {
formatMetric,
@@ -15,7 +9,6 @@ import {
groupDataByTimeDimension,
toFullMetricString,
} from "@/src/features/widgets/chart-library/utils";
-import { useChartTickBudget } from "@/src/features/widgets/chart-library/useChartTickBudget";
import {
parseChartTimestamp,
prepareTimeAxis,
@@ -24,215 +17,111 @@ import { prepareVisibleSeries } from "@/src/features/widgets/chart-library/prepa
import {
seriesColor,
SeriesOverflowNote,
- TimeSeriesLegend,
- useSeriesLegend,
} from "@/src/features/widgets/chart-library/TimeSeriesLegend";
-import { temporalAxisTickProp } from "@/src/features/widgets/chart-library/TimeAxisTick";
+import { getPlainTextFromReactNode } from "@/src/utils/react-node-plain-text";
-/**
- * VerticalBarChartTimeSeries component
- * @param data - Data to be displayed. Expects an array of objects with time_dimension, 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 VerticalBarChartTimeSeries: React.FC<ChartProps> = ({
+export function VerticalBarChartTimeSeries({
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,
legendPosition = "auto",
legendSummary = "none",
legendInteraction = "highlight",
maxVisibleSeries,
- syncId,
sync,
- subtleFill = false,
hideXAxisLabels = false,
-}) => {
- const [selfHovered, setSelfHovered] = useState(false);
+}: Omit<ChartProps, "subtleFill">) {
const groupedData = useMemo(() => groupDataByTimeDimension(data), [data]);
- const allDimensions = useMemo(() => getUniqueDimensions(data), [data]);
- // Cap how many series we draw (data -> preparer seam): a high-cardinality
- // breakdown of hundreds of series is both unreadable and slow to hover. (LFE-10549)
- const series = useMemo(
- () => prepareVisibleSeries(data, allDimensions),
- [data, allDimensions],
+ const dimensions = useMemo(() => getUniqueDimensions(data), [data]);
+ const visibleSeries = useMemo(
+ () => prepareVisibleSeries(data, dimensions),
+ [data, dimensions],
);
- const dimensions = series.visible;
- const { ref: containerRef, maxTicks } = useChartTickBudget();
- const chartBoxRef = useRef<HTMLDivElement>(null);
const timeAxis = useMemo(
() =>
prepareTimeAxis(
- groupedData.map((d) => d.time_dimension),
- maxTicks,
- { hideCategoryTickLabels: hideXAxisLabels },
+ groupedData.map((datum) => datum.time_dimension),
+ undefined,
+ {
+ hideCategoryTickLabels: hideXAxisLabels,
+ },
),
- [groupedData, maxTicks, hideXAxisLabels],
+ [groupedData, hideXAxisLabels],
);
-
- const { legendItems, onLegendClick, isRendered, isDimmed } = useSeriesLegend({
- data,
- dimensions,
- config,
- legendSummary,
- legendInteraction,
- maxVisibleSeries,
- });
-
const formatValue = (value: number) =>
toFullMetricString(metricFormatter(value, { style: "compact" }));
-
- const renderedDimensions = dimensions.filter(isRendered);
- const syncedIndex = groupedData.findIndex(
- (item) =>
- String(
- parseChartTimestamp(item.time_dimension)?.getTime() ??
- item.time_dimension,
- ) === sync?.activeKey,
- );
+ const chartData = groupedData.map((datum) => ({
+ key: String(datum.time_dimension ?? ""),
+ values: Object.fromEntries(
+ visibleSeries.visible.map((dimension) => [
+ dimension,
+ typeof datum[dimension] === "number" ? datum[dimension] : null,
+ ]),
+ ),
+ }));
+ const chartSeries = visibleSeries.visible.map((dimension, index) => ({
+ id: dimension,
+ label:
+ getPlainTextFromReactNode(config?.[dimension]?.label ?? dimension) ??
+ dimension,
+ color: seriesColor(index),
+ }));
+ let chartLegend: LineChartLegend = { visibility: "hidden" };
+ if (legendPosition !== "none" && legendInteraction === "toggle") {
+ chartLegend = {
+ visibility: legendPosition === "auto" ? "auto" : "visible",
+ interaction: "toggle",
+ summary: legendSummary,
+ maxVisibleSeries,
+ };
+ } else if (legendPosition !== "none") {
+ chartLegend = {
+ visibility: legendPosition === "auto" ? "auto" : "visible",
+ interaction: "highlight",
+ summary: legendSummary,
+ };
+ }
return (
- <div
- ref={containerRef}
- className="flex h-full w-full min-w-0 flex-col"
- // onMouseMove (not just onMouseEnter) so the tooltip un-gates even when the
- // cursor is already over the chart at mount/refresh (enter never fires). (LFE-10549)
- onMouseEnter={() => setSelfHovered(true)}
- onMouseMove={() => setSelfHovered(true)}
- onMouseLeave={() => {
- setSelfHovered(false);
- sync?.onActiveKeyChange(undefined);
- }}
- // Keyboard parity: recharts' accessibilityLayer lets Tab/arrow users move
- // the crosshair, but that fires no mouse event — un-gate the tooltip on
- // focus too, and re-gate only when focus leaves the chart. (LFE-10549)
- onFocus={() => setSelfHovered(true)}
- onBlur={(e) => {
- if (!e.currentTarget.contains(e.relatedTarget as Node | null)) {
- setSelfHovered(false);
- sync?.onActiveKeyChange(undefined);
- }
- }}
- >
- {series.total > dimensions.length && (
+ <div className="flex size-full min-w-0 flex-col">
+ {visibleSeries.total > visibleSeries.visible.length ? (
<SeriesOverflowNote
- visibleCount={dimensions.length}
- totalCount={series.total}
+ visibleCount={visibleSeries.visible.length}
+ totalCount={visibleSeries.total}
+ />
+ ) : null}
+ <div className="min-h-0 flex-1">
+ <StackedBarChart
+ data={chartData}
+ series={chartSeries}
+ legend={chartLegend}
+ valueFormatter={formatValue}
+ tickFormatter={(key) => timeAxis.formatTick(key)}
+ categoryXAxisLabels={timeAxis.mode === "category"}
+ tooltipFormatter={(key) => timeAxis.formatTooltip(key)}
+ hideXAxisLabels={hideXAxisLabels && timeAxis.mode === "category"}
+ sync={
+ sync
+ ? {
+ activeKey: chartData.find(
+ (_, index) =>
+ String(
+ parseChartTimestamp(
+ groupedData[index]?.time_dimension,
+ )?.getTime() ?? groupedData[index]?.time_dimension,
+ ) === sync.activeKey,
+ )?.key,
+ onActiveKeyChange: (key) =>
+ sync.onActiveKeyChange(
+ key === undefined
+ ? undefined
+ : String(parseChartTimestamp(key)?.getTime() ?? key),
+ ),
+ }
+ : undefined
+ }
/>
- )}
- <ChartContainer
- ref={chartBoxRef}
- 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={groupedData}
- syncId={syncId}
- syncMethod="value"
- onMouseMove={(state) => {
- if (state.activeLabel === undefined) return;
- sync?.onActiveKeyChange(
- String(
- parseChartTimestamp(state.activeLabel)?.getTime() ??
- state.activeLabel,
- ),
- );
- }}
- >
- {/* Horizontal only: y-gridlines make bar heights gaugeable like the
- line/area charts; the bars themselves already mark the x-rhythm,
- so vertical lines would only add noise between them. (LFE-10576) */}
- <CartesianGrid
- stroke="hsl(var(--chart-grid))"
- vertical={false}
- syncWithTicks
- />
- <XAxis
- dataKey="time_dimension"
- stroke="hsl(var(--chart-grid))"
- fontSize={12}
- tickLine={false}
- axisLine={false}
- interval={timeAxis.interval}
- tickFormatter={timeAxis.formatTick}
- {...timeAxis.tickProps}
- {...temporalAxisTickProp(
- timeAxis,
- groupedData.at(-1)?.time_dimension,
- )}
- />
- <YAxis
- type="number"
- stroke="hsl(var(--chart-grid))"
- fontSize={12}
- tickLine={false}
- axisLine={false}
- niceTicks="auto"
- tickFormatter={(value) => formatValue(Number(value))}
- />
- {dimensions.map((dimension, index) => {
- if (!isRendered(dimension)) return null;
- const muted = isDimmed(dimension);
- return (
- <Bar
- key={dimension}
- dataKey={dimension}
- stroke={seriesColor(index)}
- strokeOpacity={muted ? 0.2 : 1}
- fill={seriesColor(index)}
- fillOpacity={muted ? 0.2 : subtleFill ? 0.3 : 1}
- stackId={renderedDimensions.length > 1 ? "stack" : undefined}
- isAnimationActive={false}
- />
- );
- })}
- <ChartActiveReferenceLine />
- <ChartTooltip
- active={syncedIndex >= 0 ? true : undefined}
- defaultIndex={syncedIndex >= 0 ? syncedIndex : undefined}
- cursor={false}
- content={({ active, payload, label, coordinate }) =>
- // Synced siblings show only the crosshair; the tooltip is the
- // hovered chart's, portaled out of the chart frame. (LFE-10549)
- selfHovered ? (
- <ChartTooltipPortal
- active={active}
- coordinate={coordinate}
- anchorRef={chartBoxRef}
- >
- <ChartTooltipContent
- active={active}
- payload={payload}
- label={label}
- labelFormatter={(value) => timeAxis.formatTooltip(value)}
- valueFormatter={formatValue}
- sortPayloadByValue="desc"
- />
- </ChartTooltipPortal>
- ) : null
- }
- />
- </BarChart>
- </ChartContainer>
- {legendItems.length > 0 &&
- (legendPosition === "below" ||
- (legendPosition === "auto" && legendItems.length > 1)) && (
- <TimeSeriesLegend
- items={legendItems}
- interaction={legendInteraction}
- onItemClick={onLegendClick}
- formatSummary={formatValue}
- />
- )}
+ </div>
</div>
);
-};
+}
diff --git a/web/src/features/widgets/chart-library/chart-props.ts b/web/src/features/widgets/chart-library/chart-props.ts
index 92da9fc536..1ca4ca7ea8 100644
--- a/web/src/features/widgets/chart-library/chart-props.ts
+++ b/web/src/features/widgets/chart-library/chart-props.ts
@@ -124,9 +124,8 @@ export interface ChartProps {
*/
maxVisibleSeries?: number;
/**
- * Shared sync group: charts on the same dashboard timeline that pass the same
- * `syncId` show a synced hover crosshair + tooltip — hovering one moves the
- * vertical time marker on all of them. (LFE-10549)
+ * Recharts sync group for chart types that still use Recharts. Design-system
+ * charts use `sync` to share their active key instead. (LFE-10549)
*/
syncId?: string;
sync?: {
diff --git a/web/src/features/widgets/components/DashboardGrid.tsx b/web/src/features/widgets/components/DashboardGrid.tsx
index 0571a67395..3949ea2ec6 100644
--- a/web/src/features/widgets/components/DashboardGrid.tsx
+++ b/web/src/features/widgets/components/DashboardGrid.tsx
@@ -199,6 +199,7 @@ export function DashboardGrid({
widget.type === "preset" ? (
<PresetDashboardWidget
dashboardId={dashboardId}
+ chartSync={chartSync}
projectId={projectId}
readPath={readPath}
placement={widget}
diff --git a/web/src/features/widgets/components/PresetDashboardWidget.tsx b/web/src/features/widgets/components/PresetDashboardWidget.tsx
index 2eac2fe502..6556d51723 100644
--- a/web/src/features/widgets/components/PresetDashboardWidget.tsx
+++ b/web/src/features/widgets/components/PresetDashboardWidget.tsx
@@ -39,6 +39,7 @@ export interface PresetPlacement {
export function PresetDashboardWidget({
projectId,
dashboardId,
+ chartSync,
readPath,
placement,
dateRange,
@@ -53,6 +54,10 @@ export function PresetDashboardWidget({
}: {
projectId: string;
dashboardId: string;
+ chartSync: {
+ activeKey: string | undefined;
+ onActiveKeyChange: (key: string | undefined) => void;
+ };
/** Resolved by the page controller — the card must not guess the version. */
readPath: ResolvedReadPath;
placement: PresetPlacement;
@@ -163,12 +168,14 @@ export function PresetDashboardWidget({
metricsVersion,
schedulerId,
syncId: dashboardId,
+ sync: chartSync,
// Fixed presets need a definite height so their flex children can grow.
// Score Analytics is measured because each selected score adds a row.
className: heightBehavior.mode === "content" ? "min-h-full" : "h-full",
};
}, [
dashboardId,
+ chartSync,
dateRange,
filterState,
heightBehavior.mode,