Skip to content

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

refactor(web): Create design-system LineChart (#17782)

Ben Bachem76b25572e8bc
diff --git a/web/src/components/design-system/charts/ChartLegend.tsx b/web/src/components/design-system/charts/ChartLegend.tsx
new file mode 100644
index 0000000000..7457cae08b
--- /dev/null
+++ b/web/src/components/design-system/charts/ChartLegend.tsx
@@ -0,0 +1,250 @@
+"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>
+ );
+}
diff --git a/web/src/components/design-system/charts/ChartTooltip.stories.tsx b/web/src/components/design-system/charts/ChartTooltip.stories.tsx
new file mode 100644
index 0000000000..b7913c2065
--- /dev/null
+++ b/web/src/components/design-system/charts/ChartTooltip.stories.tsx
@@ -0,0 +1,218 @@
+import { type ComponentProps } from "react";
+import preview from "../../../../.storybook/preview";
+import { expect, userEvent, within } from "storybook/test";
+
+import { ChartTooltip } from "./ChartTooltip";
+
+type ChartTooltipController = Parameters<
+ ComponentProps<typeof ChartTooltip>["children"]
+>[0];
+
+type ChartTooltipDemoProps = {
+ data: Parameters<ChartTooltipController["getReferenceProps"]>[0];
+};
+
+function ChartTooltipDemo({ data }: ChartTooltipDemoProps) {
+ return (
+ <ChartTooltip>
+ {({ activeIndex, getReferenceProps }) => (
+ <svg
+ viewBox="0 0 480 240"
+ className="h-full w-full"
+ aria-label="Tooltip story chart"
+ >
+ <rect
+ x="120"
+ y="60"
+ width="240"
+ height="120"
+ rx="12"
+ fill={activeIndex === data.index ? "#6366f1" : "#a5b4fc"}
+ className="outline-hidden focus-visible:outline-2 focus-visible:outline-offset-2"
+ role="graphics-symbol"
+ tabIndex={0}
+ aria-label="Tooltip trigger"
+ {...getReferenceProps(data)}
+ />
+ </svg>
+ )}
+ </ChartTooltip>
+ );
+}
+
+async function focusTooltip(canvasElement: HTMLElement) {
+ const canvas = within(canvasElement);
+ canvas.getByLabelText("Tooltip trigger").focus();
+ return within(canvasElement.ownerDocument.body).findByRole("tooltip");
+}
+
+const itemsData: ChartTooltipDemoProps["data"] = {
+ type: "items",
+ index: 0,
+ items: [
+ { id: "api", label: "API", value: "$18.42", color: "#6366f1" },
+ { id: "worker", label: "Worker", value: "$12.08", color: "#06b6d4" },
+ ],
+};
+
+const meta = preview.meta({
+ component: ChartTooltipDemo,
+ parameters: { layout: "fullscreen" },
+ args: {
+ data: itemsData,
+ },
+ decorators: [
+ (Story) => (
+ <div className="h-dvh w-full p-8">
+ <Story />
+ </div>
+ ),
+ ],
+});
+
+export const Items = meta.story({
+ name: "(Test) Items",
+ args: { data: itemsData },
+ play: async ({ canvasElement }) => {
+ const tooltip = await focusTooltip(canvasElement);
+ await expect(tooltip).toHaveTextContent("API");
+ await expect(tooltip).toHaveTextContent("$18.42");
+ await expect(tooltip.querySelectorAll("rect")).toHaveLength(2);
+ },
+});
+
+export const WithHeading = meta.story({
+ name: "(Test) With Heading",
+ args: {
+ data: {
+ type: "items",
+ index: 0,
+ heading: "September 22, 2026",
+ items: [
+ { id: "api", label: "API", value: "1,240", color: "#6366f1" },
+ { id: "worker", label: "Worker", value: "830", color: "#06b6d4" },
+ ],
+ },
+ },
+ play: async ({ canvasElement }) => {
+ const tooltip = await focusTooltip(canvasElement);
+ await expect(tooltip).toHaveTextContent("September 22, 2026");
+ },
+});
+
+export const Emphasis = meta.story({
+ name: "(Test) Emphasis",
+ args: {
+ data: {
+ type: "items",
+ index: 0,
+ emphasizedItemId: "emphasized",
+ items: [
+ {
+ id: "emphasized",
+ label: "Emphasized",
+ value: "82",
+ color: "#6366f1",
+ },
+ {
+ id: "dimmed-a",
+ label: "Dimmed",
+ value: "12",
+ color: "#f59e0b",
+ },
+ {
+ id: "dimmed-b",
+ label: "Also dimmed",
+ value: "8",
+ color: "#06b6d4",
+ },
+ ],
+ },
+ },
+ play: async ({ canvasElement }) => {
+ const tooltip = await focusTooltip(canvasElement);
+ await expect(
+ within(tooltip).getByText("Dimmed").closest(".opacity-30"),
+ ).toBeInTheDocument();
+ },
+});
+
+export const Primary = meta.story({
+ name: "(Test) Primary",
+ args: {
+ data: {
+ type: "primary",
+ index: 0,
+ label: "Claude Sonnet",
+ value: "31 (31%)",
+ color: "#6366f1",
+ },
+ },
+ play: async ({ canvasElement }) => {
+ const tooltip = await focusTooltip(canvasElement);
+ await expect(tooltip).toHaveTextContent("Claude Sonnet");
+ await expect(tooltip).toHaveTextContent("31 (31%)");
+ },
+});
+
+export const PrimaryWithDetails = meta.story({
+ name: "(Test) Primary With Details",
+ args: {
+ data: {
+ type: "primary",
+ index: 0,
+ heading: "Other",
+ label: "Combined slices",
+ value: "8 (8%)",
+ color: "#6366f1",
+ details: [
+ { label: "Small model", value: "5 (5%)" },
+ { label: "Legacy model", value: "3 (3%)" },
+ ],
+ },
+ },
+ play: async ({ canvasElement }) => {
+ const tooltip = await focusTooltip(canvasElement);
+ await expect(tooltip).toHaveTextContent("Combined slices");
+ await expect(tooltip).toHaveTextContent("Small model");
+ await expect(tooltip).toHaveTextContent("Legacy model");
+ await expect(within(tooltip).getByRole("separator")).toBeInTheDocument();
+ },
+});
+
+export const LongContent = meta.story({
+ name: "(Test) Long Content",
+ args: {
+ data: {
+ type: "items",
+ index: 0,
+ heading: "A deliberately long heading for a dense chart tooltip",
+ items: [
+ {
+ id: "long-model",
+ label: "A model name that is intentionally long enough to truncate",
+ value: "$1,234,567.890123",
+ color: "#6366f1",
+ },
+ ],
+ },
+ },
+ play: async ({ canvasElement }) => {
+ const tooltip = await focusTooltip(canvasElement);
+ await expect(tooltip).toBeVisible();
+ },
+});
+
+export const PointerHover = meta.story({
+ name: "(Test) Pointer Hover",
+ args: { data: itemsData },
+ play: async ({ canvasElement }) => {
+ const canvas = within(canvasElement);
+ await userEvent.hover(canvas.getByLabelText("Tooltip trigger"));
+
+ const tooltip = await within(canvasElement.ownerDocument.body).findByRole(
+ "tooltip",
+ );
+ await expect(tooltip).toBeVisible();
+ },
+});
diff --git a/web/src/components/design-system/charts/ChartTooltip.tsx b/web/src/components/design-system/charts/ChartTooltip.tsx
index 78bd782ac3..211cf1f2f1 100644
--- a/web/src/components/design-system/charts/ChartTooltip.tsx
+++ b/web/src/components/design-system/charts/ChartTooltip.tsx
@@ -10,6 +10,7 @@ import {
useFloating,
} from "@floating-ui/react";
import {
+ Fragment,
useLayoutEffect,
useState,
type FocusEvent,
@@ -19,18 +20,43 @@ import {
import { useLayerContainer } from "@/src/context/LayerContext/LayerContext";
+type TooltipItem = {
+ label: string;
+ value: string;
+ color?: string;
+};
+
+type TooltipData = {
+ index: number;
+ heading?: string;
+ focusPoint?: { x: number; y: number };
+} & (
+ | {
+ type: "items";
+ items: Array<TooltipItem & { id: string; color: string }>;
+ emphasizedItemId?: string;
+ label?: never;
+ value?: never;
+ color?: never;
+ details?: never;
+ }
+ | {
+ type: "primary";
+ items?: never;
+ label: string;
+ value: string;
+ color: string;
+ details?: Array<Omit<TooltipItem, "color">>;
+ emphasizedItemId?: never;
+ }
+);
+
export function ChartTooltip({
children,
}: {
children: (controller: {
activeIndex: number | undefined;
- getReferenceProps: (data: {
- index: number;
- label: string;
- value: string;
- color: string;
- details?: { label: string; value: string }[];
- }) => {
+ getReferenceProps: (data: TooltipData) => {
onPointerEnter: (event: PointerEvent<SVGElement>) => void;
onPointerMove: (event: PointerEvent<SVGElement>) => void;
onPointerLeave: () => void;
@@ -39,16 +65,13 @@ export function ChartTooltip({
};
}) => ReactNode;
}) {
- const [activeTooltip, setActiveTooltip] = useState<{
- index: number;
- label: string;
- value: string;
- color: string;
- details?: { label: string; value: string }[];
- reference: SVGElement;
- clientPoint?: { x: number; y: number };
- placement: "left" | "right";
- }>();
+ const [activeTooltip, setActiveTooltip] = useState<
+ TooltipData & {
+ reference: SVGElement;
+ clientPoint?: { x: number; y: number };
+ placement: "left" | "right";
+ }
+ >();
useLayoutEffect(() => {
if (activeTooltip && !activeTooltip.reference.isConnected) {
@@ -71,13 +94,7 @@ export function ChartTooltip({
y: activeTooltip?.clientPoint?.y,
});
- const getReferenceProps = (data: {
- index: number;
- label: string;
- value: string;
- color: string;
- details?: { label: string; value: string }[];
- }) => {
+ const getReferenceProps = (data: TooltipData) => {
const showAtPointer = (event: PointerEvent<SVGElement>) => {
const { clientX, clientY, currentTarget } = event;
const chartBounds =
@@ -99,15 +116,28 @@ export function ChartTooltip({
onPointerLeave: () => setActiveTooltip(undefined),
onFocus: (event: FocusEvent<SVGElement>) => {
const sliceBounds = event.currentTarget.getBoundingClientRect();
- const chartBounds =
- event.currentTarget.ownerSVGElement?.getBoundingClientRect();
+ const svg = event.currentTarget.ownerSVGElement;
+ const chartBounds = svg?.getBoundingClientRect();
+ const focusPoint = svg?.createSVGPoint();
+ if (focusPoint && data.focusPoint) {
+ focusPoint.x = data.focusPoint.x;
+ focusPoint.y = data.focusPoint.y;
+ }
+ const screenMatrix = svg?.getScreenCTM();
+ const transformedFocusPoint =
+ focusPoint && data.focusPoint && screenMatrix
+ ? focusPoint.matrixTransform(screenMatrix)
+ : undefined;
+ const referenceX =
+ transformedFocusPoint?.x ?? sliceBounds.left + sliceBounds.width / 2;
setActiveTooltip({
...data,
reference: event.currentTarget,
+ clientPoint: transformedFocusPoint
+ ? { x: transformedFocusPoint.x, y: transformedFocusPoint.y }
+ : undefined,
placement:
- chartBounds &&
- sliceBounds.left + sliceBounds.width / 2 <
- chartBounds.left + chartBounds.width / 2
+ chartBounds && referenceX < chartBounds.left + chartBounds.width / 2
? "left"
: "right",
});
@@ -116,6 +146,41 @@ export function ChartTooltip({
};
};
+ const tooltipRows: Array<
+ TooltipItem & {
+ id: string;
+ emphasis: "default" | "emphasized" | "dimmed";
+ kind: "peer" | "primary" | "detail";
+ }
+ > = [];
+ if (activeTooltip?.type === "items") {
+ for (const item of activeTooltip.items) {
+ let emphasis: "default" | "emphasized" | "dimmed" = "dimmed";
+ if (activeTooltip.emphasizedItemId === undefined) emphasis = "default";
+ else if (activeTooltip.emphasizedItemId === item.id) {
+ emphasis = "emphasized";
+ }
+ tooltipRows.push({ ...item, emphasis, kind: "peer" });
+ }
+ } else if (activeTooltip?.type === "primary") {
+ tooltipRows.push({
+ id: "primary",
+ label: activeTooltip.label,
+ value: activeTooltip.value,
+ color: activeTooltip.color,
+ emphasis: "default",
+ kind: "primary",
+ });
+ tooltipRows.push(
+ ...(activeTooltip.details ?? []).map((item, index) => ({
+ ...item,
+ id: `detail-${index}`,
+ emphasis: "default" as const,
+ kind: "detail" as const,
+ })),
+ );
+ }
+
return (
<>
{children({ activeIndex: activeTooltip?.index, getReferenceProps })}
@@ -127,46 +192,46 @@ export function ChartTooltip({
className="border-border/50 bg-background pointer-events-none z-50 grid min-w-32 gap-1.5 rounded-lg border px-2.5 py-1.5 text-xs shadow-xl"
style={floatingStyles}
>
- <div className="flex items-center gap-2">
- <svg
- viewBox="0 0 10 10"
- className="size-2.5 shrink-0"
- aria-hidden="true"
- >
- <rect
- width="10"
- height="10"
- rx="2"
- fill={activeTooltip.color}
- />
- </svg>
- <div className="flex min-w-0 flex-1 items-center justify-between gap-x-3 leading-tight">
- <span
- className="text-muted-foreground truncate"
- title={activeTooltip.label}
- >
- {activeTooltip.label}
- </span>
- <span className="text-foreground shrink-0 font-mono font-bold whitespace-nowrap tabular-nums">
- {activeTooltip.value}
- </span>
+ {activeTooltip.heading ? (
+ <div className="text-foreground font-bold">
+ {activeTooltip.heading}
</div>
- </div>
- {activeTooltip.details?.map((detail, index) => (
- <div
- key={`${detail.label}-${index}`}
- className="flex min-w-0 items-center justify-between gap-x-3 pl-4 leading-tight"
- >
- <span
- className="text-muted-foreground truncate"
- title={detail.label}
+ ) : null}
+ {tooltipRows.map((item, index) => (
+ <Fragment key={item.id}>
+ {item.kind === "detail" &&
+ tooltipRows[index - 1]?.kind !== "detail" ? (
+ <div role="separator" className="border-border/50 border-t" />
+ ) : null}
+ <div
+ className={`flex min-w-0 items-center gap-2 leading-tight transition-opacity duration-150 ${item.emphasis === "dimmed" ? "opacity-30" : "opacity-100"}`}
>
- {detail.label}
- </span>
- <span className="text-foreground shrink-0 font-mono whitespace-nowrap tabular-nums">
- {detail.value}
- </span>
- </div>
+ {item.kind !== "detail" ? (
+ <svg
+ viewBox="0 0 10 10"
+ className="size-2.5 shrink-0"
+ aria-hidden="true"
+ >
+ <rect width="10" height="10" rx="2" fill={item.color} />
+ </svg>
+ ) : (
+ <span className="w-2.5 shrink-0" />
+ )}
+ <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`}
+ title={item.label}
+ >
+ {item.label}
+ </span>
+ <span
+ className={`text-foreground shrink-0 font-mono whitespace-nowrap tabular-nums ${item.kind === "detail" ? "" : "font-bold"}`}
+ >
+ {item.value}
+ </span>
+ </div>
+ </div>
+ </Fragment>
))}
</div>
</FloatingPortal>
diff --git a/web/src/components/design-system/charts/LineChart/LineChart.stories.tsx b/web/src/components/design-system/charts/LineChart/LineChart.stories.tsx
new file mode 100644
index 0000000000..0512b9e9e3
--- /dev/null
+++ b/web/src/components/design-system/charts/LineChart/LineChart.stories.tsx
@@ -0,0 +1,326 @@
+import preview from "../../../../../.storybook/preview";
+import { expect, userEvent, waitFor, within } from "storybook/test";
+import {
+ LineChart,
+ type LineChartLegend,
+ type LineChartSeries,
+ type LineChartThreshold,
+} from "./LineChart";
+
+type LineChartStoryProps = {
+ legend?: LineChartLegend;
+ thresholds?: LineChartThreshold[];
+ variant?:
+ | "default"
+ | "empty"
+ | "many-lines"
+ | "boundary-points"
+ | "category-short-labels"
+ | "category-long-labels"
+ | "category-hidden-labels";
+};
+
+const LineChartDemo = (props: LineChartStoryProps) => {
+ if (
+ props.variant === "category-short-labels" ||
+ props.variant === "category-long-labels" ||
+ props.variant === "category-hidden-labels"
+ ) {
+ let categoryChartData = categoryData;
+ if (props.variant === "category-short-labels") {
+ categoryChartData = shortCategoryData;
+ }
+ return (
+ <LineChart
+ data={categoryChartData}
+ series={categorySeries}
+ xAxis={{
+ type: "category",
+ labels:
+ props.variant === "category-hidden-labels" ? "hidden" : "visible",
+ }}
+ />
+ );
+ }
+
+ let chartData: Array<{
+ x: Date;
+ values: Record<string, number | null>;
+ }> = data;
+ if (props.variant === "many-lines") chartData = manyLinesData;
+ if (props.variant === "boundary-points") chartData = boundaryPointData;
+ if (props.variant === "empty") chartData = [];
+ const chartSeries = props.variant === "many-lines" ? manyLinesSeries : series;
+
+ return (
+ <LineChart
+ data={chartData}
+ series={chartSeries}
+ legend={props.legend}
+ valueFormatter={(value) => `$${value.toFixed(2)}`}
+ thresholds={props.thresholds}
+ showDataPointDots={props.variant === "boundary-points"}
+ xAxis={{
+ type: "time",
+ tickFormatter: (value) =>
+ value.toLocaleDateString(undefined, {
+ month: "short",
+ day: "numeric",
+ timeZone: "UTC",
+ }),
+ }}
+ />
+ );
+};
+
+const series = [
+ { id: "api", label: "API", color: "#3a3dee" },
+ { id: "worker", label: "Worker", color: "#07b9d5" },
+];
+
+const data = Array.from({ length: 14 }, (_, index) => ({
+ x: new Date(Date.UTC(2026, 8, index + 1)),
+ values: {
+ api: 18 + index * 2 + Math.sin(index) * 8,
+ worker: index === 7 ? null : 42 - index + Math.cos(index) * 6,
+ },
+}));
+
+const boundaryPointData = [
+ { x: new Date(Date.UTC(2026, 8, 1)), values: { api: 0, worker: null } },
+ { x: new Date(Date.UTC(2026, 8, 2)), values: { api: 100, worker: null } },
+];
+
+const manyLinesSeries: LineChartSeries[] = Array.from(
+ { length: 24 },
+ (_, index) => ({
+ id: `series-${index + 1}`,
+ label: `Series ${index + 1}`,
+ color: `hsl(${Math.round((index / 24) * 360)} 70% 50%)`,
+ }),
+);
+
+const manyLinesData = Array.from({ length: 30 }, (_, pointIndex) => ({
+ x: new Date(Date.UTC(2026, 8, pointIndex + 1)),
+ values: Object.fromEntries(
+ manyLinesSeries.map((item, seriesIndex) => [
+ item.id,
+ 50 +
+ Math.sin(pointIndex / 2 + seriesIndex) * 18 +
+ Math.cos(pointIndex / 5 + seriesIndex * 0.7) * 12 +
+ seriesIndex * 2,
+ ]),
+ ),
+}));
+
+const categoryData = Array.from({ length: 6 }, (_, index) => ({
+ x: `production-evaluation-run-${index + 1}-with-a-long-name`,
+ values: { cost: 20 + index * 8 },
+}));
+
+const shortCategoryData = Array.from({ length: 6 }, (_, index) => ({
+ x: `Run ${index + 1}`,
+ values: { cost: 20 + index * 8 },
+}));
+
+const categorySeries: LineChartSeries[] = [
+ { id: "cost", label: "Cost", color: "#3a3dee" },
+];
+
+const meta = preview.meta({
+ component: LineChartDemo,
+ parameters: { layout: "fullscreen" },
+ args: {},
+ decorators: [
+ (Story) => (
+ <div className="h-dvh w-full">
+ <Story />
+ </div>
+ ),
+ ],
+});
+
+export const Default = meta.story({});
+
+export const BoundaryPoints = meta.story({
+ name: "(Test) Boundary Points",
+ args: { variant: "boundary-points" },
+ play: async ({ canvasElement }) => {
+ const points = canvasElement.querySelectorAll<SVGCircleElement>(
+ 'circle[fill="#3a3dee"][r="4"]',
+ );
+ 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,
+ );
+ }
+ },
+});
+
+export const Empty = meta.story({
+ name: "(Test) Empty",
+ args: { variant: "empty" },
+ play: async ({ canvasElement }) => {
+ const canvas = within(canvasElement);
+
+ await expect(
+ canvas.getByRole("group", { name: "Line chart" }),
+ ).toBeVisible();
+ await expect(canvas.queryAllByRole("graphics-symbol")).toHaveLength(0);
+ },
+});
+
+export const ManyLines = meta.story({
+ args: { variant: "many-lines" },
+});
+
+export const ManyLegendEntries = meta.story({
+ name: "(Test) Many Legend Entries",
+ args: {
+ variant: "many-lines",
+ legend: {
+ visibility: "visible",
+ interaction: "toggle",
+ summary: "sum",
+ },
+ },
+ play: async ({ canvasElement }) => {
+ const canvas = within(canvasElement);
+ const firstPoint = canvas.getAllByRole("graphics-symbol")[0];
+ if (!firstPoint) throw new Error("Data point not found");
+
+ firstPoint.focus();
+
+ await waitFor(() =>
+ expect(
+ canvasElement.querySelectorAll("[data-active-data-point]"),
+ ).toHaveLength(1),
+ );
+ },
+});
+
+export const WithLegend = meta.story({
+ args: {
+ legend: {
+ visibility: "visible",
+ interaction: "toggle",
+ summary: "sum",
+ },
+ },
+});
+
+export const WithThreshold = meta.story({
+ args: {
+ thresholds: [
+ {
+ value: 40,
+ color: "var(--color-red-600)",
+ label: "Budget",
+ region: "above",
+ },
+ ],
+ },
+});
+
+export const CategoryLongLabels = meta.story({
+ name: "(Test) Category Long Labels",
+ args: { variant: "category-long-labels" },
+ play: async ({ canvasElement }) => {
+ const firstInteractionArea = canvasElement.querySelector(
+ 'rect[fill="transparent"]',
+ );
+ if (!firstInteractionArea) throw new Error("Interaction area not found");
+
+ await userEvent.hover(firstInteractionArea);
+
+ const activeLabel = canvasElement.querySelector(
+ "[data-active-x-axis-label]",
+ );
+ await expect(activeLabel).toHaveTextContent(categoryData[0]?.x ?? "");
+ await expect(activeLabel).toHaveAttribute("font-weight", "700");
+ await expect(
+ canvasElement
+ .querySelector("[data-active-x-axis-label-background]")
+ ?.getAttribute("fill"),
+ ).toContain("url(#");
+
+ const renderedLabels = canvasElement.querySelectorAll(
+ "[data-x-axis-label]",
+ );
+ await expect(renderedLabels).toHaveLength(categoryData.length);
+ Array.from(renderedLabels)
+ .filter((label) => !label.hasAttribute("data-active-x-axis-label"))
+ .forEach((label) => {
+ expect(label).not.toHaveAttribute("transform");
+ expect(label.textContent).toMatch(/…$/);
+ });
+ await expect(
+ canvasElement.querySelectorAll("[data-category-tick]"),
+ ).toHaveLength(categoryData.length);
+
+ const tooltip = await within(canvasElement.ownerDocument.body).findByRole(
+ "tooltip",
+ );
+ await expect(tooltip).toHaveTextContent(categoryData[0]?.x ?? "");
+ },
+});
+
+export const CategoryShortLabels = meta.story({
+ name: "(Test) Category Short Labels",
+ args: { variant: "category-short-labels" },
+ play: async ({ canvasElement }) => {
+ const canvas = within(canvasElement);
+
+ shortCategoryData.forEach(({ x }) => {
+ expect(canvas.getByText(x)).not.toHaveAttribute("transform");
+ });
+ await expect(
+ canvasElement.querySelectorAll("[data-category-tick]"),
+ ).toHaveLength(shortCategoryData.length);
+ },
+});
+
+export const CategoryHiddenLabels = meta.story({
+ args: { variant: "category-hidden-labels" },
+});
+
+export const KeyboardFocus = meta.story({
+ name: "(Test) Keyboard Focus",
+ play: async ({ canvasElement }) => {
+ const canvas = within(canvasElement);
+ const firstPoint = canvas.getByLabelText(/2026.*API.*18/);
+
+ firstPoint.focus();
+
+ const activeLabel = await waitFor(() => {
+ const label = canvasElement.querySelector("[data-active-x-axis-label]");
+ expect(label).toHaveTextContent("Sep 1");
+ return label;
+ });
+ await expect(activeLabel).toHaveAttribute("font-weight", "700");
+ await expect(
+ canvasElement
+ .querySelector("[data-active-x-axis-label-background]")
+ ?.getAttribute("fill"),
+ ).toContain("url(#");
+
+ const tooltip = await within(canvasElement.ownerDocument.body).findByRole(
+ "tooltip",
+ );
+ await expect(tooltip).toHaveTextContent("API");
+ await expect(tooltip).toHaveTextContent("$18.00");
+
+ const firstTooltipLeft = tooltip.getBoundingClientRect().left;
+ const points = canvas.getAllByRole("graphics-symbol");
+ const nextPoint = points[points.indexOf(firstPoint) + 1];
+ await userEvent.tab();
+
+ await expect(nextPoint).toHaveFocus();
+ await waitFor(() =>
+ expect(tooltip.getBoundingClientRect().left).not.toBe(firstTooltipLeft),
+ );
+ },
+});
diff --git a/web/src/components/design-system/charts/LineChart/LineChart.tsx b/web/src/components/design-system/charts/LineChart/LineChart.tsx
new file mode 100644
index 0000000000..bfd59409ab
--- /dev/null
+++ b/web/src/components/design-system/charts/LineChart/LineChart.tsx
@@ -0,0 +1,974 @@
+"use client";
+
+import { useId, 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";
+
+type LineChartValues = {
+ values: Record<string, number | null>;
+};
+
+type TimeLineChartDatum = LineChartValues & { x: Date };
+type CategoryLineChartDatum = LineChartValues & { x: string };
+
+export type LineChartSeries = {
+ id: string;
+ label: string;
+ color: string;
+};
+
+type ConfiguredLineChartSeries = LineChartSeries & {
+ emphasis?: "default" | "dimmed" | "emphasized";
+};
+
+export type LineChartLegend =
+ | { visibility: "hidden" }
+ | ({
+ visibility: "auto" | "visible";
+ summary: "none" | "sum";
+ } & (
+ | { interaction: "highlight" }
+ | { interaction: "toggle"; maxVisibleSeries?: number }
+ ));
+
+export type LineChartThreshold = {
+ value: number;
+ color: string;
+ fillColor?: string;
+ label?: string;
+ region?: "above" | "below" | "equal" | "not-equal";
+ lineStyle?: "solid" | "dashed";
+};
+
+type CommonLineChartProps = {
+ series: LineChartSeries[];
+ valueFormatter?: (value: number) => string;
+ showDataPointDots?: boolean;
+ connectNulls?: boolean;
+ thresholds?: LineChartThreshold[];
+ ariaLabel?: string;
+ sync?: {
+ activeKey: string | undefined;
+ onActiveKeyChange: (key: string | undefined) => void;
+ };
+ legend?: LineChartLegend;
+};
+
+type LineChartProps = CommonLineChartProps &
+ (
+ | {
+ data: TimeLineChartDatum[];
+ xAxis: {
+ type: "time";
+ tickFormatter?: (value: Date) => string;
+ tooltipFormatter?: (value: Date) => string;
+ };
+ }
+ | {
+ data: CategoryLineChartDatum[];
+ xAxis: {
+ type: "category";
+ labels?: "visible" | "hidden";
+ tickFormatter?: (value: string) => string;
+ tooltipFormatter?: (value: string) => string;
+ };
+ }
+ );
+
+type NormalizedDatum = LineChartValues & {
+ key: string;
+ 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();
+
+const getSeriesSummaries = (
+ data: LineChartProps["data"],
+ series: LineChartSeries[],
+) =>
+ 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 > 0
+ ? values.reduce((total, value) => total + value, 0)
+ : null,
+ ] as const;
+ }),
+ );
+
+const getInitiallyHiddenSeriesIds = (
+ series: LineChartSeries[],
+ summaries: Map<string, number | null>,
+ legend: LineChartLegend | undefined,
+) => {
+ if (
+ legend?.visibility === "hidden" ||
+ legend?.interaction !== "toggle" ||
+ legend.maxVisibleSeries === undefined
+ ) {
+ return new Set<string>();
+ }
+ const ranked = [...series].sort(
+ (left, right) =>
+ (summaries.get(right.id) ?? -Infinity) -
+ (summaries.get(left.id) ?? -Infinity),
+ );
+ const visible = new Set(
+ ranked
+ .slice(0, Math.max(0, legend.maxVisibleSeries))
+ .map((item) => item.id),
+ );
+ return new Set(
+ series.flatMap((item) => (visible.has(item.id) ? [] : [item.id])),
+ );
+};
+
+function useLineChartLegend(
+ data: LineChartProps["data"],
+ series: LineChartSeries[],
+ legend: LineChartLegend | undefined,
+) {
+ const summaries = useMemo(
+ () => getSeriesSummaries(data, series),
+ [data, series],
+ );
+ const initialHidden = useMemo(
+ () => getInitiallyHiddenSeriesIds(series, summaries, legend),
+ [legend, series, summaries],
+ );
+ const legendInteraction =
+ legend?.visibility === "auto" || legend?.visibility === "visible"
+ ? legend.interaction
+ : "";
+ const maxVisibleSeries =
+ (legend?.visibility === "auto" || legend?.visibility === "visible") &&
+ legend.interaction === "toggle"
+ ? (legend.maxVisibleSeries ?? "")
+ : "";
+ const seedKey = `${legend?.visibility ?? "hidden"}|${legendInteraction}|${maxVisibleSeries}|${JSON.stringify(series.map((item) => item.id).sort())}`;
+ const [legendState, setLegendState] = useState({
+ seedKey,
+ highlightedSeriesId: undefined as string | undefined,
+ hiddenSeriesIds: initialHidden,
+ });
+ const effectiveLegendState =
+ legendState.seedKey === seedKey
+ ? legendState
+ : {
+ seedKey,
+ highlightedSeriesId: undefined,
+ hiddenSeriesIds: initialHidden,
+ };
+ const { highlightedSeriesId, hiddenSeriesIds } = effectiveLegendState;
+
+ const toggleSeries = (seriesId: string) => {
+ const next = new Set(hiddenSeriesIds);
+ if (next.has(seriesId)) next.delete(seriesId);
+ else next.add(seriesId);
+ setLegendState({ ...effectiveLegendState, hiddenSeriesIds: next });
+ };
+ const highlightSeries = (seriesId: string) => {
+ setLegendState({
+ ...effectiveLegendState,
+ highlightedSeriesId:
+ highlightedSeriesId === seriesId ? undefined : seriesId,
+ });
+ };
+ const setAllSeriesHidden = (hidden: boolean) => {
+ setLegendState({
+ ...effectiveLegendState,
+ hiddenSeriesIds: new Set(hidden ? series.map((item) => item.id) : []),
+ });
+ };
+ const configuredSeries: ConfiguredLineChartSeries[] = series.flatMap(
+ (item) => {
+ if (hiddenSeriesIds.has(item.id)) return [];
+ let emphasis: ConfiguredLineChartSeries["emphasis"] = "dimmed";
+ if (highlightedSeriesId === undefined) emphasis = "default";
+ else if (highlightedSeriesId === item.id) emphasis = "emphasized";
+ return [
+ {
+ ...item,
+ emphasis,
+ },
+ ];
+ },
+ );
+
+ return {
+ configuredSeries,
+ hiddenSeriesIds,
+ highlightedSeriesId,
+ highlightSeries,
+ summaries,
+ setAllSeriesHidden,
+ toggleSeries,
+ };
+}
+
+const normalizeLineChartData = (
+ data: LineChartProps["data"],
+ xAxisType: LineChartProps["xAxis"]["type"],
+) => {
+ if (xAxisType === "time") {
+ return data
+ .map((datum) => ({
+ ...datum,
+ key: String(datum.x instanceof Date ? datum.x.getTime() : datum.x),
+ }))
+ .sort((left, right) => {
+ const leftTime = left.x instanceof Date ? left.x.getTime() : Number.NaN;
+ const rightTime =
+ right.x instanceof Date ? right.x.getTime() : Number.NaN;
+ return leftTime - rightTime;
+ });
+ }
+ return data.map((datum) => ({
+ ...datum,
+ key: String(datum.x),
+ }));
+};
+
+const getThresholdRegions = (
+ threshold: LineChartThreshold,
+ y: number,
+ plotHeight: number,
+) => {
+ const epsilon = Math.max(plotHeight * 0.01, 2);
+ if (threshold.region === "above") return [[TOP_MARGIN, y - TOP_MARGIN]];
+ if (threshold.region === "below") {
+ return [[y, TOP_MARGIN + 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],
+ ];
+ }
+ return [];
+};
+
+export function LineChart(props: LineChartProps) {
+ const {
+ data,
+ series,
+ valueFormatter = defaultValueFormatter,
+ legend,
+ } = props;
+ const [activeSeriesId, setActiveSeriesId] = useState<string>();
+ const {
+ configuredSeries,
+ hiddenSeriesIds,
+ highlightedSeriesId,
+ highlightSeries,
+ summaries,
+ setAllSeriesHidden,
+ toggleSeries,
+ } = useLineChartLegend(data, series, legend);
+ const showLegend =
+ legend?.visibility === "visible" ||
+ (legend?.visibility === "auto" && series.length > 1);
+
+ return (
+ <div className="flex size-full min-w-0 flex-col">
+ <div className="min-h-0 flex-1">
+ <ChartContainer>
+ {({ width, height }) => (
+ <LineChartContent
+ {...props}
+ series={configuredSeries}
+ onActiveSeriesChange={setActiveSeriesId}
+ width={width}
+ height={height}
+ />
+ )}
+ </ChartContainer>
+ </div>
+ {showLegend ? (
+ <ChartLegend
+ selectionActions={
+ legend.interaction === "toggle"
+ ? {
+ allSelected: hiddenSeriesIds.size === 0,
+ onSelectAll: () => setAllSeriesHidden(false),
+ onDeselectAll: () => setAllSeriesHidden(true),
+ }
+ : undefined
+ }
+ items={series.map((item) => {
+ const hidden = hiddenSeriesIds.has(item.id);
+ const focused = highlightedSeriesId === 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";
+ return {
+ id: item.id,
+ label: item.label,
+ color: item.color,
+ value:
+ legend.summary === "sum" && summaries.get(item.id) !== null
+ ? {
+ label: "Sum",
+ value: valueFormatter(summaries.get(item.id) ?? 0),
+ }
+ : undefined,
+ muted:
+ hidden ||
+ (activeSeriesId !== undefined
+ ? activeSeriesId !== item.id
+ : legend.interaction !== "toggle" &&
+ highlightedSeriesId !== undefined &&
+ !focused),
+ action: {
+ label,
+ pressed: legend.interaction === "toggle" ? !hidden : focused,
+ onClick: () => {
+ if (legend.interaction === "toggle") {
+ toggleSeries(item.id);
+ return;
+ }
+ highlightSeries(item.id);
+ },
+ },
+ };
+ })}
+ />
+ ) : null}
+ </div>
+ );
+}
+
+function LineChartContent(
+ props: Omit<LineChartProps, "series"> & {
+ series: ConfiguredLineChartSeries[];
+ onActiveSeriesChange: (seriesId: string | undefined) => void;
+ width: number;
+ height: number;
+ },
+) {
+ const {
+ series,
+ valueFormatter = defaultValueFormatter,
+ showDataPointDots = false,
+ connectNulls = false,
+ thresholds = [],
+ ariaLabel = "Line chart",
+ sync,
+ onActiveSeriesChange,
+ width,
+ height,
+ xAxis,
+ } = 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 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 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],
+ );
+ const timeScale = useMemo(() => {
+ const timestamps = data.map((datum) =>
+ datum.x instanceof Date ? datum.x.getTime() : Number.NaN,
+ );
+ let min = Math.min(...timestamps);
+ let max = Math.max(...timestamps);
+ if (!Number.isFinite(min) || !Number.isFinite(max)) {
+ min = 0;
+ max = 1;
+ }
+ return scaleUtc()
+ .domain([new Date(min), new Date(max)])
+ .range([LEFT_MARGIN, LEFT_MARGIN + plotWidth]);
+ }, [data, plotWidth]);
+ const getX = (datum: NormalizedDatum) =>
+ datum.x instanceof Date
+ ? timeScale(datum.x)
+ : (categoryScale(datum.key) ?? LEFT_MARGIN);
+ const getXFromKey = (key: string) =>
+ xAxis.type === "time"
+ ? 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;
+ const xTicks =
+ xAxis.type === "time"
+ ? [
+ ...(firstX instanceof Date ? [firstX] : []),
+ ...timeScale.ticks(Math.max(0, maxXTicks - 2)).filter((value) => {
+ const x = timeScale(value);
+ return (
+ x - LEFT_MARGIN >= APPROX_TIME_TICK_WIDTH &&
+ LEFT_MARGIN + plotWidth - x >= APPROX_TIME_TICK_WIDTH
+ );
+ }),
+ ...(lastX instanceof Date ? [lastX] : []),
+ ]
+ .filter(
+ (value, index, ticks) =>
+ ticks.findIndex(
+ (candidate) => candidate.getTime() === value.getTime(),
+ ) === index,
+ )
+ .sort((left, right) => left.getTime() - right.getTime())
+ .map((value) => ({
+ key: String(value.getTime()),
+ 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,
+ };
+ });
+ const activeKey =
+ hoveredIndex === undefined ? sync?.activeKey : data[hoveredIndex]?.key;
+ const activeDatum = data.find((datum) => datum.key === activeKey);
+ const formatXAxisTick = (datum: NormalizedDatum) => {
+ if (xAxis.type === "time" && datum.x instanceof Date) {
+ return xAxis.tickFormatter?.(datum.x) ?? datum.x.toLocaleDateString();
+ }
+ if (xAxis.type === "category" && typeof datum.x === "string") {
+ return xAxis.tickFormatter?.(datum.x) ?? datum.x;
+ }
+ return String(datum.x);
+ };
+ const activeXAxisTick = activeDatum
+ ? {
+ key: activeDatum.key,
+ x: getX(activeDatum),
+ label: formatXAxisTick(activeDatum),
+ }
+ : undefined;
+ const visibleXTicks = activeXAxisTick
+ ? [
+ ...xTicks.filter((tick) => tick.key !== activeXAxisTick.key),
+ activeXAxisTick,
+ ].sort((left, right) => left.x - right.x)
+ : xTicks;
+ const formatXTooltip = (datum: NormalizedDatum) => {
+ if (xAxis.type === "time" && datum.x instanceof Date) {
+ return xAxis.tooltipFormatter?.(datum.x) ?? datum.x.toLocaleString();
+ }
+ if (xAxis.type === "category" && typeof datum.x === "string") {
+ return xAxis.tooltipFormatter?.(datum.x) ?? datum.x;
+ }
+ return String(datum.x);
+ };
+ const lineGenerator = line<NormalizedDatum>()
+ .x((datum: NormalizedDatum) => getX(datum))
+ .y((datum: NormalizedDatum) => yScale(Number(datum.values.__current)))
+ .defined(
+ (datum: NormalizedDatum) => typeof datum.values.__current === "number",
+ );
+
+ const findNearestSeries = (
+ event: PointerEvent<SVGRectElement>,
+ index: number,
+ ) => {
+ const svg = event.currentTarget.ownerSVGElement;
+ if (!svg) return;
+ const pointerY = event.clientY - svg.getBoundingClientRect().top;
+ let distance = Infinity;
+ let nearest: string[] = [];
+ for (const item of series) {
+ const value = data[index]?.values[item.id];
+ if (typeof value !== "number") continue;
+ const nextDistance = Math.abs(yScale(value) - pointerY);
+ if (nextDistance < distance - 1) {
+ distance = nextDistance;
+ nearest = [item.id];
+ } else if (Math.abs(nextDistance - distance) <= 1) {
+ nearest.push(item.id);
+ }
+ }
+ // Only emphasize an unambiguous nearby line. Empty space and overlapping
+ // lines retain equal emphasis rather than selecting an arbitrary series.
+ const nearestSeriesId =
+ distance <= SERIES_HOVER_DISTANCE && nearest.length === 1
+ ? nearest[0]
+ : undefined;
+ setHoveredSeriesId(nearestSeriesId);
+ if (!hasConfiguredEmphasis) onActiveSeriesChange(nearestSeriesId);
+ };
+ const hasConfiguredEmphasis = series.some(
+ (item) => item.emphasis && item.emphasis !== "default",
+ );
+ const configuredEmphasizedSeries = series.filter(
+ (item) => item.emphasis === "emphasized",
+ );
+ let activeSeriesId: string | undefined;
+ if (configuredEmphasizedSeries.length === 1) {
+ activeSeriesId = configuredEmphasizedSeries[0]?.id;
+ } else if (!hasConfiguredEmphasis) {
+ activeSeriesId = hoveredSeriesId;
+ }
+
+ if (width <= 0 || height <= 0 || plotWidth <= 0 || plotHeight <= 0) {
+ return <svg width={width} height={height} aria-hidden="true" />;
+ }
+
+ return (
+ <ChartTooltip>
+ {({ activeIndex, getReferenceProps }) => (
+ <svg
+ width={width}
+ height={height}
+ role="group"
+ aria-label={ariaLabel}
+ className="block overflow-visible"
+ >
+ <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);
+ return (
+ <g key={`${threshold.value}-${index}`}>
+ {regions.map(([regionY, regionHeight], regionIndex) => (
+ <rect
+ key={regionIndex}
+ x={LEFT_MARGIN}
+ y={regionY}
+ width={plotWidth}
+ height={Math.max(0, regionHeight)}
+ fill={threshold.fillColor ?? threshold.color}
+ opacity={0.14}
+ />
+ ))}
+ <line
+ x1={LEFT_MARGIN}
+ x2={LEFT_MARGIN + plotWidth}
+ y1={y}
+ y2={y}
+ stroke={threshold.color}
+ strokeWidth={1.5}
+ strokeDasharray={
+ threshold.lineStyle === "dashed" ? "4 4" : undefined
+ }
+ />
+ {threshold.label ? (
+ <text
+ x={LEFT_MARGIN + plotWidth - 4}
+ y={y - 4}
+ textAnchor="end"
+ fill={threshold.color}
+ fontSize={11}
+ >
+ {threshold.label}
+ </text>
+ ) : null}
+ </g>
+ );
+ })}
+
+ {series.map((item) => {
+ const proximityDimmed =
+ !hasConfiguredEmphasis &&
+ hoveredSeriesId !== undefined &&
+ hoveredSeriesId !== item.id;
+ const proximityEmphasized =
+ !hasConfiguredEmphasis && hoveredSeriesId === item.id;
+ const seriesData = data.map((datum) => ({
+ ...datum,
+ values: { __current: datum.values[item.id] ?? null },
+ }));
+ const path = connectNulls
+ ? lineGenerator(
+ seriesData.filter((datum) => datum.values.__current !== null),
+ )
+ : lineGenerator(seriesData);
+ return (
+ <g
+ key={item.id}
+ className="transition-opacity duration-150"
+ opacity={
+ item.emphasis === "dimmed" || proximityDimmed ? 0.2 : 1
+ }
+ >
+ <path
+ d={path ?? undefined}
+ fill="none"
+ stroke={item.color}
+ strokeWidth={
+ item.emphasis === "emphasized" || proximityEmphasized
+ ? 3.5
+ : 2.5
+ }
+ strokeLinejoin="round"
+ strokeLinecap="round"
+ />
+ {seriesData.map((datum, index) => {
+ const value = datum.values.__current;
+ if (typeof value !== "number") return null;
+ const previous = seriesData[index - 1]?.values.__current;
+ const next = seriesData[index + 1]?.values.__current;
+ const isolated = previous == null && next == null;
+ const active = activeIndex === index;
+ const activeForSeries =
+ active &&
+ (activeSeriesId === undefined ||
+ activeSeriesId === item.id);
+ if (!showDataPointDots && !isolated && !activeForSeries)
+ return null;
+ return (
+ <circle
+ key={datum.key}
+ data-active-data-point={activeForSeries ? "" : undefined}
+ cx={getX(datum)}
+ cy={yScale(value)}
+ r={activeForSeries ? 5 : 4}
+ fill={item.color}
+ pointerEvents="none"
+ />
+ );
+ })}
+ </g>
+ );
+ })}
+
+ {activeKey !== undefined ? (
+ <line
+ x1={getXFromKey(activeKey)}
+ x2={getXFromKey(activeKey)}
+ y1={TOP_MARGIN}
+ y2={TOP_MARGIN + plotHeight}
+ stroke="hsl(var(--foreground))"
+ strokeDasharray="3 3"
+ opacity={0.35}
+ pointerEvents="none"
+ />
+ ) : 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 =
+ index === 0
+ ? LEFT_MARGIN
+ : (getX(data[index - 1] ?? datum) + currentX) / 2;
+ const right =
+ index === data.length - 1
+ ? LEFT_MARGIN + plotWidth
+ : (currentX + getX(data[index + 1] ?? datum)) / 2;
+ const values = series
+ .flatMap((item) => {
+ const value = datum.values[item.id];
+ return typeof value === "number" ? [{ item, value }] : [];
+ })
+ .sort((left, right) => right.value - left.value);
+ const first = values[0];
+ if (!first) return null;
+ const heading = formatXTooltip(datum);
+ const tooltipItems = values.map(({ item, value }) => ({
+ id: item.id,
+ label: item.label,
+ value: valueFormatter(value),
+ color: item.color,
+ }));
+ const referenceProps = getReferenceProps({
+ type: "items",
+ index,
+ heading,
+ focusPoint: {
+ x: currentX,
+ y: TOP_MARGIN + plotHeight / 2,
+ },
+ emphasizedItemId:
+ series.find((item) => item.emphasis === "emphasized")?.id ??
+ (!hasConfiguredEmphasis ? hoveredSeriesId : undefined),
+ items: tooltipItems,
+ });
+ return (
+ <g key={datum.key}>
+ <rect
+ x={left}
+ y={TOP_MARGIN}
+ width={Math.max(1, right - left)}
+ height={plotHeight}
+ fill="transparent"
+ {...referenceProps}
+ onPointerEnter={(event) => {
+ setHoveredIndex(index);
+ sync?.onActiveKeyChange(datum.key);
+ referenceProps.onPointerEnter(event);
+ findNearestSeries(event, index);
+ }}
+ onPointerMove={(event) => {
+ setHoveredIndex(index);
+ sync?.onActiveKeyChange(datum.key);
+ referenceProps.onPointerMove(event);
+ findNearestSeries(event, index);
+ }}
+ onPointerLeave={() => {
+ setHoveredIndex(undefined);
+ setHoveredSeriesId(undefined);
+ onActiveSeriesChange(undefined);
+ sync?.onActiveKeyChange(undefined);
+ referenceProps.onPointerLeave();
+ }}
+ />
+ {values.map(({ item, value }) => {
+ const focusReferenceProps = getReferenceProps({
+ type: "items",
+ index,
+ heading,
+ focusPoint: { x: currentX, y: yScale(value) },
+ emphasizedItemId: item.id,
+ items: tooltipItems,
+ });
+ return (
+ <circle
+ key={item.id}
+ cx={currentX}
+ cy={yScale(value)}
+ r={6}
+ fill="transparent"
+ pointerEvents="none"
+ tabIndex={0}
+ role="graphics-symbol"
+ aria-label={`${heading}: ${item.label} ${valueFormatter(value)}`}
+ {...focusReferenceProps}
+ onFocus={(event) => {
+ setHoveredIndex(index);
+ setHoveredSeriesId(item.id);
+ if (!hasConfiguredEmphasis)
+ onActiveSeriesChange(item.id);
+ focusReferenceProps.onFocus(event);
+ }}
+ onBlur={() => {
+ setHoveredIndex(undefined);
+ setHoveredSeriesId(undefined);
+ if (!hasConfiguredEmphasis)
+ onActiveSeriesChange(undefined);
+ focusReferenceProps.onBlur();
+ }}
+ />
+ );
+ })}
+ </g>
+ );
+ })}
+ </svg>
+ )}
+ </ChartTooltip>
+ );
+}
diff --git a/web/src/components/design-system/charts/PieChart/PieChart.tsx b/web/src/components/design-system/charts/PieChart/PieChart.tsx
index 086e076ad7..2db628a502 100644
--- a/web/src/components/design-system/charts/PieChart/PieChart.tsx
+++ b/web/src/components/design-system/charts/PieChart/PieChart.tsx
@@ -187,6 +187,7 @@ function PieChartContent({
tabIndex={0}
aria-label={`${slice.data.label}: ${valueFormatter(slice.data.value)}`}
{...getReferenceProps({
+ type: "primary",
index,
label: slice.data.label,
value: `${valueFormatter(slice.data.value)} (${percentageFormatter.format(slice.data.value / totalValue)})`,
diff --git a/web/src/features/widgets/chart-library/AreaChartTimeSeries.tsx b/web/src/features/widgets/chart-library/AreaChartTimeSeries.tsx
index 685b795b8b..0cbf27d965 100644
--- a/web/src/features/widgets/chart-library/AreaChartTimeSeries.tsx
+++ b/web/src/features/widgets/chart-library/AreaChartTimeSeries.tsx
@@ -21,7 +21,10 @@ import {
prepareDenseSeries,
prepareIsolatedPoints,
} from "@/src/features/widgets/chart-library/prepareDenseSeries";
-import { prepareTimeAxis } from "@/src/features/widgets/chart-library/prepareTimeAxis";
+import {
+ parseChartTimestamp,
+ prepareTimeAxis,
+} from "@/src/features/widgets/chart-library/prepareTimeAxis";
import { temporalAxisTickProp } from "@/src/features/widgets/chart-library/TimeAxisTick";
import { prepareVisibleSeries } from "@/src/features/widgets/chart-library/prepareVisibleSeries";
import {
@@ -48,6 +51,7 @@ export const AreaChartTimeSeries: React.FC<ChartProps> = ({
legendInteraction = "highlight",
maxVisibleSeries,
syncId,
+ sync,
subtleFill = false,
missingValue = "gap",
connectNulls = false,
@@ -102,6 +106,13 @@ export const AreaChartTimeSeries: React.FC<ChartProps> = ({
const tooltipFormatter = (value: number) =>
toFullMetricString(metricFormatter(value, { style: "compact" }));
+ const syncedIndex = groupedData.findIndex(
+ (item) =>
+ String(
+ parseChartTimestamp(item.time_dimension)?.getTime() ??
+ item.time_dimension,
+ ) === sync?.activeKey,
+ );
return (
<div
@@ -111,14 +122,19 @@ export const AreaChartTimeSeries: React.FC<ChartProps> = ({
// cursor is already over the chart at mount/refresh (enter never fires). (LFE-10549)
onMouseEnter={() => setSelfHovered(true)}
onMouseMove={() => setSelfHovered(true)}
- onMouseLeave={() => setSelfHovered(false)}
+ 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))
+ if (!e.currentTarget.contains(e.relatedTarget as Node | null)) {
setSelfHovered(false);
+ sync?.onActiveKeyChange(undefined);
+ }
}}
>
{series.total > dimensions.length && (
@@ -137,6 +153,15 @@ export const AreaChartTimeSeries: React.FC<ChartProps> = ({
data={groupedData}
syncId={syncId}
syncMethod="value"
+ onMouseMove={(state) => {
+ if (state.activeLabel === undefined) return;
+ sync?.onActiveKeyChange(
+ String(
+ parseChartTimestamp(state.activeLabel)?.getTime() ??
+ state.activeLabel,
+ ),
+ );
+ }}
>
{/* syncWithTicks: grid lines sit exactly on the budget-thinned axis
ticks (a line per shown day/hour), instead of recharts' default
@@ -197,6 +222,8 @@ export const AreaChartTimeSeries: React.FC<ChartProps> = ({
})}
<ChartActiveReferenceLine />
<ChartTooltip
+ active={syncedIndex >= 0 ? true : undefined}
+ defaultIndex={syncedIndex >= 0 ? syncedIndex : undefined}
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)
diff --git a/web/src/features/widgets/chart-library/Chart.clienttest.tsx b/web/src/features/widgets/chart-library/Chart.clienttest.tsx
index 36f586b1f5..65cd34af9f 100644
--- a/web/src/features/widgets/chart-library/Chart.clienttest.tsx
+++ b/web/src/features/widgets/chart-library/Chart.clienttest.tsx
@@ -51,11 +51,7 @@ describe("Chart dispatcher — empty-state guard (LFE-14333)", () => {
<Chart chartType="LINE_TIME_SERIES" data={data} rowLimit={100} />,
);
expect(screen.queryByText("No data")).not.toBeInTheDocument();
- // The real chart primitive mounted instead of the empty-state box —
- // `ChartContainer` stamps a `data-chart` id on its wrapper unconditionally,
- // independent of the (jsdom-only) 0x0 layout warning recharts logs when it
- // can't measure a real box to size its <svg> surface.
- expect(container.querySelector("[data-chart]")).toBeInTheDocument();
+ expect(container.querySelector("svg")).toBeInTheDocument();
});
it("does NOT show NoDataOrLoading while isLoading, even with no data yet", () => {
diff --git a/web/src/features/widgets/chart-library/Chart.tsx b/web/src/features/widgets/chart-library/Chart.tsx
index c3cc831ace..420ba8f6f0 100644
--- a/web/src/features/widgets/chart-library/Chart.tsx
+++ b/web/src/features/widgets/chart-library/Chart.tsx
@@ -8,6 +8,7 @@ import {
type LegendSummaryMode,
type LegendInteraction,
type MissingBucketValue,
+ type ChartProps,
} from "@/src/features/widgets/chart-library/chart-props";
import { formatMetric } from "@/src/features/widgets/chart-library/utils";
import { isChartDataEmpty } from "@/src/features/widgets/chart-library/isChartDataEmpty";
@@ -60,6 +61,7 @@ const ChartComponent = ({
legendInteraction,
maxVisibleSeries,
syncId,
+ sync,
overrideWarning = false,
metricFormatter: metricFormatterOverride,
thresholds,
@@ -94,6 +96,7 @@ const ChartComponent = ({
legendInteraction?: LegendInteraction;
maxVisibleSeries?: number;
syncId?: string;
+ sync?: ChartProps["sync"];
overrideWarning?: boolean;
metricFormatter?: MetricFormatterFunction;
thresholds?: ChartThreshold[];
@@ -188,6 +191,7 @@ const ChartComponent = ({
legendInteraction={legendInteraction}
maxVisibleSeries={maxVisibleSeries}
syncId={syncId}
+ sync={sync}
showDataPointDots={chartConfig?.show_data_point_dots ?? false}
thresholds={thresholds}
missingValue={missingValue}
@@ -205,6 +209,7 @@ const ChartComponent = ({
legendInteraction={legendInteraction}
maxVisibleSeries={maxVisibleSeries}
syncId={syncId}
+ sync={sync}
subtleFill={chartConfig?.subtle_fill}
missingValue={missingValue}
hideXAxisLabels={hideXAxisLabels}
@@ -221,6 +226,7 @@ const ChartComponent = ({
legendInteraction={legendInteraction}
maxVisibleSeries={maxVisibleSeries}
syncId={syncId}
+ sync={sync}
subtleFill={chartConfig?.subtle_fill}
hideXAxisLabels={hideXAxisLabels}
/>
diff --git a/web/src/features/widgets/chart-library/LineChartTimeSeries.tsx b/web/src/features/widgets/chart-library/LineChartTimeSeries.tsx
index 81146aafbc..9e5e97f941 100644
--- a/web/src/features/widgets/chart-library/LineChartTimeSeries.tsx
+++ b/web/src/features/widgets/chart-library/LineChartTimeSeries.tsx
@@ -1,24 +1,10 @@
-/* eslint-disable no-nested-ternary */
-import React, { useMemo, useRef, useState } from "react";
-import {
- ChartActiveReferenceLine,
- ChartContainer,
- ChartTooltip,
- ChartTooltipContent,
- ChartTooltipPortal,
-} from "@/src/components/ui/chart";
-import { isolatedPointDot } from "@/src/features/widgets/chart-library/IsolatedPointDot";
-import { NearestSeriesProbe } from "@/src/features/widgets/chart-library/NearestSeriesProbe";
+import { useMemo } from "react";
+
import {
- CartesianGrid,
- Label,
- Line,
- LineChart,
- ReferenceArea,
- ReferenceLine,
- XAxis,
- YAxis,
-} from "recharts";
+ LineChart as DesignSystemLineChart,
+ type LineChartLegend,
+ type LineChartThreshold,
+} from "@/src/components/design-system/charts/LineChart/LineChart";
import {
type ChartProps,
type ChartThreshold,
@@ -29,160 +15,52 @@ import {
groupDataByTimeDimension,
toFullMetricString,
} from "@/src/features/widgets/chart-library/utils";
-import { useChartTickBudget } from "@/src/features/widgets/chart-library/useChartTickBudget";
+import { prepareDenseSeries } from "@/src/features/widgets/chart-library/prepareDenseSeries";
import {
- prepareDenseSeries,
- prepareIsolatedPoints,
-} from "@/src/features/widgets/chart-library/prepareDenseSeries";
-import { prepareTimeAxis } from "@/src/features/widgets/chart-library/prepareTimeAxis";
-import { temporalAxisTickProp } from "@/src/features/widgets/chart-library/TimeAxisTick";
+ parseChartTimestamp,
+ prepareTimeAxis,
+} from "@/src/features/widgets/chart-library/prepareTimeAxis";
import { prepareVisibleSeries } from "@/src/features/widgets/chart-library/prepareVisibleSeries";
import {
seriesColor,
SeriesOverflowNote,
- TimeSeriesLegend,
- useSeriesLegend,
} from "@/src/features/widgets/chart-library/TimeSeriesLegend";
+import { getPlainTextFromReactNode } from "@/src/utils/react-node-plain-text";
-/** computeMetricExtent returns the [min, max] of all numeric metric values across the data, for sizing the eq/neq band. */
-const computeMetricExtent = (
- data: ChartProps["data"],
-): { min: number; max: number } | null => {
- let min = Infinity;
- let max = -Infinity;
- for (const point of data) {
- const m = point.metric;
- if (typeof m === "number" && Number.isFinite(m)) {
- if (m < min) min = m;
- if (m > max) max = m;
- }
- }
- return Number.isFinite(min) && Number.isFinite(max) ? { min, max } : null;
-};
-
-/** ThresholdOverlay returns the ReferenceLine + (operator-derived) ReferenceArea recharts elements for a single ChartThreshold. */
-const ThresholdOverlay = ({
- threshold,
- extent,
-}: {
- threshold: ChartThreshold;
- extent: { min: number; max: number } | null;
-}) => {
- const stroke = `var(--color-${threshold.color}-600)`;
- const fill = `var(--color-${threshold.color}-500)`;
- const elements: React.ReactNode[] = [];
-
- switch (threshold.operator) {
- case "GT":
- case "GTE":
- elements.push(
- <ReferenceArea
- key={`area-${threshold.value}`}
- y2={threshold.value}
- ifOverflow="extendDomain"
- fill={fill}
- fillOpacity={0.14}
- stroke="none"
- />,
- );
- break;
- case "LT":
- case "LTE":
- elements.push(
- <ReferenceArea
- key={`area-${threshold.value}`}
- y1={threshold.value}
- ifOverflow="extendDomain"
- fill={fill}
- fillOpacity={0.14}
- stroke="none"
- />,
- );
- break;
- case "EQ":
- case "NEQ": {
- // Floor at 1 so threshold.value === 0 with no extent doesn't collapse
- // the band to a zero-height area (which Recharts then tiles across the
- // full chart).
- const bandEpsilon = Math.max(
- extent && extent.max > extent.min
- ? (extent.max - extent.min) * 0.01
- : Math.abs(threshold.value) * 0.01,
- 1,
- );
- if (threshold.operator === "EQ") {
- // The violation IS the band: a thin shaded region centered on value.
- elements.push(
- <ReferenceArea
- key={`area-${threshold.value}`}
- y1={threshold.value - bandEpsilon}
- y2={threshold.value + bandEpsilon}
- ifOverflow="extendDomain"
- fill={fill}
- fillOpacity={0.14}
- stroke="none"
- />,
- );
- } else {
- elements.push(
- <ReferenceArea
- key={`area-above-${threshold.value}`}
- y2={threshold.value + bandEpsilon}
- ifOverflow="extendDomain"
- fill={fill}
- fillOpacity={0.14}
- stroke="none"
- />,
- <ReferenceArea
- key={`area-below-${threshold.value}`}
- y1={threshold.value - bandEpsilon}
- ifOverflow="extendDomain"
- fill={fill}
- fillOpacity={0.14}
- stroke="none"
- />,
- );
- }
- break;
- }
+function toDesignSystemThreshold(
+ threshold: ChartThreshold,
+): LineChartThreshold {
+ let region: LineChartThreshold["region"];
+ if (threshold.operator === "GT" || threshold.operator === "GTE") {
+ region = "above";
+ } else if (threshold.operator === "LT" || threshold.operator === "LTE") {
+ region = "below";
+ } else if (threshold.operator === "EQ") {
+ region = "equal";
+ } else {
+ region = "not-equal";
}
- // Inclusive operators get solid lines, exclusive operators get dashed lines
- const isInclusive =
- threshold.operator === "GTE" ||
- threshold.operator === "LTE" ||
- threshold.operator === "EQ";
-
- elements.push(
- <ReferenceLine
- key={`line-${threshold.value}`}
- y={threshold.value}
- stroke={stroke}
- strokeWidth={1.5}
- strokeDasharray={isInclusive ? undefined : "4 4"}
- ifOverflow="extendDomain"
- >
- {threshold.label && (
- <Label
- value={threshold.label}
- position="insideTopRight"
- fill={stroke}
- fontSize={11}
- />
- )}
- </ReferenceLine>,
- );
-
- return <>{elements}</>;
-};
+ return {
+ value: threshold.value,
+ label: threshold.label,
+ color: `var(--color-${threshold.color}-600)`,
+ fillColor: `var(--color-${threshold.color}-500)`,
+ region,
+ lineStyle:
+ threshold.operator === "GT" ||
+ threshold.operator === "LT" ||
+ threshold.operator === "NEQ"
+ ? "dashed"
+ : "solid",
+ };
+}
/**
- * LineChartTimeSeries 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.
+ * Widget adapter for the design-system D3 line chart. Query-specific data
+ * shaping and legend state stay here; drawing belongs to the design system.
*/
-export const LineChartTimeSeries: React.FC<ChartProps> = ({
+export function LineChartTimeSeries({
data,
config = {
metric: {
@@ -192,27 +70,19 @@ export const LineChartTimeSeries: React.FC<ChartProps> = ({
},
},
},
- accessibilityLayer = true,
metricFormatter = (value, options) => formatMetric(value, options),
legendPosition = "auto",
legendSummary = "none",
legendInteraction = "highlight",
maxVisibleSeries,
- syncId,
- // Lines draw clean by default — a dot per sample is chart-junk on anything
- // but a handful of points. The hovered point still gets a dot (activeDot),
- // so the value is readable on hover without littering the line. (LFE-10549, V7)
+ sync,
showDataPointDots = false,
thresholds,
missingValue = "gap",
connectNulls = false,
hideXAxisLabels = false,
-}) => {
- const metricExtent = useMemo(() => computeMetricExtent(data), [data]);
-
+}: ChartProps) {
const allDimensions = useMemo(() => getUniqueDimensions(data), [data]);
- // Make every (bucket, series) cell explicit — 0 for additive metrics, null
- // (a real gap) otherwise — so lines never draw across no-data buckets. (LFE-10694)
const groupedData = useMemo(
() =>
prepareDenseSeries(
@@ -222,213 +92,105 @@ export const LineChartTimeSeries: React.FC<ChartProps> = ({
),
[data, allDimensions, missingValue],
);
- // A real value with gaps on both sides spans no line segment — mark it with
- // a dot so honest gaps never hide real data. (LFE-10694)
- const isolatedPoints = useMemo(
- () => prepareIsolatedPoints(groupedData, allDimensions),
- [groupedData, allDimensions],
- );
- // 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(
+ const visibleSeries = useMemo(
() => prepareVisibleSeries(data, allDimensions),
[data, allDimensions],
);
- const dimensions = series.visible;
- const { ref: containerRef, maxTicks } = useChartTickBudget();
- const chartBoxRef = useRef<HTMLDivElement>(null);
+ const dimensions = visibleSeries.visible;
const timeAxis = useMemo(
() =>
prepareTimeAxis(
- groupedData.map((d) => d.time_dimension),
- maxTicks,
+ groupedData.map((datum) => datum.time_dimension),
+ undefined,
{ hideCategoryTickLabels: hideXAxisLabels },
),
- [groupedData, maxTicks, hideXAxisLabels],
- );
-
- const {
- legendItems,
- onLegendClick,
- isRendered,
- isDimmed,
- isHighlightActive,
- } = useSeriesLegend({
- data,
- dimensions,
- config,
- legendSummary,
- legendInteraction,
- maxVisibleSeries,
- });
-
- const renderedDimensions = dimensions.filter(isRendered);
-
- // Hover proximity: the line the cursor is vertically nearest to is emphasized
- // and the rest dimmed; cleared when the cursor isn't on a line (then everything
- // renders normally). Disabled while a series is click-focused, and gated on
- // self-hover so a synced sibling chart doesn't react to a cursor over another.
- const [selfHovered, setSelfHovered] = useState(false);
- const [nearestDimensions, setNearestDimensions] = useState<string[]>([]);
- const nearestSet = useMemo(
- () => new Set(nearestDimensions),
- [nearestDimensions],
+ [groupedData, hideXAxisLabels],
);
- const proximityActive = !isHighlightActive && nearestSet.size > 0;
-
- const tooltipFormatter = (value: number) =>
+ const formatValue = (value: number) =>
toFullMetricString(metricFormatter(value, { style: "compact" }));
+ const chartData = useMemo(
+ () =>
+ groupedData.map((datum) => ({
+ x: String(datum.time_dimension ?? ""),
+ values: Object.fromEntries(
+ dimensions.map((dimension) => {
+ const value = datum[dimension];
+ return [dimension, typeof value === "number" ? value : null];
+ }),
+ ),
+ })),
+ [dimensions, groupedData],
+ );
+ const chartSeries = dimensions.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,
+ };
+ }
+ const chart =
+ timeAxis.mode === "category" ? (
+ <DesignSystemLineChart
+ data={chartData}
+ series={chartSeries}
+ valueFormatter={formatValue}
+ showDataPointDots={showDataPointDots}
+ connectNulls={connectNulls}
+ thresholds={thresholds?.map(toDesignSystemThreshold)}
+ sync={sync}
+ legend={chartLegend}
+ xAxis={{
+ type: "category",
+ labels: hideXAxisLabels ? "hidden" : "visible",
+ tickFormatter: (value) => timeAxis.formatTick(value),
+ tooltipFormatter: (value) => timeAxis.formatTooltip(value),
+ }}
+ />
+ ) : (
+ <DesignSystemLineChart
+ data={chartData.flatMap((datum) => {
+ const date = parseChartTimestamp(datum.x);
+ return date ? [{ ...datum, x: date }] : [];
+ })}
+ series={chartSeries}
+ valueFormatter={formatValue}
+ showDataPointDots={showDataPointDots}
+ connectNulls={connectNulls}
+ thresholds={thresholds?.map(toDesignSystemThreshold)}
+ sync={sync}
+ legend={chartLegend}
+ xAxis={{
+ type: "time",
+ tickFormatter: (value) => timeAxis.formatTick(value.getTime()),
+ tooltipFormatter: (value) => timeAxis.formatTooltip(value.getTime()),
+ }}
+ />
+ );
return (
- <div
- ref={containerRef}
- className="flex size-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)}
- // 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);
- }}
- >
- {series.total > dimensions.length && (
+ <div className="flex size-full min-w-0 flex-col">
+ {visibleSeries.total > dimensions.length ? (
<SeriesOverflowNote
visibleCount={dimensions.length}
- totalCount={series.total}
+ totalCount={visibleSeries.total}
/>
- )}
- <ChartContainer
- ref={chartBoxRef}
- config={config}
- className="min-h-0 flex-1"
- >
- <LineChart
- accessibilityLayer={accessibilityLayer}
- data={groupedData}
- syncId={syncId}
- syncMethod="value"
- >
- {/* syncWithTicks: grid lines sit exactly on the budget-thinned axis
- ticks (a line per shown day/hour), instead of recharts' default
- every-bucket grid — density follows the tick budget. (LFE-10576) */}
- <CartesianGrid
- stroke="hsl(var(--chart-grid))"
- vertical={timeAxis.showVerticalGrid}
- 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}
- width="auto"
- niceTicks="auto"
- tickFormatter={(value) => tooltipFormatter(Number(value))}
- />
- {dimensions.map((dimension, index) => {
- if (!isRendered(dimension)) return null;
- const nearest = proximityActive && nearestSet.has(dimension);
- const muted = isDimmed(dimension) || (proximityActive && !nearest);
- const isolated = isolatedPoints.get(dimension);
- return (
- <Line
- key={dimension}
- type="linear"
- dataKey={dimension}
- strokeWidth={nearest ? 3.5 : 2.5}
- dot={
- showDataPointDots && !muted
- ? { r: 4 }
- : // Neighborless points span no line segment; a dot is the
- // only thing that keeps them visible. (LFE-10694)
- isolated
- ? isolatedPointDot(isolated, seriesColor(index), muted)
- : false
- }
- // The hover marker is independent of the static-dot setting: even
- // a dotless line reveals the point under the cursor.
- activeDot={muted ? false : { r: 5, strokeWidth: 0 }}
- stroke={seriesColor(index)}
- strokeOpacity={muted ? 0.2 : 1}
- connectNulls={connectNulls}
- isAnimationActive={false}
- />
- );
- })}
- {thresholds?.map((threshold, i) => (
- <ThresholdOverlay
- key={`threshold-${i}-${threshold.value}`}
- threshold={threshold}
- extent={metricExtent}
- />
- ))}
- <ChartActiveReferenceLine />
- <ChartTooltip
- content={({ active, payload, label, coordinate }) =>
- // Synced sibling charts share the crosshair (above) but the
- // tooltip belongs only to the chart under the cursor; it portals
- // into the overlay layer so the chart frame never clips it. (LFE-10549)
- selfHovered ? (
- <ChartTooltipPortal
- active={active}
- coordinate={coordinate}
- anchorRef={chartBoxRef}
- >
- <ChartTooltipContent
- active={active}
- payload={payload}
- label={label}
- indicator="line"
- labelFormatter={(value) => timeAxis.formatTooltip(value)}
- valueFormatter={tooltipFormatter}
- sortPayloadByValue="desc"
- highlightedKeys={proximityActive ? nearestSet : undefined}
- />
- </ChartTooltipPortal>
- ) : null
- }
- />
- <NearestSeriesProbe
- // Only the lines actually drawn are candidates — otherwise a hidden
- // (toggled-off) series whose data still sits in groupedData could be
- // picked as "nearest" and mute every visible line. (LFE-10549)
- dimensions={renderedDimensions}
- enabled={selfHovered && !isHighlightActive}
- onNearestChange={setNearestDimensions}
- />
- </LineChart>
- </ChartContainer>
- {legendItems.length > 0 &&
- (legendPosition === "below" ||
- (legendPosition === "auto" && legendItems.length > 1)) && (
- <TimeSeriesLegend
- items={legendItems}
- interaction={legendInteraction}
- onItemClick={onLegendClick}
- formatSummary={tooltipFormatter}
- />
- )}
+ ) : null}
+ <div className="min-h-0 flex-1">{chart}</div>
</div>
);
-};
+}
diff --git a/web/src/features/widgets/chart-library/NearestSeriesProbe.tsx b/web/src/features/widgets/chart-library/NearestSeriesProbe.tsx
deleted file mode 100644
index 671d7d143b..0000000000
--- a/web/src/features/widgets/chart-library/NearestSeriesProbe.tsx
+++ /dev/null
@@ -1,103 +0,0 @@
-/* eslint-disable @repo/no-null-render */
-import { useEffect, useMemo, useRef } from "react";
-import {
- useActiveTooltipCoordinate,
- useActiveTooltipDataPoints,
- useIsTooltipActive,
- useYAxisScale,
-} from "recharts";
-
-/** Two lines count as overlapping (both highlight) within this many pixels. */
-const COLOCATED_PX = 1;
-
-/**
- * Detects the single series line the cursor is vertically nearest to at the
- * hovered x and reports it upward so the chart can emphasize it. Renders
- * nothing — it only reads recharts' active-hover state via hooks, so it MUST be
- * a child of the chart (LineChart/AreaChart). (LFE-10549)
- *
- * Reports the nearest line only when the cursor is within `thresholdPx` of it
- * (otherwise nothing — the chart renders normally). A second line is reported
- * only when it sits within {@link COLOCATED_PX} of the nearest one, i.e. they
- * overlap at that pixel. Gate with `enabled` so a synced sibling chart (whose
- * crosshair tracks via syncId) doesn't react to a cursor that isn't over it.
- */
-export function NearestSeriesProbe({
- dimensions,
- thresholdPx = 8,
- enabled = true,
- onNearestChange,
-}: {
- dimensions: string[];
- thresholdPx?: number;
- enabled?: boolean;
- onNearestChange: (nearest: string[]) => void;
-}) {
- const isActive = useIsTooltipActive();
- const coordinate = useActiveTooltipCoordinate();
- const yScale = useYAxisScale();
- const activePoints = useActiveTooltipDataPoints<Record<string, unknown>>();
-
- const nearest = useMemo(() => {
- const cursorY = coordinate?.y;
- const row = activePoints?.[0];
- if (
- !enabled ||
- !isActive ||
- typeof cursorY !== "number" ||
- !yScale ||
- !row
- ) {
- return [] as string[];
- }
-
- const positions: { dimension: string; pixelY: number }[] = [];
- for (const dimension of dimensions) {
- const value = row[dimension];
- if (typeof value !== "number" || !Number.isFinite(value)) continue;
- const pixelY = yScale(value);
- if (typeof pixelY !== "number") continue;
- positions.push({ dimension, pixelY });
- }
- if (positions.length === 0) return [];
-
- let closest = positions[0];
- for (const position of positions) {
- if (
- Math.abs(position.pixelY - cursorY) < Math.abs(closest.pixelY - cursorY)
- ) {
- closest = position;
- }
- }
- // Only highlight when the cursor is essentially on a line.
- if (Math.abs(closest.pixelY - cursorY) > thresholdPx) return [];
- // The nearest line, plus any line overlapping it at this pixel row.
- return positions
- .filter(
- (position) =>
- Math.abs(position.pixelY - closest.pixelY) <= COLOCATED_PX,
- )
- .map((position) => position.dimension);
- }, [
- enabled,
- isActive,
- coordinate,
- yScale,
- activePoints,
- dimensions,
- thresholdPx,
- ]);
-
- // Report only when the set actually changes (the cursor moving within a line's
- // band shouldn't churn parent state). JSON.stringify (not join) so two distinct
- // dimension lists can't collide on a shared separator.
- const key = JSON.stringify(nearest);
- const lastKey = useRef<string | null>(null);
- useEffect(() => {
- if (lastKey.current === key) return;
- lastKey.current = key;
- onNearestChange(nearest);
- }, [key, nearest, onNearestChange]);
-
- return null;
-}
diff --git a/web/src/features/widgets/chart-library/TimeSeriesLegend.tsx b/web/src/features/widgets/chart-library/TimeSeriesLegend.tsx
index 7796a078f7..df2d6eff85 100644
--- a/web/src/features/widgets/chart-library/TimeSeriesLegend.tsx
+++ b/web/src/features/widgets/chart-library/TimeSeriesLegend.tsx
@@ -1,5 +1,6 @@
/* eslint-disable no-nested-ternary */
import React, { useEffect, useMemo, useRef, useState } from "react";
+import { ChartLegend } from "@/src/components/design-system/charts/ChartLegend";
import { type ChartConfig } from "@/src/components/ui/chart";
import {
type DataPoint,
@@ -8,7 +9,6 @@ import {
} from "@/src/features/widgets/chart-library/chart-props";
import { getDimensionSummaries } from "@/src/features/widgets/chart-library/utils";
import { getPlainTextFromReactNode } from "@/src/utils/react-node-plain-text";
-import { cn } from "@/src/utils/tailwind";
/** The 8-slot chart palette, cycled by series index (matches the series fills). */
export const seriesColor = (index: number): string =>
@@ -183,58 +183,53 @@ export function TimeSeriesLegend({
formatSummary: (value: number) => string;
}) {
return (
- // Wrap onto multiple rows so every series stays visible, but cap the
- // legend's height and scroll inside it — a chart with hundreds of series
- // must never let the legend crowd the plot out entirely. (LFE-10549)
- // Sits BELOW the plot (classic bottom-legend placement), so it pads
- // against the x-axis above it. (LFE-10576)
- <div className="[max-height:8rem] min-w-0 shrink-0 overflow-y-auto pt-2">
- <div className="flex flex-wrap justify-center gap-x-4 gap-y-1">
- {items.map((item) => {
- const labelText = getPlainTextFromReactNode(item.label);
- // Labels must describe the NEXT action, not the current state.
- // - toggle: click flips visibility → "Show"/"Hide".
- // - highlight: clicking the focused series clears focus ("Show all
- // series"); clicking any other focuses it ("Show only X"). (Getting
- // this from `dimmed` alone inverts it once a series is focused.)
- const ariaLabel =
- interaction === "toggle"
- ? item.dimmed
- ? `Show ${labelText}`
- : `Hide ${labelText}`
- : item.focused
- ? "Show all series"
- : `Show only ${labelText}`;
- // aria-pressed reflects state: visible (toggle) / focused (highlight).
- const ariaPressed =
- interaction === "toggle" ? !item.dimmed : item.focused;
- return (
- <button
- key={item.dimension}
- type="button"
- onClick={() => onItemClick(item.dimension)}
- className={cn(
- "flex shrink-0 items-center gap-1.5 text-xs whitespace-nowrap transition-opacity",
- "cursor-pointer hover:opacity-80",
- item.dimmed && "opacity-40",
- )}
- aria-pressed={ariaPressed}
- aria-label={ariaLabel}
- >
- <div
- className="h-2 w-2 shrink-0 rounded-[2px]"
- style={{ backgroundColor: item.color }}
- />
- <span className="text-muted-foreground">{item.label}</span>
- {item.summary !== null && (
- <span className="text-foreground font-bold">
- {formatSummary(item.summary)}
- </span>
- )}
- </button>
- );
- })}
- </div>
- </div>
+ <ChartLegend
+ selectionActions={
+ interaction === "toggle"
+ ? {
+ allSelected: items.every((item) => !item.dimmed),
+ onSelectAll: () => {
+ items
+ .filter((item) => item.dimmed)
+ .forEach((item) => onItemClick(item.dimension));
+ },
+ onDeselectAll: () => {
+ items
+ .filter((item) => !item.dimmed)
+ .forEach((item) => onItemClick(item.dimension));
+ },
+ }
+ : undefined
+ }
+ items={items.map((item) => {
+ const labelText =
+ getPlainTextFromReactNode(item.label) ?? item.dimension;
+ // Labels describe the next action, which cannot be inferred from the
+ // visual muted state alone in highlight mode.
+ const actionLabel =
+ interaction === "toggle"
+ ? item.dimmed
+ ? `Show ${labelText}`
+ : `Hide ${labelText}`
+ : item.focused
+ ? "Show all series"
+ : `Show only ${labelText}`;
+ return {
+ id: item.dimension,
+ label: item.label,
+ color: item.color,
+ value:
+ item.summary === null
+ ? undefined
+ : { label: "Sum", value: formatSummary(item.summary) },
+ muted: item.dimmed,
+ action: {
+ label: actionLabel,
+ pressed: interaction === "toggle" ? !item.dimmed : item.focused,
+ onClick: () => onItemClick(item.dimension),
+ },
+ };
+ })}
+ />
);
}
diff --git a/web/src/features/widgets/chart-library/VerticalBarChartTimeSeries.tsx b/web/src/features/widgets/chart-library/VerticalBarChartTimeSeries.tsx
index aa6e0389c3..024ad97656 100644
--- a/web/src/features/widgets/chart-library/VerticalBarChartTimeSeries.tsx
+++ b/web/src/features/widgets/chart-library/VerticalBarChartTimeSeries.tsx
@@ -16,7 +16,10 @@ import {
toFullMetricString,
} from "@/src/features/widgets/chart-library/utils";
import { useChartTickBudget } from "@/src/features/widgets/chart-library/useChartTickBudget";
-import { prepareTimeAxis } from "@/src/features/widgets/chart-library/prepareTimeAxis";
+import {
+ parseChartTimestamp,
+ prepareTimeAxis,
+} from "@/src/features/widgets/chart-library/prepareTimeAxis";
import { prepareVisibleSeries } from "@/src/features/widgets/chart-library/prepareVisibleSeries";
import {
seriesColor,
@@ -49,6 +52,7 @@ export const VerticalBarChartTimeSeries: React.FC<ChartProps> = ({
legendInteraction = "highlight",
maxVisibleSeries,
syncId,
+ sync,
subtleFill = false,
hideXAxisLabels = false,
}) => {
@@ -87,6 +91,13 @@ export const VerticalBarChartTimeSeries: React.FC<ChartProps> = ({
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,
+ );
return (
<div
@@ -96,14 +107,19 @@ export const VerticalBarChartTimeSeries: React.FC<ChartProps> = ({
// cursor is already over the chart at mount/refresh (enter never fires). (LFE-10549)
onMouseEnter={() => setSelfHovered(true)}
onMouseMove={() => setSelfHovered(true)}
- onMouseLeave={() => setSelfHovered(false)}
+ 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))
+ if (!e.currentTarget.contains(e.relatedTarget as Node | null)) {
setSelfHovered(false);
+ sync?.onActiveKeyChange(undefined);
+ }
}}
>
{series.total > dimensions.length && (
@@ -122,6 +138,15 @@ export const VerticalBarChartTimeSeries: React.FC<ChartProps> = ({
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,
@@ -172,6 +197,8 @@ export const VerticalBarChartTimeSeries: React.FC<ChartProps> = ({
})}
<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
diff --git a/web/src/features/widgets/chart-library/chart-props.ts b/web/src/features/widgets/chart-library/chart-props.ts
index ba5f316b75..f8af522c78 100644
--- a/web/src/features/widgets/chart-library/chart-props.ts
+++ b/web/src/features/widgets/chart-library/chart-props.ts
@@ -129,6 +129,10 @@ export interface ChartProps {
* vertical time marker on all of them. (LFE-10549)
*/
syncId?: string;
+ sync?: {
+ activeKey: string | undefined;
+ onActiveKeyChange: (key: string | undefined) => void;
+ };
showValueLabels?: boolean;
showDataPointDots?: boolean;
subtleFill?: boolean;
diff --git a/web/src/features/widgets/components/DashboardGrid.tsx b/web/src/features/widgets/components/DashboardGrid.tsx
index c4567b1e95..0571a67395 100644
--- a/web/src/features/widgets/components/DashboardGrid.tsx
+++ b/web/src/features/widgets/components/DashboardGrid.tsx
@@ -11,6 +11,7 @@ import { DashboardWidget } from "@/src/features/widgets";
import type { ResolvedReadPath } from "@/src/features/events";
import { type FilterState } from "@langfuse/shared";
import { useState, useEffect, useRef, useCallback } from "react";
+import { type ChartProps } from "@/src/features/widgets/chart-library/chart-props";
export type DashboardPlacement = WidgetPlacement | PresetPlacement;
@@ -112,6 +113,11 @@ export function DashboardGrid({
/** Duplicate a preset card next to it (editable dashboards only). */
onDuplicatePreset?: (anchor: PresetPlacement) => void;
}) {
+ const [activeChartKey, setActiveChartKey] = useState<string>();
+ const chartSync: ChartProps["sync"] = {
+ activeKey: activeChartKey,
+ onActiveKeyChange: setActiveChartKey,
+ };
const { containerRef, width } = useDebouncedContainerWidth(200);
const [contentHeights, setContentHeights] = useState<Record<string, number>>(
{},
@@ -216,6 +222,7 @@ export function DashboardGrid({
) : (
<DashboardWidget
dashboardId={dashboardId}
+ chartSync={chartSync}
projectId={projectId}
readPath={readPath}
placement={widget}
diff --git a/web/src/features/widgets/components/DashboardWidget.tsx b/web/src/features/widgets/components/DashboardWidget.tsx
index 312e07cb6b..2f26142aab 100644
--- a/web/src/features/widgets/components/DashboardWidget.tsx
+++ b/web/src/features/widgets/components/DashboardWidget.tsx
@@ -15,6 +15,7 @@ import {
} from "@langfuse/shared/query";
import { type z } from "zod";
import { Chart } from "@/src/features/widgets/chart-library/Chart";
+import { type ChartProps } from "@/src/features/widgets/chart-library/chart-props";
import { type FilterState, type OrderByState } from "@langfuse/shared";
import { isTimeSeriesChart } from "@/src/features/widgets/chart-library/utils";
import {
@@ -81,6 +82,7 @@ export interface WidgetPlacement {
export function DashboardWidget({
projectId,
dashboardId,
+ chartSync,
readPath,
placement,
dateRange,
@@ -94,6 +96,7 @@ export function DashboardWidget({
}: {
projectId: string;
dashboardId: string;
+ chartSync: ChartProps["sync"];
/** Resolved by the page controller — the widget must not guess the version. */
readPath: ResolvedReadPath;
placement: WidgetPlacement;
@@ -773,33 +776,38 @@ export function DashboardWidget({
</div>
) : (
<div className="relative min-h-0 flex-1">
- <Chart
- chartType={widget.data.chartType}
- data={transformedData}
- // Sync the hover crosshair across all time-series widgets on this
- // dashboard (non-time-series chart types ignore it). (LFE-10549)
- syncId={dashboardId}
- config={chartMetricConfig}
- rowLimit={
- widget.data.chartConfig.type === "LINE_TIME_SERIES" ||
- widget.data.chartConfig.type === "BAR_TIME_SERIES" ||
- widget.data.chartConfig.type === "AREA_TIME_SERIES"
- ? 100
- : (widget.data.chartConfig.row_limit ?? 100)
- }
- chartConfig={chartConfigForRender}
- sortState={
- widget.data.chartType === "PIVOT_TABLE" ? sortState : undefined
- }
- onSortChange={
- widget.data.chartType === "PIVOT_TABLE" ? updateSort : undefined
- }
- isLoading={queryResult.isPending}
- metricFormatter={chartPresentation?.metricFormatter}
- missingValue={getWidgetMissingBucketValue(
- widget.data.metrics[0]?.agg ?? "count",
- )}
- />
+ <div className="absolute inset-0">
+ <Chart
+ chartType={widget.data.chartType}
+ data={transformedData}
+ syncId={dashboardId}
+ sync={chartSync}
+ config={chartMetricConfig}
+ rowLimit={
+ widget.data.chartConfig.type === "LINE_TIME_SERIES" ||
+ widget.data.chartConfig.type === "BAR_TIME_SERIES" ||
+ widget.data.chartConfig.type === "AREA_TIME_SERIES"
+ ? 100
+ : (widget.data.chartConfig.row_limit ?? 100)
+ }
+ chartConfig={chartConfigForRender}
+ sortState={
+ widget.data.chartType === "PIVOT_TABLE"
+ ? sortState
+ : undefined
+ }
+ onSortChange={
+ widget.data.chartType === "PIVOT_TABLE"
+ ? updateSort
+ : undefined
+ }
+ isLoading={queryResult.isPending}
+ metricFormatter={chartPresentation?.metricFormatter}
+ missingValue={getWidgetMissingBucketValue(
+ widget.data.metrics[0]?.agg ?? "count",
+ )}
+ />
+ </div>
<ChartLoadingState
isLoading={chartLoadingState.isLoading}
showSpinner={chartLoadingState.showSpinner}
diff --git a/web/src/features/widgets/components/PresetDashboardWidget.tsx b/web/src/features/widgets/components/PresetDashboardWidget.tsx
index 9e47c61624..f674629e3a 100644
--- a/web/src/features/widgets/components/PresetDashboardWidget.tsx
+++ b/web/src/features/widgets/components/PresetDashboardWidget.tsx
@@ -169,14 +169,15 @@ export function PresetDashboardWidget({
metricsVersion,
schedulerId,
syncId: dashboardId,
- // Most presets stretch to their fixed tile. Score Analytics is measured
- // by the grid because each selected score adds another chart row.
- className: "min-h-full",
+ // 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,
dateRange,
filterState,
+ heightBehavior.mode,
metricsVersion,
projectId,
schedulerId,