Skip to content

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

refactor(web): Create design-system AreaChart (#17870)

Ben Bachemdbf5107df264
diff --git a/web/src/components/design-system/charts/AreaChart/AreaChart.stories.tsx b/web/src/components/design-system/charts/AreaChart/AreaChart.stories.tsx
new file mode 100644
index 0000000000..1f01b474fb
--- /dev/null
+++ b/web/src/components/design-system/charts/AreaChart/AreaChart.stories.tsx
@@ -0,0 +1,394 @@
+import { useState } from "react";
+import preview from "../../../../../.storybook/preview";
+import { expect, userEvent, within } from "storybook/test";
+import { AreaChart } from "./AreaChart";
+import { type LineChartLegend } from "../LineChart/LineChart";
+import { AreaChartTimeSeries } from "@/src/features/widgets/chart-library/AreaChartTimeSeries";
+import { LineChartTimeSeries } from "@/src/features/widgets/chart-library/LineChartTimeSeries";
+
+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: 42 - index + Math.cos(index) * 6,
+ },
+}));
+
+const gaps = [
+ { x: new Date(Date.UTC(2026, 8, 1)), values: { api: 8, worker: null } },
+ { x: new Date(Date.UTC(2026, 8, 2)), values: { api: null, worker: null } },
+ { x: new Date(Date.UTC(2026, 8, 3)), values: { api: 12, worker: 4 } },
+ { x: new Date(Date.UTC(2026, 8, 4)), values: { api: null, worker: 9 } },
+ { x: new Date(Date.UTC(2026, 8, 5)), values: { api: 16, worker: null } },
+];
+
+type StoryProps = {
+ scenario?:
+ | "single"
+ | "time"
+ | "stacked"
+ | "gaps"
+ | "negative"
+ | "category"
+ | "denseCategory"
+ | "narrowCategory"
+ | "mixedBuckets";
+ connectNulls?: boolean;
+ legend?: LineChartLegend;
+};
+
+function AreaChartDemo({
+ scenario = "single",
+ connectNulls,
+ legend,
+}: StoryProps) {
+ const [activeKey, setActiveKey] = useState<string>();
+ if (scenario === "mixedBuckets") {
+ const mixedData = [
+ { time_dimension: "2026-09-01", dimension: "api", metric: 12 },
+ { time_dimension: "2026-09-04", dimension: "api", metric: 18 },
+ { time_dimension: "Unknown", dimension: "api", metric: 7 },
+ ];
+ return (
+ <div className="flex size-full flex-col">
+ <div className="min-h-0 flex-1" data-chart="area">
+ <AreaChartTimeSeries
+ data={mixedData}
+ sync={{ activeKey, onActiveKeyChange: setActiveKey }}
+ />
+ </div>
+ <div className="min-h-0 flex-1" data-chart="line">
+ <LineChartTimeSeries
+ data={mixedData}
+ sync={{ activeKey, onActiveKeyChange: setActiveKey }}
+ />
+ </div>
+ </div>
+ );
+ }
+ if (scenario === "narrowCategory") {
+ return (
+ <div className="h-full w-[220px]">
+ <AreaChart
+ data={Array.from({ length: 6 }, (_, index) => ({
+ x: `Category ${index}`,
+ values: { api: index },
+ }))}
+ series={series.slice(0, 1)}
+ xAxis={{ type: "category" }}
+ />
+ </div>
+ );
+ }
+ if (scenario === "denseCategory") {
+ return (
+ <AreaChart
+ data={Array.from({ length: 80 }, (_, index) => ({
+ x: `Category ${index}`,
+ values: { api: index },
+ }))}
+ series={series.slice(0, 1)}
+ xAxis={{ type: "category" }}
+ />
+ );
+ }
+ if (scenario === "category") {
+ return (
+ <AreaChart
+ data={[
+ { x: "Development", values: { api: 12, worker: 7 } },
+ { x: "Staging", values: { api: 26, worker: 14 } },
+ { x: "Production", values: { api: 43, worker: 31 } },
+ ]}
+ series={series}
+ xAxis={{ type: "category" }}
+ legend={legend}
+ />
+ );
+ }
+
+ let chartData: {
+ x: Date;
+ values: { api: number | null; worker: number | null };
+ }[] = data;
+ if (scenario === "gaps") chartData = gaps;
+ else if (scenario === "negative") {
+ chartData = data.map((datum, index) => ({
+ ...datum,
+ values: { api: index * 3 - 18, worker: 12 - index * 2 },
+ }));
+ }
+
+ return (
+ <AreaChart
+ data={chartData}
+ series={scenario === "single" ? series.slice(0, 1) : series}
+ xAxis={{ type: "time" }}
+ valueFormatter={(value) => `${value.toFixed(1)} requests`}
+ stacked={scenario === "stacked"}
+ connectNulls={connectNulls}
+ legend={legend}
+ />
+ );
+}
+
+const meta = preview.meta({
+ component: AreaChartDemo,
+ parameters: { layout: "fullscreen" },
+ args: {},
+ decorators: [
+ (Story) => (
+ <div className="h-dvh w-full">
+ <Story />
+ </div>
+ ),
+ ],
+});
+
+export const Default = meta.story({});
+
+export const DenseCategories = meta.story({
+ name: "(Test) Dense Categories",
+ args: { scenario: "denseCategory" },
+ play: async ({ canvasElement }) => {
+ const labels = canvasElement.querySelectorAll('[data-x-axis-label=""]');
+ await expect(labels.length).toBeGreaterThan(1);
+ await expect(labels.length).toBeLessThan(80);
+ await expect(labels[0]).toHaveTextContent("Category");
+ },
+});
+
+export const NarrowCategories = meta.story({
+ name: "(Test) Narrow Categories",
+ args: { scenario: "narrowCategory" },
+ play: async ({ canvasElement }) => {
+ const labels = canvasElement.querySelectorAll('[data-x-axis-label=""]');
+ await expect(labels[0]).toHaveTextContent("Category 0");
+ await expect(labels[labels.length - 1]).toHaveTextContent("Category 5");
+ },
+});
+
+export const MixedBuckets = meta.story({
+ name: "(Test) Mixed Buckets",
+ args: { scenario: "mixedBuckets" },
+ play: async ({ canvasElement }) => {
+ const area = canvasElement.querySelector<HTMLElement>(
+ '[data-chart="area"]',
+ );
+ const line = canvasElement.querySelector<HTMLElement>(
+ '[data-chart="line"]',
+ );
+ if (!area || !line) throw new Error("Charts not found");
+ for (const chart of [area, line]) {
+ await expect(
+ within(chart).getByRole("graphics-symbol", { name: /Unknown.*7/ }),
+ ).toBeInTheDocument();
+ await expect(
+ chart.querySelector('[data-x-axis-label=""]'),
+ ).toHaveTextContent("Sep 1");
+ }
+ const datePoint = within(area).getByRole("graphics-symbol", {
+ name: /Sep 1, 2026.*12/,
+ });
+ const hoverArea = datePoint.parentElement?.querySelector("rect");
+ if (!hoverArea) throw new Error("Hover area not found");
+ await userEvent.hover(hoverArea);
+ await expect(
+ line.querySelector('line[stroke-dasharray="3 3"]'),
+ ).toBeInTheDocument();
+ },
+});
+
+export const OverlappingAreas = meta.story({
+ name: "(Test) Overlapping Areas",
+ args: { scenario: "time" },
+ play: async ({ canvasElement }) => {
+ const fills = canvasElement.querySelectorAll<SVGPathElement>(
+ 'path[fill^="url(#"]',
+ );
+ await expect(fills).toHaveLength(2);
+ const stops = canvasElement.querySelectorAll(
+ 'linearGradient stop[stop-color^="color-mix"]',
+ );
+ await expect(stops).toHaveLength(4);
+ await expect(stops[0]).toHaveAttribute(
+ "stop-color",
+ "color-mix(in srgb, #3a3dee 75%, hsl(var(--background)))",
+ );
+ await expect(stops[2]).toHaveAttribute(
+ "stop-color",
+ "color-mix(in srgb, #07b9d5 75%, hsl(var(--background)))",
+ );
+ for (const fill of fills) {
+ await expect(fill).not.toHaveAttribute("fill-opacity");
+ await expect(fill.getAttribute("fill")).toMatch(/^url\(#.+\)$/);
+ }
+ const hoverArea = canvasElement.querySelector<SVGRectElement>(
+ 'rect[fill="transparent"]',
+ );
+ if (!hoverArea) throw new Error("Hover area not found");
+ await userEvent.hover(hoverArea);
+ await expect(stops[0]).toHaveAttribute(
+ "stop-color",
+ "color-mix(in srgb, #3a3dee 75%, hsl(var(--background)))",
+ );
+ await expect(stops[2]).toHaveAttribute(
+ "stop-color",
+ "color-mix(in srgb, #07b9d5 75%, hsl(var(--background)))",
+ );
+ for (const stroke of canvasElement.querySelectorAll('path[stroke^="#"]')) {
+ await expect(stroke).toHaveAttribute("stroke-width", "2.5");
+ }
+ },
+});
+
+export const StackedAreas = meta.story({
+ name: "(Test) Stacked Areas",
+ args: {
+ scenario: "stacked",
+ legend: { visibility: "visible", interaction: "toggle", summary: "sum" },
+ },
+ play: async ({ canvasElement }) => {
+ const canvas = within(canvasElement);
+ const apiPoint = canvas.getAllByRole("graphics-symbol", { name: /API/ })[0];
+ const workerPoint = canvas.getAllByRole("graphics-symbol", {
+ name: /Worker/,
+ })[0];
+ if (!apiPoint || !workerPoint) throw new Error("Data points not found");
+ await expect(Number(workerPoint.getAttribute("cy"))).toBeLessThan(
+ Number(apiPoint.getAttribute("cy")),
+ );
+ const workerFill = canvasElement.querySelectorAll<SVGPathElement>(
+ 'path[fill^="url(#"]',
+ )[1];
+ const baseline = workerFill?.getAttribute("d")?.match(/L[\d.]+,([\d.]+)Z$/);
+ await expect(Number(baseline?.[1])).toBeCloseTo(
+ Number(apiPoint.getAttribute("cy")),
+ 0,
+ );
+ workerPoint.focus();
+ const tooltip = await within(canvasElement.ownerDocument.body).findByRole(
+ "tooltip",
+ );
+ await expect(tooltip).toHaveTextContent("Worker");
+ await expect(tooltip).toHaveTextContent("48.0 requests");
+ await userEvent.click(
+ await canvas.findByRole("button", { name: "Hide API" }),
+ );
+ await expect(
+ canvasElement.querySelectorAll('path[fill^="url(#"]'),
+ ).toHaveLength(1);
+ },
+});
+
+export const WithLegend = meta.story({
+ name: "(Test) With Legend",
+ args: {
+ scenario: "time",
+ legend: { visibility: "visible", interaction: "toggle", summary: "sum" },
+ },
+ play: async ({ canvasElement }) => {
+ const canvas = within(canvasElement);
+ const api = await canvas.findByRole("button", { name: "Hide API" });
+ await expect(api).toHaveTextContent("Sum:");
+ await userEvent.click(api);
+ await expect(
+ canvas.getByRole("button", { name: "Show API" }),
+ ).toHaveAttribute("aria-pressed", "false");
+ await expect(
+ canvasElement.querySelector('linearGradient stop[stop-color*="#3a3dee"]'),
+ ).not.toBeInTheDocument();
+ await userEvent.click(canvas.getByRole("button", { name: "Show API" }));
+ await expect(
+ canvasElement.querySelector('linearGradient stop[stop-color*="#3a3dee"]'),
+ ).toBeInTheDocument();
+ },
+});
+
+export const HighlightLegend = meta.story({
+ name: "(Test) Highlight Legend",
+ args: {
+ scenario: "time",
+ legend: {
+ visibility: "visible",
+ interaction: "highlight",
+ summary: "none",
+ },
+ },
+ play: async ({ canvasElement }) => {
+ const canvas = within(canvasElement);
+ await userEvent.click(
+ await canvas.findByRole("button", { name: "Show only API" }),
+ );
+ await expect(
+ canvas.getByRole("button", { name: "Show all series" }),
+ ).toHaveAttribute("aria-pressed", "true");
+ await expect(
+ canvasElement.querySelector('linearGradient stop[stop-color*="#07b9d5"]'),
+ ).toHaveAttribute(
+ "stop-color",
+ "color-mix(in srgb, #07b9d5 15%, hsl(var(--background)))",
+ );
+ },
+});
+
+export const LimitedVisibleSeries = meta.story({
+ name: "(Test) Limited Visible Series",
+ args: {
+ scenario: "time",
+ legend: {
+ visibility: "visible",
+ interaction: "toggle",
+ summary: "none",
+ maxVisibleSeries: 1,
+ },
+ },
+ play: async ({ canvasElement }) => {
+ const canvas = within(canvasElement);
+ await expect(
+ canvasElement.querySelectorAll('path[fill^="url(#"]'),
+ ).toHaveLength(1);
+ await expect(
+ await canvas.findByRole("button", { name: /Show (API|Worker)/ }),
+ ).toHaveAttribute("aria-pressed", "false");
+ },
+});
+
+export const GapsAndIsolatedPoints = meta.story({
+ name: "(Test) Gaps And Isolated Points",
+ args: { scenario: "gaps" },
+ play: async ({ canvasElement }) => {
+ await expect(
+ canvasElement.querySelectorAll('circle[fill="#3a3dee"][r="4"]'),
+ ).toHaveLength(3);
+ const firstPoint = within(canvasElement).getByRole("graphics-symbol", {
+ name: /API 8\.0 requests/,
+ });
+ firstPoint.focus();
+ const tooltip = await within(canvasElement.ownerDocument.body).findByRole(
+ "tooltip",
+ );
+ await expect(tooltip).toHaveTextContent("8.0 requests");
+ },
+});
+
+export const ConnectNulls = meta.story({
+ args: { scenario: "gaps", connectNulls: true },
+});
+
+export const NegativeValues = meta.story({
+ name: "(Test) Negative Values",
+ args: { scenario: "negative" },
+ play: async ({ canvasElement }) => {
+ await expect(
+ canvasElement.querySelector("[data-zero-baseline]"),
+ ).toBeInTheDocument();
+ },
+});
+
+export const Categories = meta.story({ args: { scenario: "category" } });
diff --git a/web/src/components/design-system/charts/AreaChart/AreaChart.tsx b/web/src/components/design-system/charts/AreaChart/AreaChart.tsx
new file mode 100644
index 0000000000..0623d8a6d5
--- /dev/null
+++ b/web/src/components/design-system/charts/AreaChart/AreaChart.tsx
@@ -0,0 +1,21 @@
+"use client";
+
+import { type ComponentProps } from "react";
+
+import { SeriesChartCore } from "@/src/components/design-system/internal/charts/SeriesChartCore";
+
+export function AreaChart(
+ props: ComponentProps<typeof SeriesChartCore> & {
+ stacked?: boolean;
+ areaVariant?: never;
+ areaStacked?: never;
+ },
+) {
+ return (
+ <SeriesChartCore
+ {...props}
+ areaVariant
+ areaStacked={props.stacked ?? false}
+ />
+ );
+}
diff --git a/web/src/components/design-system/charts/LineChart/LineChart.stories.tsx b/web/src/components/design-system/charts/LineChart/LineChart.stories.tsx
index 9be7b64a67..e129f4d84b 100644
--- a/web/src/components/design-system/charts/LineChart/LineChart.stories.tsx
+++ b/web/src/components/design-system/charts/LineChart/LineChart.stories.tsx
@@ -62,15 +62,7 @@ const LineChartDemo = (props: LineChartStoryProps) => {
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",
- }),
- }}
+ xAxis={{ type: "time" }}
/>
);
};
diff --git a/web/src/components/design-system/charts/LineChart/LineChart.tsx b/web/src/components/design-system/charts/LineChart/LineChart.tsx
index 51a22e7635..5825e43b2f 100644
--- a/web/src/components/design-system/charts/LineChart/LineChart.tsx
+++ b/web/src/components/design-system/charts/LineChart/LineChart.tsx
@@ -1,883 +1,20 @@
"use client";
-import { useMemo, useState, type PointerEvent } from "react";
-import { scaleLinear, scalePoint, scaleUtc } from "d3-scale";
-import { line } from "d3-shape";
+import { type ComponentProps } from "react";
-import { ChartContainer } from "@/src/components/design-system/charts/ChartContainer";
-import { CartesianChart } from "@/src/components/design-system/internal/charts/CartesianChart";
-import { CartesianLayout } from "@/src/components/design-system/internal/charts/CartesianLayout";
-import { ChartLegend } from "@/src/components/design-system/internal/charts/ChartLegend";
-import { ChartTooltip } from "@/src/components/design-system/internal/charts/ChartTooltip";
+import { SeriesChartCore } from "@/src/components/design-system/internal/charts/SeriesChartCore";
-type LineChartValues = {
- values: Record<string, number | null>;
-};
+export type {
+ LineChartLegend,
+ LineChartSeries,
+ LineChartThreshold,
+} from "@/src/components/design-system/internal/charts/SeriesChartCore";
-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 APPROX_TIME_TICK_WIDTH = 64;
-const CATEGORY_TICK_GAP = 16;
-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,
- top: number,
- plotHeight: number,
-) => {
- const epsilon = Math.max(plotHeight * 0.01, 2);
- if (threshold.region === "above") return [[top, y - top]];
- if (threshold.region === "below") {
- return [[y, top + plotHeight - y]];
- }
- if (threshold.region === "equal") return [[y - epsilon, epsilon * 2]];
- if (threshold.region === "not-equal") {
- return [
- [top, y - epsilon - top],
- [y + epsilon, top + 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 }) => (
- <CartesianLayout
- width={width}
- height={height}
- showXAxisLabels={
- props.xAxis.type !== "category" ||
- props.xAxis.labels !== "hidden"
- }
- >
- {(layout) => (
- <LineChartContent
- {...props}
- {...layout}
- series={configuredSeries}
- onActiveSeriesChange={setActiveSeriesId}
- width={width}
- height={height}
- />
- )}
- </CartesianLayout>
- )}
- </ChartContainer>
- </div>
- {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;
- measuredPlot: { left: number; top: number; width: number; height: number };
- maxYTicks: number;
- plotForTicks: (labels: string[]) => {
- left: number;
- top: number;
- width: number;
- height: number;
- };
+export function LineChart(
+ props: ComponentProps<typeof SeriesChartCore> & {
+ areaVariant?: never;
+ areaStacked?: never;
},
) {
- const {
- series,
- valueFormatter = defaultValueFormatter,
- showDataPointDots = false,
- connectNulls = false,
- thresholds = [],
- ariaLabel = "Line chart",
- sync,
- onActiveSeriesChange,
- width,
- height,
- xAxis,
- measuredPlot,
- maxYTicks,
- plotForTicks,
- } = props;
- const [hoveredIndex, setHoveredIndex] = useState<number>();
- const [hoveredSeriesId, setHoveredSeriesId] = useState<string>();
- const showXAxisLabels =
- xAxis.type !== "category" || xAxis.labels !== "hidden";
- const plotHeight = measuredPlot.height;
- const yRangePadding = Math.min(MAX_VISIBLE_POINT_RADIUS, plotHeight / 2);
-
- const data = useMemo<NormalizedDatum[]>(
- () => normalizeLineChartData(props.data, props.xAxis.type),
- [props.data, props.xAxis.type],
- );
-
- const yScale = useMemo(() => {
- const values = data.flatMap((datum) =>
- series.flatMap((item) => {
- const value = datum.values[item.id];
- return typeof value === "number" && Number.isFinite(value)
- ? [value]
- : [];
- }),
- );
- values.push(...thresholds.map((threshold) => threshold.value));
- let min = Math.min(...values);
- let max = Math.max(...values);
- if (!Number.isFinite(min) || !Number.isFinite(max)) {
- min = 0;
- max = 1;
- } else if (min === max) {
- const padding = Math.max(Math.abs(min) * 0.1, 1);
- min -= padding;
- max += padding;
- }
- if (min < 0) max = Math.max(0, max);
- return scaleLinear()
- .domain([min, max])
- .nice(maxYTicks)
- .range([
- measuredPlot.top + plotHeight - yRangePadding,
- measuredPlot.top + yRangePadding,
- ]);
- }, [
- data,
- maxYTicks,
- measuredPlot.top,
- plotHeight,
- series,
- thresholds,
- yRangePadding,
- ]);
-
- const yTicks = yScale.ticks(maxYTicks);
- const plot = plotForTicks(yTicks.map(valueFormatter));
- const LEFT_MARGIN = plot.left;
- const TOP_MARGIN = plot.top;
- const plotWidth = plot.width;
-
- const categoryScale = useMemo(
- () =>
- scalePoint<string>()
- .domain(data.map((datum) => datum.key))
- .range([LEFT_MARGIN, LEFT_MARGIN + plotWidth])
- .padding(data.length > 1 ? 0 : 0.5),
- [LEFT_MARGIN, 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]);
- }, [LEFT_MARGIN, 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 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) => ({
- key: datum.key,
- x: getX(datum),
- label: xAxis.tickFormatter?.(String(datum.x)) ?? String(datum.x),
- maxWidth: plotWidth / Math.max(1, data.length) - CATEGORY_TICK_GAP,
- }));
- const activeKey =
- hoveredIndex === undefined ? sync?.activeKey : data[hoveredIndex]?.key;
- const activeDatum = data.find((datum) => datum.key === activeKey);
- 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, maxWidth: undefined },
- ].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 hasDistinctColors = series.some(
- (item) => item.color !== series[0]?.color,
- );
- 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 }) => (
- <CartesianChart
- width={width}
- height={height}
- ariaLabel={ariaLabel}
- plot={plot}
- yTicks={yTicks}
- y={yScale}
- valueFormatter={valueFormatter}
- categoryBoundaries={xAxis.type === "category"}
- zeroY={
- yScale.domain()[1] >= 0 &&
- data.some((datum) =>
- series.some((item) => (datum.values[item.id] ?? 0) < 0),
- )
- ? yScale(0)
- : undefined
- }
- xAxis={
- showXAxisLabels
- ? {
- ticks: visibleXTicks,
- activeKey,
- showCategoryTicks: xAxis.type === "category",
- }
- : undefined
- }
- >
- {thresholds.map((threshold, index) => {
- const y = yScale(threshold.value);
- const regions = getThresholdRegions(
- threshold,
- y,
- TOP_MARGIN,
- 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}
-
- {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: hasDistinctColors ? item.color : undefined,
- }));
- 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>
- );
- })}
- </CartesianChart>
- )}
- </ChartTooltip>
- );
+ return <SeriesChartCore {...props} />;
}
diff --git a/web/src/components/design-system/internal/charts/SeriesChartCore.tsx b/web/src/components/design-system/internal/charts/SeriesChartCore.tsx
new file mode 100644
index 0000000000..d1061d4ee2
--- /dev/null
+++ b/web/src/components/design-system/internal/charts/SeriesChartCore.tsx
@@ -0,0 +1,1005 @@
+"use client";
+
+import { useId, useMemo, useState, type PointerEvent } from "react";
+import { scaleLinear, scalePoint, scaleUtc } from "d3-scale";
+import { area, line } from "d3-shape";
+
+import { ChartContainer } from "@/src/components/design-system/charts/ChartContainer";
+import { CartesianChart } from "@/src/components/design-system/internal/charts/CartesianChart";
+import { CartesianLayout } from "@/src/components/design-system/internal/charts/CartesianLayout";
+import { ChartLegend } from "@/src/components/design-system/internal/charts/ChartLegend";
+import { ChartTooltip } from "@/src/components/design-system/internal/charts/ChartTooltip";
+
+type LineChartValues = {
+ values: Record<string, number | null>;
+};
+
+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 APPROX_TIME_TICK_WIDTH = 64;
+const CATEGORY_TICK_GAP = 16;
+const SERIES_HOVER_DISTANCE = 10;
+const MAX_VISIBLE_POINT_RADIUS = 5;
+const defaultValueFormatter = (value: number) => value.toLocaleString();
+const defaultTimeTickFormatter = (value: Date) =>
+ value.toLocaleDateString(undefined, {
+ month: "short",
+ day: "numeric",
+ timeZone: "UTC",
+ });
+
+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,
+ top: number,
+ plotHeight: number,
+) => {
+ const epsilon = Math.max(plotHeight * 0.01, 2);
+ if (threshold.region === "above") return [[top, y - top]];
+ if (threshold.region === "below") {
+ return [[y, top + plotHeight - y]];
+ }
+ if (threshold.region === "equal") return [[y - epsilon, epsilon * 2]];
+ if (threshold.region === "not-equal") {
+ return [
+ [top, y - epsilon - top],
+ [y + epsilon, top + plotHeight - y - epsilon],
+ ];
+ }
+ return [];
+};
+
+export function SeriesChartCore(
+ props: LineChartProps & { areaVariant?: boolean; areaStacked?: boolean },
+) {
+ 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 }) => (
+ <CartesianLayout
+ width={width}
+ height={height}
+ showXAxisLabels={
+ props.xAxis.type !== "category" ||
+ props.xAxis.labels !== "hidden"
+ }
+ >
+ {(layout) => (
+ <LineChartContent
+ {...props}
+ {...layout}
+ series={configuredSeries}
+ onActiveSeriesChange={setActiveSeriesId}
+ width={width}
+ height={height}
+ />
+ )}
+ </CartesianLayout>
+ )}
+ </ChartContainer>
+ </div>
+ {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"> & {
+ areaVariant?: boolean;
+ areaStacked?: boolean;
+ series: ConfiguredLineChartSeries[];
+ onActiveSeriesChange: (seriesId: string | undefined) => void;
+ width: number;
+ height: number;
+ measuredPlot: { left: number; top: number; width: number; height: number };
+ maxYTicks: number;
+ plotForTicks: (labels: string[]) => {
+ left: number;
+ top: number;
+ width: number;
+ height: number;
+ };
+ },
+) {
+ const {
+ series,
+ valueFormatter = defaultValueFormatter,
+ showDataPointDots = false,
+ connectNulls = false,
+ areaVariant,
+ areaStacked = false,
+ thresholds = [],
+ ariaLabel = areaVariant ? "Area chart" : "Line chart",
+ sync,
+ onActiveSeriesChange,
+ width,
+ height,
+ xAxis,
+ measuredPlot,
+ maxYTicks,
+ plotForTicks,
+ } = props;
+ const [hoveredIndex, setHoveredIndex] = useState<number>();
+ const [hoveredSeriesId, setHoveredSeriesId] = useState<string>();
+ const areaGradientId = useId();
+ const showXAxisLabels =
+ xAxis.type !== "category" || xAxis.labels !== "hidden";
+ const plotHeight = measuredPlot.height;
+ const yRangePadding = Math.min(MAX_VISIBLE_POINT_RADIUS, plotHeight / 2);
+
+ const data = useMemo<NormalizedDatum[]>(
+ () => normalizeLineChartData(props.data, props.xAxis.type),
+ [props.data, props.xAxis.type],
+ );
+ const stackedValues = useMemo(() => {
+ if (!areaStacked) return [];
+ return data.map((datum) => {
+ let positive = 0;
+ let negative = 0;
+ const offsets = new Map<string, { base: number; top: number }>();
+ for (const item of series) {
+ const value = datum.values[item.id];
+ if (typeof value !== "number" || !Number.isFinite(value)) continue;
+ const base = value >= 0 ? positive : negative;
+ const top = base + value;
+ offsets.set(item.id, { base, top });
+ if (value >= 0) positive = top;
+ else negative = top;
+ }
+ return offsets;
+ });
+ }, [areaStacked, data, series]);
+ const yScale = useMemo(() => {
+ const values = areaStacked
+ ? stackedValues.flatMap((offsets) =>
+ [...offsets.values()].flatMap(({ base, top }) => [base, top]),
+ )
+ : data.flatMap((datum) =>
+ series.flatMap((item) => {
+ const value = datum.values[item.id];
+ return typeof value === "number" && Number.isFinite(value)
+ ? [value]
+ : [];
+ }),
+ );
+ values.push(...thresholds.map((threshold) => threshold.value));
+ let min = Math.min(...values);
+ let max = Math.max(...values);
+ if (!Number.isFinite(min) || !Number.isFinite(max)) {
+ min = 0;
+ max = 1;
+ } else if (min === max) {
+ const padding = Math.max(Math.abs(min) * 0.1, 1);
+ min -= padding;
+ max += padding;
+ }
+ if (areaVariant) {
+ min = Math.min(0, min);
+ max = Math.max(0, max);
+ } else if (min < 0) max = Math.max(0, max);
+ return scaleLinear()
+ .domain([min, max])
+ .nice(maxYTicks)
+ .range([
+ measuredPlot.top + plotHeight - yRangePadding,
+ measuredPlot.top + yRangePadding,
+ ]);
+ }, [
+ data,
+ areaVariant,
+ areaStacked,
+ stackedValues,
+ maxYTicks,
+ measuredPlot.top,
+ plotHeight,
+ series,
+ thresholds,
+ yRangePadding,
+ ]);
+
+ const yTicks = yScale.ticks(maxYTicks);
+ const plot = plotForTicks(yTicks.map(valueFormatter));
+ const LEFT_MARGIN = plot.left;
+ const TOP_MARGIN = plot.top;
+ const plotWidth = plot.width;
+
+ const categoryScale = useMemo(
+ () =>
+ scalePoint<string>()
+ .domain(data.map((datum) => datum.key))
+ .range([LEFT_MARGIN, LEFT_MARGIN + plotWidth])
+ .padding(data.length > 1 ? 0 : 0.5),
+ [LEFT_MARGIN, 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]);
+ }, [LEFT_MARGIN, 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 maxXTicks = Math.max(2, Math.floor(plotWidth / APPROX_TIME_TICK_WIDTH));
+ const firstX = data[0]?.x;
+ const lastX = data[data.length - 1]?.x;
+ const categoryTickStep = Math.max(
+ 1,
+ Math.ceil((80 * Math.max(1, data.length - 1)) / Math.max(1, plotWidth)),
+ );
+ const categoryTickIndices = data.flatMap((_, index) =>
+ index % categoryTickStep === 0 &&
+ (index === 0 ||
+ ((data.length - 1 - index) * plotWidth) / Math.max(1, data.length - 1) >=
+ 80)
+ ? [index]
+ : [],
+ );
+ if (data.length > 1) categoryTickIndices.push(data.length - 1);
+ 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) ?? defaultTimeTickFormatter(value),
+ }))
+ : categoryTickIndices.map((index, tickIndex) => {
+ const datum = data[index]!;
+ const previous = categoryTickIndices[tickIndex - 1];
+ const next = categoryTickIndices[tickIndex + 1];
+ const gap = Math.min(
+ previous === undefined ? Infinity : index - previous,
+ next === undefined ? Infinity : next - index,
+ );
+ return {
+ key: datum.key,
+ x: getX(datum),
+ label: xAxis.tickFormatter?.(String(datum.x)) ?? String(datum.x),
+ maxWidth: Math.max(
+ 0,
+ (plotWidth * (Number.isFinite(gap) ? gap : 1)) /
+ Math.max(1, data.length - 1) -
+ CATEGORY_TICK_GAP,
+ ),
+ };
+ });
+ 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) ?? defaultTimeTickFormatter(datum.x)
+ );
+ }
+ 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, maxWidth: undefined },
+ ].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 areaGenerator = area<NormalizedDatum>()
+ .x((datum) => getX(datum))
+ .y0((datum) => yScale(Number(datum.values.__base ?? 0)))
+ .y1((datum) => yScale(Number(datum.values.__current)))
+ .defined((datum) => 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(stackedValues[index]?.get(item.id)?.top ?? 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 hasDistinctColors = series.some(
+ (item) => item.color !== series[0]?.color,
+ );
+ 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 }) => (
+ <CartesianChart
+ width={width}
+ height={height}
+ ariaLabel={ariaLabel}
+ plot={plot}
+ yTicks={yTicks}
+ y={yScale}
+ valueFormatter={valueFormatter}
+ categoryBoundaries={xAxis.type === "category"}
+ zeroY={
+ yScale.domain()[1] >= 0 &&
+ data.some((datum) =>
+ series.some((item) => (datum.values[item.id] ?? 0) < 0),
+ )
+ ? yScale(0)
+ : undefined
+ }
+ xAxis={
+ showXAxisLabels
+ ? {
+ ticks: visibleXTicks,
+ activeKey,
+ showCategoryTicks: xAxis.type === "category",
+ }
+ : undefined
+ }
+ >
+ {thresholds.map((threshold, index) => {
+ const y = yScale(threshold.value);
+ const regions = getThresholdRegions(
+ threshold,
+ y,
+ TOP_MARGIN,
+ 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, seriesIndex) => {
+ const proximityDimmed =
+ !hasConfiguredEmphasis &&
+ hoveredSeriesId !== undefined &&
+ hoveredSeriesId !== item.id;
+ const proximityEmphasized =
+ !hasConfiguredEmphasis && hoveredSeriesId === item.id;
+ const seriesData = data.map((datum, index) => ({
+ ...datum,
+ values: {
+ __current:
+ stackedValues[index]?.get(item.id)?.top ??
+ datum.values[item.id] ??
+ null,
+ __base: stackedValues[index]?.get(item.id)?.base ?? 0,
+ },
+ }));
+ const path = connectNulls
+ ? lineGenerator(
+ seriesData.filter((datum) => datum.values.__current !== null),
+ )
+ : lineGenerator(seriesData);
+ const fillPath = areaVariant
+ ? areaGenerator(
+ connectNulls
+ ? seriesData.filter(
+ (datum) => datum.values.__current !== null,
+ )
+ : seriesData,
+ )
+ : null;
+ const dimmed = item.emphasis === "dimmed" || proximityDimmed;
+ return (
+ <g
+ key={item.id}
+ className="transition-opacity duration-150"
+ opacity={areaVariant || !dimmed ? 1 : 0.2}
+ >
+ {areaVariant ? (
+ <>
+ <defs>
+ <linearGradient
+ id={`${areaGradientId}-${seriesIndex}`}
+ x1="0"
+ y1="0"
+ x2="0"
+ y2="1"
+ >
+ <stop
+ offset="0"
+ stopColor={`color-mix(in srgb, ${item.color} ${dimmed ? 15 : 75}%, hsl(var(--background)))`}
+ />
+ <stop
+ offset="1"
+ stopColor={`color-mix(in srgb, ${item.color} ${dimmed ? 5 : 25}%, hsl(var(--background)))`}
+ />
+ </linearGradient>
+ </defs>
+ <path
+ d={fillPath ?? undefined}
+ fill={`url(#${areaGradientId}-${seriesIndex})`}
+ pointerEvents="none"
+ />
+ </>
+ ) : null}
+ <path
+ d={path ?? undefined}
+ fill="none"
+ stroke={item.color}
+ strokeOpacity={areaVariant && dimmed ? 0.2 : undefined}
+ 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}
+
+ {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: hasDistinctColors ? item.color : undefined,
+ }));
+ 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);
+ if (!areaVariant) findNearestSeries(event, index);
+ }}
+ onPointerMove={(event) => {
+ setHoveredIndex(index);
+ sync?.onActiveKeyChange(datum.key);
+ referenceProps.onPointerMove(event);
+ if (!areaVariant) findNearestSeries(event, index);
+ }}
+ onPointerLeave={() => {
+ setHoveredIndex(undefined);
+ setHoveredSeriesId(undefined);
+ onActiveSeriesChange(undefined);
+ sync?.onActiveKeyChange(undefined);
+ referenceProps.onPointerLeave();
+ }}
+ />
+ {values.map(({ item, value }) => {
+ const pointY = yScale(
+ stackedValues[index]?.get(item.id)?.top ?? value,
+ );
+ const focusReferenceProps = getReferenceProps({
+ type: "items",
+ index,
+ heading,
+ focusPoint: { x: currentX, y: pointY },
+ emphasizedItemId: item.id,
+ items: tooltipItems,
+ });
+ return (
+ <circle
+ key={item.id}
+ cx={currentX}
+ cy={pointY}
+ 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>
+ );
+ })}
+ </CartesianChart>
+ )}
+ </ChartTooltip>
+ );
+}
diff --git a/web/src/components/ui/chart.tsx b/web/src/components/ui/chart.tsx
index 090eb1047f..2d6ec83c1d 100644
--- a/web/src/components/ui/chart.tsx
+++ b/web/src/components/ui/chart.tsx
@@ -1,4 +1,3 @@
-/* eslint-disable no-nested-ternary */
/* eslint-disable @repo/no-style-props, @repo/no-null-render */
"use client";
@@ -11,7 +10,6 @@ import type {
} from "recharts";
import { cn } from "@/src/utils/tailwind";
-import { Layer } from "@/src/components/design-system/Layer/Layer";
import { getPlainTextFromReactNode } from "@/src/utils/react-node-plain-text";
// Format: { THEME_NAME: CSS_SELECTOR }
@@ -348,94 +346,6 @@ const ChartTooltipContent = React.forwardRef<
);
ChartTooltipContent.displayName = "ChartTooltip";
-/** Horizontal gap between the hovered point and the tooltip's near edge. */
-const TOOLTIP_GAP_PX = 14;
-/**
- * Upper bound on the tooltip's width. Coordinates the two decisions that used
- * to fight each other: the side choice below guarantees the chosen side has
- * this much room whenever any side does, and the box never asks for more — so
- * hovering across a chart can't hit the "placed left but sized by the space on
- * the right" squeeze. Long series names past this truncate (full name in the
- * row's `title`). (LFE-10576)
- */
-const TOOLTIP_MAX_WIDTH_PX = 448;
-
-/**
- * Renders a chart tooltip into the app's `tooltip` overlay layer (see
- * `components/design-system/Layer/Layer.tsx`) so it escapes the chart card's
- * `overflow` clipping and always
- * paints on top — never cut off at the chart frame. Positioned at the hovered
- * point (recharts' `coordinate`, relative to the chart box) translated to screen
- * coordinates. (LFE-10549)
- *
- * Side placement and sizing are ONE decision: the tooltip goes right of the
- * point unless a full-width tooltip no longer fits there and the left side is
- * larger. Crucially the box is anchored by the edge NEAREST the point (`left`
- * when placed right, `right` when placed left) — never positioned at the point
- * and then translated across it. A translate happens after layout, so a
- * left-flipped tooltip laid out at `left: x` would still shrink-to-fit against
- * the RIGHT viewport edge and ellipsize every row at exactly the x-positions
- * where it flips. Anchoring by the near edge makes the browser size it against
- * the side it actually occupies. (LFE-10576)
- */
-function ChartTooltipPortal({
- active,
- coordinate,
- anchorRef,
- children,
-}: {
- active?: boolean;
- coordinate?: { x?: number; y?: number };
- anchorRef: React.RefObject<HTMLElement | null>;
- children: React.ReactNode;
-}) {
- if (
- !active ||
- !coordinate ||
- coordinate.x == null ||
- coordinate.y == null ||
- typeof window === "undefined"
- ) {
- return null;
- }
- const anchor = anchorRef.current;
- if (!anchor) return null;
- const rect = anchor.getBoundingClientRect();
- const x = rect.left + coordinate.x;
- const y = rect.top + coordinate.y;
- const spaceRight = window.innerWidth - x - TOOLTIP_GAP_PX;
- const spaceLeft = x - TOOLTIP_GAP_PX;
- const flipLeft = spaceRight < TOOLTIP_MAX_WIDTH_PX && spaceLeft > spaceRight;
- // Anchor the tooltip's bottom/top to the point near the viewport's
- // bottom/top so a tall multi-series tooltip can't spill its rows out of view
- // (the overlay layer no longer clips it). (LFE-10549)
- const translateY =
- y > window.innerHeight * 0.65
- ? "-100%"
- : y < window.innerHeight * 0.2
- ? "0%"
- : "-50%";
-
- return (
- <Layer name="tooltip">
- <div
- style={{
- position: "fixed",
- ...(flipLeft
- ? { right: window.innerWidth - x + TOOLTIP_GAP_PX }
- : { left: x + TOOLTIP_GAP_PX }),
- top: y,
- maxWidth: TOOLTIP_MAX_WIDTH_PX,
- transform: `translateY(${translateY})`,
- pointerEvents: "none",
- }}
- >
- {children}
- </div>
- </Layer>
- );
-}
-
type ChartLegendProps = React.ComponentProps<typeof RechartsPrimitive.Legend>;
function ChartLegend({ itemSorter = null, ...props }: ChartLegendProps) {
@@ -532,8 +442,6 @@ function getFillColor(
export {
ChartContainer,
ChartTooltip,
- ChartTooltipContent,
- ChartTooltipPortal,
ChartLegend,
ChartActiveReferenceLine,
useChart,
diff --git a/web/src/features/widgets/chart-library/AreaChartTimeSeries.tsx b/web/src/features/widgets/chart-library/AreaChartTimeSeries.tsx
index 0cbf27d965..6d6a6695a3 100644
--- a/web/src/features/widgets/chart-library/AreaChartTimeSeries.tsx
+++ b/web/src/features/widgets/chart-library/AreaChartTimeSeries.tsx
@@ -1,13 +1,7 @@
-/* eslint-disable no-nested-ternary */
-import React, { useMemo, useRef, useState } from "react";
-import {
- ChartActiveReferenceLine,
- ChartContainer,
- ChartTooltip,
- ChartTooltipContent,
- ChartTooltipPortal,
-} from "@/src/components/ui/chart";
-import { Area, AreaChart, CartesianGrid, XAxis, YAxis } from "recharts";
+import { useMemo } from "react";
+
+import { AreaChart as DesignSystemAreaChart } from "@/src/components/design-system/charts/AreaChart/AreaChart";
+import { type LineChartLegend } from "@/src/components/design-system/charts/LineChart/LineChart";
import { type ChartProps } from "@/src/features/widgets/chart-library/chart-props";
import {
formatMetric,
@@ -15,26 +9,19 @@ import {
groupDataByTimeDimension,
toFullMetricString,
} from "@/src/features/widgets/chart-library/utils";
-import { isolatedPointDot } from "@/src/features/widgets/chart-library/IsolatedPointDot";
-import { useChartTickBudget } from "@/src/features/widgets/chart-library/useChartTickBudget";
-import {
- prepareDenseSeries,
- prepareIsolatedPoints,
-} from "@/src/features/widgets/chart-library/prepareDenseSeries";
+import { prepareDenseSeries } from "@/src/features/widgets/chart-library/prepareDenseSeries";
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 {
seriesColor,
SeriesOverflowNote,
- TimeSeriesLegend,
- useSeriesLegend,
} from "@/src/features/widgets/chart-library/TimeSeriesLegend";
+import { getPlainTextFromReactNode } from "@/src/utils/react-node-plain-text";
-export const AreaChartTimeSeries: React.FC<ChartProps> = ({
+export function AreaChartTimeSeries({
data,
config = {
metric: {
@@ -44,23 +31,17 @@ export const AreaChartTimeSeries: React.FC<ChartProps> = ({
},
},
},
- accessibilityLayer = true,
metricFormatter = (value, options) => formatMetric(value, options),
legendPosition = "auto",
legendSummary = "none",
legendInteraction = "highlight",
maxVisibleSeries,
- syncId,
sync,
- subtleFill = false,
missingValue = "gap",
connectNulls = false,
hideXAxisLabels = false,
-}) => {
- const [selfHovered, setSelfHovered] = useState(false);
+}: Omit<ChartProps, "subtleFill">) {
const allDimensions = useMemo(() => getUniqueDimensions(data), [data]);
- // Make every (bucket, series) cell explicit — 0 for additive metrics, null
- // (a real gap) otherwise — so areas never draw across no-data buckets. (LFE-10694)
const groupedData = useMemo(
() =>
prepareDenseSeries(
@@ -70,194 +51,122 @@ export const AreaChartTimeSeries: React.FC<ChartProps> = ({
),
[data, allDimensions, missingValue],
);
- // A real value with gaps on both sides spans no area 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 hasNonTimestampBucket = groupedData.some(
+ (datum) => !parseChartTimestamp(datum.time_dimension),
+ );
const timeAxis = useMemo(
() =>
prepareTimeAxis(
- groupedData.map((d) => d.time_dimension),
- maxTicks,
+ groupedData.map((datum) => datum.time_dimension),
+ undefined,
{ hideCategoryTickLabels: hideXAxisLabels },
),
- [groupedData, maxTicks, hideXAxisLabels],
+ [groupedData, hideXAxisLabels],
);
-
- const { legendItems, onLegendClick, isRendered, isDimmed } = useSeriesLegend({
- data,
- dimensions,
- config,
- legendSummary,
- legendInteraction,
- maxVisibleSeries,
- });
-
- const tooltipFormatter = (value: number) =>
+ const dateAxis = useMemo(() => {
+ if (timeAxis.mode !== "category") return timeAxis;
+ const dates = groupedData.flatMap((datum) => {
+ const date = parseChartTimestamp(datum.time_dimension);
+ return date ? [date.getTime()] : [];
+ });
+ return dates.length ? prepareTimeAxis(dates) : timeAxis;
+ }, [groupedData, timeAxis]);
+ const formatValue = (value: number) =>
toFullMetricString(metricFormatter(value, { style: "compact" }));
- const syncedIndex = groupedData.findIndex(
- (item) =>
- String(
- parseChartTimestamp(item.time_dimension)?.getTime() ??
- item.time_dimension,
- ) === sync?.activeKey,
+ 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" || hasNonTimestampBucket ? (
+ <DesignSystemAreaChart
+ data={chartData}
+ series={chartSeries}
+ valueFormatter={formatValue}
+ connectNulls={connectNulls}
+ sync={sync}
+ legend={chartLegend}
+ xAxis={{
+ type: "category",
+ labels: hideXAxisLabels ? "hidden" : "visible",
+ tickFormatter: (value) => {
+ const date = parseChartTimestamp(value);
+ return date
+ ? dateAxis.formatTick(date.getTime())
+ : timeAxis.formatTick(value);
+ },
+ tooltipFormatter: (value) => {
+ const date = parseChartTimestamp(value);
+ return date
+ ? dateAxis.formatTooltip(date.getTime())
+ : timeAxis.formatTooltip(value);
+ },
+ }}
+ />
+ ) : (
+ <DesignSystemAreaChart
+ data={chartData.flatMap((datum) => {
+ const date = parseChartTimestamp(datum.x);
+ return date ? [{ ...datum, x: date }] : [];
+ })}
+ series={chartSeries}
+ valueFormatter={formatValue}
+ connectNulls={connectNulls}
+ 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 h-full w-full min-w-0 flex-col"
- // onMouseMove (not just onMouseEnter) so the tooltip un-gates even when the
- // cursor is already over the chart at mount/refresh (enter never fires). (LFE-10549)
- onMouseEnter={() => setSelfHovered(true)}
- onMouseMove={() => setSelfHovered(true)}
- onMouseLeave={() => {
- setSelfHovered(false);
- sync?.onActiveKeyChange(undefined);
- }}
- // Keyboard parity: recharts' accessibilityLayer lets Tab/arrow users move
- // the crosshair, but that fires no mouse event — un-gate the tooltip on
- // focus too, and re-gate only when focus leaves the chart. (LFE-10549)
- onFocus={() => setSelfHovered(true)}
- onBlur={(e) => {
- if (!e.currentTarget.contains(e.relatedTarget as Node | null)) {
- setSelfHovered(false);
- sync?.onActiveKeyChange(undefined);
- }
- }}
- >
- {series.total > dimensions.length && (
+ <div className="flex size-full min-w-0 flex-col">
+ {visibleSeries.total > dimensions.length ? (
<SeriesOverflowNote
visibleCount={dimensions.length}
- totalCount={series.total}
+ totalCount={visibleSeries.total}
/>
- )}
- <ChartContainer
- ref={chartBoxRef}
- config={config}
- className="min-h-0 flex-1"
- >
- <AreaChart
- accessibilityLayer={accessibilityLayer}
- 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
- 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}
- niceTicks="auto"
- tickFormatter={(value) => tooltipFormatter(Number(value))}
- />
- {dimensions.map((dimension, index) => {
- if (!isRendered(dimension)) return null;
- const muted = isDimmed(dimension);
- const isolated = isolatedPoints.get(dimension);
- return (
- <Area
- key={dimension}
- type="linear"
- dataKey={dimension}
- // Neighborless points span no area segment; a dot is the only
- // thing that keeps them visible. (LFE-10694)
- dot={
- isolated
- ? isolatedPointDot(isolated, seriesColor(index), muted)
- : false
- }
- stroke={seriesColor(index)}
- fill={seriesColor(index)}
- fillOpacity={muted ? 0.15 : subtleFill ? 0.3 : 0.75}
- strokeWidth={2.5}
- strokeOpacity={muted ? 0.2 : 1}
- connectNulls={connectNulls}
- isAnimationActive={false}
- />
- );
- })}
- <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)
- 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"
- />
- </ChartTooltipPortal>
- ) : null
- }
- />
- </AreaChart>
- </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/Chart.tsx b/web/src/features/widgets/chart-library/Chart.tsx
index 8d0654651d..7a7efe3e7f 100644
--- a/web/src/features/widgets/chart-library/Chart.tsx
+++ b/web/src/features/widgets/chart-library/Chart.tsx
@@ -209,7 +209,6 @@ const ChartComponent = ({
maxVisibleSeries={maxVisibleSeries}
syncId={syncId}
sync={sync}
- subtleFill={chartConfig?.subtle_fill}
missingValue={missingValue}
hideXAxisLabels={hideXAxisLabels}
/>
diff --git a/web/src/features/widgets/chart-library/ChartingPrinciples.stories.tsx b/web/src/features/widgets/chart-library/ChartingPrinciples.stories.tsx
index 8020ca2f25..d47bb732bb 100644
--- a/web/src/features/widgets/chart-library/ChartingPrinciples.stories.tsx
+++ b/web/src/features/widgets/chart-library/ChartingPrinciples.stories.tsx
@@ -592,7 +592,6 @@ export const AreaGaps = meta.story({
<AreaChartTimeSeries
data={buildGappedData(staggeredGapSeries)}
missingValue="gap"
- subtleFill
metricFormatter={msFormatter}
/>
</ExampleCard>
@@ -604,7 +603,6 @@ export const AreaGaps = meta.story({
<AreaChartTimeSeries
data={buildGappedData(twoEras)}
missingValue="zero"
- subtleFill
/>
</ExampleCard>
</div>
diff --git a/web/src/features/widgets/chart-library/IsolatedPointDot.tsx b/web/src/features/widgets/chart-library/IsolatedPointDot.tsx
deleted file mode 100644
index c72c234af9..0000000000
--- a/web/src/features/widgets/chart-library/IsolatedPointDot.tsx
+++ /dev/null
@@ -1,36 +0,0 @@
-import React from "react";
-
-/**
- * Builds a recharts `dot` renderer that marks ONLY a series' isolated points
- * (see `prepareIsolatedPoints`). With honest gaps (`connectNulls` off), a
- * value with no drawable neighbor spans no line segment — this dot is the only
- * thing that makes it visible. All other points render nothing, keeping lines
- * clean. (LFE-10694)
- */
-export const isolatedPointDot = (
- isolated: Set<number>,
- color: string,
- muted: boolean,
-) =>
- function IsolatedPointDot(props: {
- key?: React.Key | null;
- cx?: number;
- cy?: number;
- index?: number;
- }): React.ReactElement<SVGElement> {
- const { key, cx, cy, index } = props;
- if (cx == null || cy == null || index == null || !isolated.has(index)) {
- return <g key={key} />;
- }
- return (
- <circle
- key={key}
- cx={cx}
- cy={cy}
- r={3}
- fill={color}
- fillOpacity={muted ? 0.2 : 1}
- stroke="none"
- />
- );
- };
diff --git a/web/src/features/widgets/chart-library/LineChartTimeSeries.tsx b/web/src/features/widgets/chart-library/LineChartTimeSeries.tsx
index 9e5e97f941..961f4eeec2 100644
--- a/web/src/features/widgets/chart-library/LineChartTimeSeries.tsx
+++ b/web/src/features/widgets/chart-library/LineChartTimeSeries.tsx
@@ -97,6 +97,9 @@ export function LineChartTimeSeries({
[data, allDimensions],
);
const dimensions = visibleSeries.visible;
+ const hasNonTimestampBucket = groupedData.some(
+ (datum) => !parseChartTimestamp(datum.time_dimension),
+ );
const timeAxis = useMemo(
() =>
prepareTimeAxis(
@@ -106,6 +109,14 @@ export function LineChartTimeSeries({
),
[groupedData, hideXAxisLabels],
);
+ const dateAxis = useMemo(() => {
+ if (timeAxis.mode !== "category") return timeAxis;
+ const dates = groupedData.flatMap((datum) => {
+ const date = parseChartTimestamp(datum.time_dimension);
+ return date ? [date.getTime()] : [];
+ });
+ return dates.length ? prepareTimeAxis(dates) : timeAxis;
+ }, [groupedData, timeAxis]);
const formatValue = (value: number) =>
toFullMetricString(metricFormatter(value, { style: "compact" }));
const chartData = useMemo(
@@ -144,7 +155,7 @@ export function LineChartTimeSeries({
};
}
const chart =
- timeAxis.mode === "category" ? (
+ timeAxis.mode === "category" || hasNonTimestampBucket ? (
<DesignSystemLineChart
data={chartData}
series={chartSeries}
@@ -157,8 +168,18 @@ export function LineChartTimeSeries({
xAxis={{
type: "category",
labels: hideXAxisLabels ? "hidden" : "visible",
- tickFormatter: (value) => timeAxis.formatTick(value),
- tooltipFormatter: (value) => timeAxis.formatTooltip(value),
+ tickFormatter: (value) => {
+ const date = parseChartTimestamp(value);
+ return date
+ ? dateAxis.formatTick(date.getTime())
+ : timeAxis.formatTick(value);
+ },
+ tooltipFormatter: (value) => {
+ const date = parseChartTimestamp(value);
+ return date
+ ? dateAxis.formatTooltip(date.getTime())
+ : timeAxis.formatTooltip(value);
+ },
}}
/>
) : (
diff --git a/web/src/features/widgets/chart-library/TimeAxisTick.tsx b/web/src/features/widgets/chart-library/TimeAxisTick.tsx
index 7bded27777..eadecb6c44 100644
--- a/web/src/features/widgets/chart-library/TimeAxisTick.tsx
+++ b/web/src/features/widgets/chart-library/TimeAxisTick.tsx
@@ -58,14 +58,3 @@ export function timeAxisTick(
);
};
}
-
-/** Visualiser helper: custom tick only on temporal axes (preparer stays React-free). */
-export function temporalAxisTickProp(
- timeAxis: { mode: string; formatTick: (raw: unknown) => string },
- lastValue: unknown,
-):
- | { tick: (props: XAxisTickContentProps) => ReactNode }
- | Record<string, never> {
- if (timeAxis.mode === "category") return {};
- return { tick: timeAxisTick(timeAxis.formatTick, lastValue) };
-}
diff --git a/web/src/features/widgets/chart-library/TimeSeriesLegend.tsx b/web/src/features/widgets/chart-library/TimeSeriesLegend.tsx
index df2d6eff85..00ca7ea125 100644
--- a/web/src/features/widgets/chart-library/TimeSeriesLegend.tsx
+++ b/web/src/features/widgets/chart-library/TimeSeriesLegend.tsx
@@ -1,152 +1,7 @@
-/* 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,
- type LegendInteraction,
- type LegendSummaryMode,
-} 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";
-
/** The 8-slot chart palette, cycled by series index (matches the series fills). */
export const seriesColor = (index: number): string =>
`hsl(var(--chart-${(index % 8) + 1}))`;
-export type LegendItem = {
- dimension: string;
- /**
- * Display label — the chart config's label for this series, falling back to
- * the raw dimension: the same chain the tooltip resolves a row name through
- * (`ChartTooltipContent`), so legend and tooltip can never disagree about
- * what a series is called. (LFE-10576)
- */
- label: React.ReactNode;
- /** Position in the dimension list — pins the swatch color to the series fill. */
- colorIndex: number;
- color: string;
- /** Per-series summary under the active mode, or `null` when there's nothing to show. */
- summary: number | null;
- /** Greyed in the legend: muted (highlight mode) or hidden (toggle mode). */
- dimmed: boolean;
- /** Highlight mode only: this is the actively-focused series (clicking it clears focus). */
- focused: boolean;
-};
-
-/**
- * Owns the per-series legend state for a multi-series time chart: the displayed
- * summary, the focus-vs-toggle interaction, and the optional top-N default that
- * tames overloaded charts. Returns presentation-ready legend items plus the two
- * predicates the chart needs — whether to draw a series, and whether to mute it.
- *
- * Shared by the line/area/bar time-series charts so they stay consistent.
- */
-export function useSeriesLegend({
- data,
- dimensions,
- config,
- legendSummary = "none",
- legendInteraction = "highlight",
- maxVisibleSeries,
-}: {
- data: DataPoint[];
- dimensions: string[];
- /** Resolves display labels (see {@link LegendItem.label}). */
- config?: ChartConfig;
- legendSummary?: LegendSummaryMode;
- legendInteraction?: LegendInteraction;
- maxVisibleSeries?: number;
-}): {
- legendItems: LegendItem[];
- onLegendClick: (dimension: string) => void;
- isRendered: (dimension: string) => boolean;
- isDimmed: (dimension: string) => boolean;
- /** True when a series is click-focused (highlight mode) — gates hover effects. */
- isHighlightActive: boolean;
-} {
- const summaries = useMemo(
- () => (legendSummary === "none" ? null : getDimensionSummaries(data)),
- [data, legendSummary],
- );
-
- // Seed the top-N visible set by additive magnitude (chart metrics are
- // non-negative, so a plain sum ranks "biggest series" well enough).
- const initialHidden = useMemo(() => {
- if (legendInteraction !== "toggle" || maxVisibleSeries === undefined) {
- return new Set<string>();
- }
- const magnitude = getDimensionSummaries(data);
- const keep = new Set(
- [...dimensions]
- .sort(
- (a, b) =>
- (magnitude.get(b) ?? -Infinity) - (magnitude.get(a) ?? -Infinity),
- )
- .slice(0, Math.max(0, maxVisibleSeries)),
- );
- return new Set(dimensions.filter((dimension) => !keep.has(dimension)));
- }, [data, dimensions, legendInteraction, maxVisibleSeries]);
-
- const [highlighted, setHighlighted] = useState<string | null>(null);
- const [hidden, setHidden] = useState<Set<string>>(initialHidden);
-
- // Re-seed when the series SET or overload config changes (e.g. data reloads).
- // Sort before stringifying so the key is order-insensitive: when the top-N
- // preparer reorders an unchanged set (two near-equal series swap rank on a
- // refresh), we must NOT wipe the user's highlight/hide selections.
- const seedKey = `${legendInteraction}|${maxVisibleSeries ?? ""}|${JSON.stringify([...dimensions].sort())}`;
- const prevSeedKey = useRef(seedKey);
- useEffect(() => {
- if (prevSeedKey.current === seedKey) return;
- prevSeedKey.current = seedKey;
- setHighlighted(null);
- setHidden(initialHidden);
- }, [seedKey, initialHidden]);
-
- const onLegendClick = (dimension: string) => {
- if (legendInteraction === "toggle") {
- setHidden((prev) => {
- const next = new Set(prev);
- if (next.has(dimension)) next.delete(dimension);
- else next.add(dimension);
- return next;
- });
- } else {
- setHighlighted((prev) => (prev === dimension ? null : dimension));
- }
- };
-
- const isRendered = (dimension: string) =>
- legendInteraction === "toggle" ? !hidden.has(dimension) : true;
-
- const isDimmed = (dimension: string) =>
- legendInteraction === "toggle"
- ? hidden.has(dimension)
- : highlighted !== null && highlighted !== dimension;
-
- const legendItems: LegendItem[] = dimensions.map((dimension, index) => ({
- dimension,
- label: config?.[dimension]?.label ?? dimension,
- colorIndex: index,
- color: seriesColor(index),
- summary: summaries?.get(dimension) ?? null,
- dimmed: isDimmed(dimension),
- focused: legendInteraction !== "toggle" && highlighted === dimension,
- }));
-
- const isHighlightActive =
- legendInteraction !== "toggle" && highlighted !== null;
-
- return {
- legendItems,
- onLegendClick,
- isRendered,
- isDimmed,
- isHighlightActive,
- };
-}
-
/**
* Honest "we didn't draw everything" caption for charts whose breakdown
* overflowed the render cap (see {@link prepareVisibleSeries}). Rendered even
@@ -166,70 +21,3 @@ export function SeriesOverflowNote({
</div>
);
}
-
-/**
- * Presentational legend row for the multi-series time charts. State and click
- * semantics come from {@link useSeriesLegend}; this only renders.
- */
-export function TimeSeriesLegend({
- items,
- interaction,
- onItemClick,
- formatSummary,
-}: {
- items: LegendItem[];
- interaction: LegendInteraction;
- onItemClick: (dimension: string) => void;
- formatSummary: (value: number) => string;
-}) {
- return (
- <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/useChartTickBudget.ts b/web/src/features/widgets/chart-library/useChartTickBudget.ts
deleted file mode 100644
index b71e6f4edb..0000000000
--- a/web/src/features/widgets/chart-library/useChartTickBudget.ts
+++ /dev/null
@@ -1,52 +0,0 @@
-import { useEffect, useRef, useState } from "react";
-
-// Approximate horizontal room one x-axis label needs (incl. a gap). Labels are
-// now single-unit ("2 PM" / "Jun 28" / "Jun 2026"), so ~64px is comfortable.
-const APPROX_LABEL_PX = 64;
-const AXIS_GUTTER_PX = 56;
-
-// Vertical room one y-axis label needs. Below it recharts silently drops
-// colliding labels and which ones survive is arbitrary — a 63px band came out
-// labelled "1" and "0.25", with no zero.
-const APPROX_Y_LABEL_PX = 28;
-
-/** Recharts' own YAxis default; the budget only ever thins below it. */
-const DEFAULT_Y_TICK_COUNT = 5;
-
-/**
- * Measures the chart's box and returns how many ticks comfortably fit on each
- * axis (`maxTicks` across, `maxYTicks` down). The preparer (`prepareTimeAxis`)
- * turns the x budget into the actual tick interval + labels — this hook only
- * measures.
- */
-export function useChartTickBudget() {
- const ref = useRef<HTMLDivElement>(null);
- const [size, setSize] = useState({ width: 0, height: 0 });
-
- useEffect(() => {
- const element = ref.current;
- if (!element) return;
- const observer = new ResizeObserver((entries) => {
- const box = entries[0]?.contentRect;
- setSize({ width: box?.width ?? 0, height: box?.height ?? 0 });
- });
- observer.observe(element);
- return () => observer.disconnect();
- }, []);
-
- const maxTicks =
- size.width > 0
- ? Math.max(2, Math.floor((size.width - AXIS_GUTTER_PX) / APPROX_LABEL_PX))
- : 6;
-
- // Recharts needs at least three ticks when an axis crosses zero.
- const maxYTicks =
- size.height > 0
- ? Math.min(
- DEFAULT_Y_TICK_COUNT,
- Math.max(3, Math.floor(size.height / APPROX_Y_LABEL_PX)),
- )
- : DEFAULT_Y_TICK_COUNT;
-
- return { ref, maxTicks, maxYTicks };
-}