Skip to content

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

fix(web): Chart improvements (#17900)

Ben Bachem2d19ff15c260
diff --git a/web/src/components/design-system/charts/AreaChart/AreaChart.stories.tsx b/web/src/components/design-system/charts/AreaChart/AreaChart.stories.tsx
index 1f01b474fb..ee602ccc6f 100644
--- a/web/src/components/design-system/charts/AreaChart/AreaChart.stories.tsx
+++ b/web/src/components/design-system/charts/AreaChart/AreaChart.stories.tsx
@@ -1,6 +1,6 @@
import { useState } from "react";
import preview from "../../../../../.storybook/preview";
-import { expect, userEvent, within } from "storybook/test";
+import { expect, fireEvent, userEvent, waitFor, within } from "storybook/test";
import { AreaChart } from "./AreaChart";
import { type LineChartLegend } from "../LineChart/LineChart";
import { AreaChartTimeSeries } from "@/src/features/widgets/chart-library/AreaChartTimeSeries";
@@ -152,6 +152,92 @@ const meta = preview.meta({
export const Default = meta.story({});
+export const TooltipBelowChart = meta.story({
+ name: "(Test) Tooltip Below Chart",
+ args: { scenario: "time" },
+ decorators: [
+ (Story) => (
+ <div className="h-40 w-[420px]">
+ <Story />
+ </div>
+ ),
+ ],
+ play: async ({ canvasElement }) => {
+ const hoverArea = canvasElement.querySelector<SVGRectElement>(
+ 'rect[fill="transparent"]',
+ );
+ if (!hoverArea) throw new Error("Chart hover area not found");
+ fireEvent.pointerMove(hoverArea, {
+ clientX: hoverArea.getBoundingClientRect().left + 4,
+ clientY: hoverArea.getBoundingClientRect().top + 40,
+ });
+ const tooltip = await within(canvasElement.ownerDocument.body).findByRole(
+ "tooltip",
+ );
+ await waitFor(() => {
+ const hoverBottom = hoverArea.getBoundingClientRect().bottom;
+ const tooltipBounds = tooltip.getBoundingClientRect();
+ expect(tooltipBounds.top).toBeLessThan(hoverBottom);
+ expect(tooltipBounds.bottom).toBeGreaterThan(hoverBottom);
+ });
+ },
+});
+
+export const SingleValueAnchor = meta.story({
+ name: "(Test) Single Value Anchor",
+ play: async ({ canvasElement }) => {
+ const hoverArea = canvasElement.querySelector<SVGRectElement>(
+ 'rect[fill="transparent"]',
+ );
+ if (!hoverArea) throw new Error("Missing hover area");
+ const chartBounds = hoverArea.ownerSVGElement?.getBoundingClientRect();
+ if (!chartBounds) throw new Error("Chart bounds missing");
+ const clientX = hoverArea.getBoundingClientRect().left + 4;
+ fireEvent.pointerMove(hoverArea, {
+ clientX,
+ clientY: chartBounds.top + 120,
+ });
+ const tooltip = await within(canvasElement.ownerDocument.body).findByRole(
+ "tooltip",
+ );
+ await waitFor(() => {
+ expect(tooltip.getBoundingClientRect().top).toBeGreaterThan(0);
+ });
+ const firstTop = tooltip.getBoundingClientRect().top;
+ fireEvent.pointerMove(hoverArea, {
+ clientX,
+ clientY: chartBounds.top + 200,
+ });
+ await waitFor(() => {
+ expect(tooltip.getBoundingClientRect().top).toBeCloseTo(firstTop, 0);
+ });
+ },
+});
+
+export const Intermittent = meta.story({
+ name: "(Test) Intermittent",
+ args: { scenario: "gaps" },
+ play: async ({ canvasElement }) => {
+ const labelsBeforeHover = canvasElement.querySelectorAll(
+ '[data-x-axis-label=""]',
+ ).length;
+ const hoverArea = canvasElement.querySelectorAll<SVGRectElement>(
+ 'rect[fill="transparent"]',
+ )[1];
+ if (!hoverArea) throw new Error("Missing hover area for data gap");
+ await userEvent.hover(hoverArea);
+ const tooltip = within(document.body).getByRole("tooltip");
+ await expect(tooltip).toHaveTextContent("No data available");
+ await expect(tooltip).toHaveTextContent("Sep 2, 2026");
+ const labels = Array.from(
+ canvasElement.querySelectorAll('[data-x-axis-label=""]'),
+ (label) => label.textContent,
+ );
+ await expect(labels).toHaveLength(labelsBeforeHover);
+ await expect(new Set(labels).size).toBe(labels.length);
+ },
+});
+
export const DenseCategories = meta.story({
name: "(Test) Dense Categories",
args: { scenario: "denseCategory" },
@@ -167,9 +253,20 @@ export const NarrowCategories = meta.story({
name: "(Test) Narrow Categories",
args: { scenario: "narrowCategory" },
play: async ({ canvasElement }) => {
- const labels = canvasElement.querySelectorAll('[data-x-axis-label=""]');
+ const labels = Array.from(
+ canvasElement.querySelectorAll<SVGTextElement>('[data-x-axis-label=""]'),
+ );
+ await expect(labels.length).toBeGreaterThan(0);
await expect(labels[0]).toHaveTextContent("Category 0");
- await expect(labels[labels.length - 1]).toHaveTextContent("Category 5");
+ await expect(
+ canvasElement.querySelectorAll("[data-category-tick]"),
+ ).toHaveLength(2);
+ const bounds = labels.map((label) => label.getBoundingClientRect());
+ for (let index = 1; index < bounds.length; index++) {
+ await expect(bounds[index]!.left).toBeGreaterThanOrEqual(
+ bounds[index - 1]!.right,
+ );
+ }
},
});
@@ -286,6 +383,37 @@ export const StackedAreas = meta.story({
},
});
+export const StackedAreasStableTicks = meta.story({
+ name: "(Test) Stacked Areas Stable Ticks",
+ args: { scenario: "stacked" },
+ decorators: [
+ (Story) => (
+ <div className="h-40 w-[420px]">
+ <Story />
+ </div>
+ ),
+ ],
+ play: async ({ canvasElement }) => {
+ const getLabels = () =>
+ Array.from(
+ canvasElement.querySelectorAll<SVGTextElement>("[data-x-axis-label]"),
+ (label) => [label.textContent, label.getAttribute("x")] as const,
+ );
+ const before = new Map(getLabels());
+ const hoverArea = canvasElement.querySelectorAll<SVGRectElement>(
+ 'rect[fill="transparent"]',
+ )[1];
+ if (!hoverArea) throw new Error("Second hover area not found");
+ await userEvent.hover(hoverArea);
+ const after = getLabels();
+ for (const [label, x] of after) {
+ if (label === "Sep 2") continue;
+ await expect(before.get(label)).toBe(x);
+ }
+ await expect(after.length).toBeLessThanOrEqual(before.size + 1);
+ },
+});
+
export const WithLegend = meta.story({
name: "(Test) With Legend",
args: {
diff --git a/web/src/components/design-system/charts/BarChart/BarChart.stories.tsx b/web/src/components/design-system/charts/BarChart/BarChart.stories.tsx
index 6f4f468478..8113625fc2 100644
--- a/web/src/components/design-system/charts/BarChart/BarChart.stories.tsx
+++ b/web/src/components/design-system/charts/BarChart/BarChart.stories.tsx
@@ -1,6 +1,7 @@
import preview from "../../../../../.storybook/preview";
import { expect, spyOn, userEvent, within } from "storybook/test";
+import { chartColors } from "../constants";
import { BarChart } from "./BarChart";
const data = [
@@ -58,13 +59,6 @@ export const KeyboardFocus = meta.story({
} finally {
copy.mockRestore();
}
- await expect(
- tooltip.querySelector("svg.lucide-check")?.parentElement,
- ).toHaveClass("visible");
- await expect(firstBar).toHaveAttribute("fill", "hsl(var(--chart-1))");
- await expect(
- canvas.getByRole("graphics-symbol", { name: "Beta: 24" }),
- ).toHaveAttribute("fill", expect.stringContaining("20%"));
await userEvent.tab();
await expect(
canvas.getByRole("graphics-symbol", { name: "Beta: 24" }),
@@ -78,13 +72,7 @@ export const CategoryHoverArea = meta.story({
const area = canvasElement.querySelector<SVGRectElement>(
"[data-bar-hover-area]",
);
- const bar = within(canvasElement).getByRole("graphics-symbol", {
- name: "Alpha: 12",
- });
if (!area) throw new Error("Hover area not found");
- await expect(Number(area.getAttribute("height"))).toBeGreaterThan(
- Number(bar.getAttribute("height")),
- );
await userEvent.hover(area);
const tooltip = await within(canvasElement.ownerDocument.body).findByRole(
"tooltip",
@@ -100,17 +88,52 @@ export const CategoryHoverArea = meta.story({
},
});
+export const TooltipFollowsBar = meta.story({
+ name: "(Test) Tooltip Follows Bar",
+ play: async ({ canvasElement }) => {
+ const canvas = within(canvasElement);
+ const bars = canvas.getAllByRole("graphics-symbol");
+ const areas = canvasElement.querySelectorAll<SVGRectElement>(
+ "[data-bar-hover-area]",
+ );
+ for (let index = 0; index < bars.length; index++) {
+ const bar = bars[index];
+ const area = areas[index];
+ if (!bar || !area) throw new Error("Bar or hover area not found");
+ await userEvent.hover(area);
+ const tooltip = await within(canvasElement.ownerDocument.body).findByRole(
+ "tooltip",
+ );
+ const referenceLine = canvasElement.querySelector(
+ "[data-active-reference-line]",
+ );
+ if (!referenceLine) throw new Error("Reference line not found");
+ await expect(referenceLine.compareDocumentPosition(bar)).toBe(
+ Node.DOCUMENT_POSITION_FOLLOWING,
+ );
+ const areaTop = tooltip.getBoundingClientRect().top;
+ await userEvent.hover(bar);
+ await expect(tooltip.getBoundingClientRect().top).toBeCloseTo(areaTop, 0);
+ if (index === 0) {
+ await expect(
+ tooltip.getBoundingClientRect().bottom,
+ ).toBeLessThanOrEqual(bar.getBoundingClientRect().top);
+ }
+ }
+ },
+});
+
export const CategoryColors = meta.story({
args: {
data: data.map((item, index) => ({
...item,
- color: ["#3a3dee", "#07b9d5", "#f18a42"][index],
+ color: chartColors[index],
})),
legend: {
items: data.map((item, index) => ({
id: item.label,
label: item.label,
- color: ["#3a3dee", "#07b9d5", "#f18a42"][index] ?? "",
+ color: chartColors[index] ?? "",
})),
},
},
@@ -121,7 +144,7 @@ export const CategoryColorTooltip = meta.story({
args: {
data: data.map((item, index) => ({
...item,
- color: ["#3a3dee", "#07b9d5", "#f18a42"][index],
+ color: chartColors[index],
})),
},
play: async ({ canvasElement }) => {
@@ -132,7 +155,7 @@ export const CategoryColorTooltip = meta.story({
);
await expect(tooltip.querySelector("svg rect")).toHaveAttribute(
"fill",
- "#3a3dee",
+ chartColors[0],
);
},
});
@@ -141,7 +164,7 @@ export const CategoryColorsWithoutLegend = meta.story({
args: {
data: data.map((item, index) => ({
...item,
- color: ["#3a3dee", "#07b9d5", "#f18a42"][index],
+ color: chartColors[index],
})),
},
});
@@ -153,7 +176,7 @@ export const CompactLegend = meta.story({
data: data.map((item, index) => ({
...item,
label: `production-evaluation-run-${item.label}-with-a-long-name`,
- color: ["#3a3dee", "#07b9d5", "#f18a42"][index],
+ color: chartColors[index],
})),
legend: {
items: data.map((item, index) => ({
@@ -185,10 +208,6 @@ export const ManyCategories = meta.story({
},
});
-export const SubtleFill = meta.story({
- args: { variant: "subtle" },
-});
-
export const LongLabels = meta.story({
name: "(Test) Long Labels",
args: {
@@ -201,9 +220,6 @@ export const LongLabels = meta.story({
const canvas = within(canvasElement);
const firstBar = canvas.getAllByRole("graphics-symbol")[0];
if (!firstBar) throw new Error("Bar not found");
- for (const label of canvasElement.querySelectorAll("[data-x-axis-label]")) {
- await expect(label).toHaveAttribute("text-anchor", "middle");
- }
await expect(
canvasElement.querySelector("[data-x-axis-label]"),
).toHaveTextContent(/…$/);
@@ -211,9 +227,6 @@ export const LongLabels = meta.story({
await expect(
canvasElement.querySelector("[data-active-x-axis-label]"),
).toHaveTextContent("production-evaluation-run-1-with-a-long-name");
- await expect(
- canvasElement.querySelector("[data-active-x-axis-label-background]"),
- ).toBeInTheDocument();
},
});
@@ -238,16 +251,11 @@ export const EdgeLabels = meta.story({
const label = canvasElement.querySelector<SVGTextElement>(
"[data-active-x-axis-label]",
);
- const background = canvasElement.querySelector<SVGRectElement>(
- "[data-active-x-axis-label-background]",
- );
- if (!label || !background) throw new Error("Active label not found");
+ if (!label) throw new Error("Active label not found");
const chartWidth = label.ownerSVGElement?.width.baseVal.value ?? 0;
- for (const element of [label, background]) {
- const bounds = element.getBBox();
- await expect(bounds.x).toBeGreaterThanOrEqual(0);
- await expect(bounds.x + bounds.width).toBeLessThanOrEqual(chartWidth);
- }
+ const bounds = label.getBBox();
+ await expect(bounds.x).toBeGreaterThanOrEqual(0);
+ await expect(bounds.x + bounds.width).toBeLessThanOrEqual(chartWidth);
}
},
});
@@ -272,9 +280,6 @@ export const FullyTruncatedLabels = meta.story({
await expect(
canvasElement.querySelectorAll("[data-x-axis-label]"),
).toHaveLength(0);
- await expect(
- canvasElement.querySelectorAll("[data-category-tick]"),
- ).toHaveLength(20);
const firstBar = canvas.getByRole("graphics-symbol", {
name: "Experiment 1: 1",
});
diff --git a/web/src/components/design-system/charts/ChartTooltip.stories.tsx b/web/src/components/design-system/charts/ChartTooltip.stories.tsx
index 1f76714255..188d594c62 100644
--- a/web/src/components/design-system/charts/ChartTooltip.stories.tsx
+++ b/web/src/components/design-system/charts/ChartTooltip.stories.tsx
@@ -49,6 +49,7 @@ async function focusTooltip(canvasElement: HTMLElement) {
const itemsData: ChartTooltipDemoProps["data"] = {
type: "items",
index: 0,
+ anchor: { type: "element" },
items: [
{ id: "api", label: "API", value: "$18.42", color: "#6366f1" },
{ id: "worker", label: "Worker", value: "$12.08", color: "#06b6d4" },
@@ -81,12 +82,30 @@ export const Items = meta.story({
},
});
+export const NoData = meta.story({
+ name: "(Test) No Data",
+ args: {
+ data: {
+ type: "empty",
+ index: 0,
+ anchor: { type: "element" },
+ heading: "September 22, 2026",
+ },
+ },
+ play: async ({ canvasElement }) => {
+ const tooltip = await focusTooltip(canvasElement);
+ await expect(tooltip).toHaveTextContent("September 22, 2026");
+ await expect(tooltip).toHaveTextContent("No data available");
+ },
+});
+
export const WithHeading = meta.story({
name: "(Test) With Heading",
args: {
data: {
type: "items",
index: 0,
+ anchor: { type: "element" },
heading: "September 22, 2026",
items: [
{ id: "api", label: "API", value: "1,240", color: "#6366f1" },
@@ -106,6 +125,7 @@ export const Emphasis = meta.story({
data: {
type: "items",
index: 0,
+ anchor: { type: "element" },
emphasizedItemId: "emphasized",
items: [
{
@@ -143,6 +163,7 @@ export const Primary = meta.story({
data: {
type: "primary",
index: 0,
+ anchor: { type: "element" },
label: "Claude Sonnet",
value: "31 (31%)",
color: "#6366f1",
@@ -164,6 +185,7 @@ export const PrimaryWithDetails = meta.story({
data: {
type: "primary",
index: 0,
+ anchor: { type: "element" },
heading: "Other",
label: "Combined slices",
value: "8 (8%)",
@@ -189,6 +211,7 @@ export const WithCopyHint = meta.story({
data: {
type: "primary",
index: 0,
+ anchor: { type: "element" },
label: "Alpha",
value: "12",
copyLabel: "Alpha",
@@ -235,6 +258,7 @@ export const LongContent = meta.story({
data: {
type: "items",
index: 0,
+ anchor: { type: "element" },
heading: "A deliberately long heading for a dense chart tooltip",
items: [
{
@@ -263,5 +287,25 @@ export const PointerHover = meta.story({
"tooltip",
);
await expect(tooltip).toBeVisible();
+ const bounds = tooltip.getBoundingClientRect();
+ await expect(bounds.left).toBeGreaterThanOrEqual(0);
+ await expect(bounds.right).toBeLessThanOrEqual(window.innerWidth);
+ await expect(bounds.top).toBeGreaterThanOrEqual(0);
+ await expect(bounds.bottom).toBeLessThanOrEqual(window.innerHeight);
+ },
+});
+
+export const ValuePointFallback = meta.story({
+ name: "(Test) Value Point Fallback",
+ args: {
+ data: { ...itemsData, anchor: { type: "point", x: 240, y: 40 } },
+ },
+ play: async ({ canvasElement }) => {
+ const tooltip = await focusTooltip(canvasElement);
+ const chart = within(canvasElement).getByLabelText("Tooltip story chart");
+ await expect(tooltip.getBoundingClientRect().top).toBeLessThan(
+ chart.getBoundingClientRect().top +
+ chart.getBoundingClientRect().height / 2,
+ );
},
});
diff --git a/web/src/components/design-system/charts/GroupedBarChart/GroupedBarChart.stories.tsx b/web/src/components/design-system/charts/GroupedBarChart/GroupedBarChart.stories.tsx
index 35bc6ecce8..61a3ee783a 100644
--- a/web/src/components/design-system/charts/GroupedBarChart/GroupedBarChart.stories.tsx
+++ b/web/src/components/design-system/charts/GroupedBarChart/GroupedBarChart.stories.tsx
@@ -65,7 +65,6 @@ export const LegendHighlight = meta.story({
await expect(
canvas.getByRole("graphics-symbol", { name: "First: 12" }),
).toHaveAttribute("fill", expect.stringContaining("20%"));
- await expect(canvas.getAllByRole("graphics-symbol")).toHaveLength(4);
await userEvent.click(
canvas.getByRole("button", { name: "Show all series" }),
);
@@ -79,7 +78,6 @@ export const LegendToggle = meta.story({
},
play: async ({ canvasElement }) => {
const canvas = within(canvasElement);
- await expect(canvas.getAllByRole("graphics-symbol")).toHaveLength(4);
await userEvent.click(canvas.getByRole("button", { name: "Hide Second" }));
await expect(
canvas.queryAllByRole("graphics-symbol", { name: /Second:/ }),
@@ -99,7 +97,6 @@ export const NegativeAndMissingValues = meta.story({
},
play: async ({ canvasElement }) => {
const canvas = within(canvasElement);
- await expect(canvas.getAllByRole("graphics-symbol")).toHaveLength(3);
await expect(
canvas.getByRole("graphics-symbol", { name: "First: -12" }),
).toBeInTheDocument();
@@ -133,7 +130,7 @@ export const ManyBuckets = meta.story({
).toHaveLength(100);
await expect(
canvasElement.querySelectorAll("[data-x-axis-label]").length,
- ).toBeLessThan(60);
+ ).toBe(0);
},
});
@@ -163,9 +160,6 @@ export const LongCategoryLabels = meta.story({
await expect(
canvasElement.querySelector("[data-active-x-axis-label]"),
).toHaveTextContent("dataset-run-1-transcription");
- await expect(
- canvasElement.querySelector("[data-active-x-axis-label-background]"),
- ).toBeInTheDocument();
},
});
diff --git a/web/src/components/design-system/charts/HistogramChart/HistogramChart.stories.tsx b/web/src/components/design-system/charts/HistogramChart/HistogramChart.stories.tsx
index d123124e93..bd329d6512 100644
--- a/web/src/components/design-system/charts/HistogramChart/HistogramChart.stories.tsx
+++ b/web/src/components/design-system/charts/HistogramChart/HistogramChart.stories.tsx
@@ -31,17 +31,12 @@ export const HistogramBinSpacing = meta.story({
const first = bars[0];
const second = bars[1];
if (!first || !second) throw new Error("Histogram bins not found");
- await expect(first).toHaveAttribute("rx", "0");
- await expect(
- Number(first.getAttribute("x")) + Number(first.getAttribute("width")) + 2,
- ).toBeCloseTo(Number(second.getAttribute("x")));
+ await expect(first.getBoundingClientRect().right).toBeLessThan(
+ second.getBoundingClientRect().left,
+ );
},
});
-export const SubtleFill = meta.story({
- args: { variant: "subtle" },
-});
-
export const ManyBins = meta.story({
args: {
data: Array.from({ length: 20 }, (_, index) => ({
@@ -88,7 +83,6 @@ export const InsufficientSpace = meta.story({
play: async ({ canvasElement }) => {
const canvas = within(canvasElement);
await expect(canvas.getByText("Insufficient space")).toBeInTheDocument();
- await expect(canvas.queryAllByRole("graphics-symbol")).toHaveLength(0);
},
});
diff --git a/web/src/components/design-system/charts/HorizontalBarChart/HorizontalBarChart.stories.tsx b/web/src/components/design-system/charts/HorizontalBarChart/HorizontalBarChart.stories.tsx
index 2d5fac743f..3270c0108b 100644
--- a/web/src/components/design-system/charts/HorizontalBarChart/HorizontalBarChart.stories.tsx
+++ b/web/src/components/design-system/charts/HorizontalBarChart/HorizontalBarChart.stories.tsx
@@ -24,6 +24,94 @@ const meta = preview.meta({
export const Default = meta.story({});
+export const SideTooltip = meta.story({
+ name: "(Test) Side Tooltip",
+ play: async ({ canvasElement }) => {
+ const bar = within(canvasElement).getByRole("graphics-symbol", {
+ name: "Alpha: 12",
+ });
+ bar.focus();
+ const tooltip = await within(canvasElement.ownerDocument.body).findByRole(
+ "tooltip",
+ );
+ await waitFor(() => {
+ const barBounds = bar.getBoundingClientRect();
+ const tooltipBounds = tooltip.getBoundingClientRect();
+ expect(
+ tooltipBounds.left >= barBounds.right ||
+ tooltipBounds.right <= barBounds.left,
+ ).toBe(true);
+ });
+ },
+});
+
+export const HoverTransition = meta.story({
+ name: "(Test) Hover Transition",
+ play: async ({ canvasElement }) => {
+ const bars =
+ canvasElement.querySelectorAll<SVGRectElement>("[data-bar-fill]");
+ const first = bars[0];
+ const second = bars[1];
+ if (!first || !second) throw new Error("Bars not found");
+ const hoverArea = first.parentElement?.querySelector<SVGRectElement>(
+ 'rect[fill="transparent"][aria-hidden="true"]',
+ );
+ if (!hoverArea) throw new Error("Hover area not found");
+ await userEvent.hover(hoverArea);
+ await expect(second).toHaveAttribute(
+ "fill",
+ expect.stringContaining("20%"),
+ );
+ },
+});
+
+export const HoverAcrossRowGap = meta.story({
+ name: "(Test) Hover Across Row Gap",
+ play: async ({ canvasElement }) => {
+ const bars =
+ canvasElement.querySelectorAll<SVGRectElement>("[data-bar-fill]");
+ const first = bars[0];
+ const second = bars[1];
+ const svg = canvasElement.querySelector<SVGSVGElement>(
+ "svg[aria-label='Horizontal bar chart']",
+ );
+ if (!first || !second || !svg) throw new Error("Chart bars not found");
+ const hoverArea = first.parentElement?.querySelector<SVGRectElement>(
+ 'rect[fill="transparent"][aria-hidden="true"]',
+ );
+ if (!hoverArea) throw new Error("Hover area not found");
+ await userEvent.hover(hoverArea);
+ const firstBounds = first.getBoundingClientRect();
+ const secondBounds = second.getBoundingClientRect();
+ const gapTarget = canvasElement.ownerDocument.elementFromPoint(
+ firstBounds.left + 20,
+ (firstBounds.bottom + secondBounds.top) / 2,
+ );
+ if (!gapTarget || !svg.contains(gapTarget)) {
+ throw new Error("Gap is not part of the chart hit area");
+ }
+ await userEvent.hover(gapTarget);
+ await expect(second).toHaveAttribute(
+ "fill",
+ expect.stringContaining("20%"),
+ );
+ await expect(
+ within(canvasElement.ownerDocument.body).getByRole("tooltip"),
+ ).toHaveTextContent("Alpha");
+ const secondHoverArea = second.parentElement?.querySelector<SVGRectElement>(
+ 'rect[fill="transparent"][aria-hidden="true"]',
+ );
+ if (!secondHoverArea) throw new Error("Second hover area not found");
+ await userEvent.hover(secondHoverArea);
+ await expect(first).toHaveAttribute("fill", expect.stringContaining("20%"));
+ await userEvent.unhover(secondHoverArea);
+ await expect(first).not.toHaveAttribute(
+ "fill",
+ expect.stringContaining("20%"),
+ );
+ },
+});
+
export const FillsAvailableHeight = meta.story({
name: "(Test) Fills Available Height",
play: async ({ canvasElement }) => {
@@ -35,9 +123,6 @@ export const FillsAvailableHeight = meta.story({
const first = bars[0];
const last = bars[bars.length - 1];
if (!first || !last || !svg) throw new Error("Chart bars not found");
- await expect(first.getAttribute("height")).toBe(
- last.getAttribute("height"),
- );
const topGap = Number(first.getAttribute("y")) - 26;
const bottomGap =
Number(svg.getAttribute("height")) -
@@ -46,8 +131,26 @@ export const FillsAvailableHeight = meta.story({
Number(last.getAttribute("height"));
await expect(topGap).toBeGreaterThan(1);
await expect(bottomGap).toBeCloseTo(topGap, 0);
- if (Number(svg.getAttribute("height")) >= 600) {
- await expect(topGap).toBeGreaterThan(12);
+ },
+});
+
+export const CenteredRowText = meta.story({
+ name: "(Test) Centered Row Text",
+ play: async ({ canvasElement }) => {
+ const bars =
+ canvasElement.querySelectorAll<SVGRectElement>("[data-bar-fill]");
+ for (const bar of bars) {
+ const row = bar.parentElement;
+ const texts = row?.querySelectorAll<SVGTextElement>("text");
+ if (!texts || texts.length !== 2) throw new Error("Row text not found");
+ const barBounds = bar.getBoundingClientRect();
+ const barCenter = (barBounds.top + barBounds.bottom) / 2;
+ for (const text of texts) {
+ const bounds = text.getBoundingClientRect();
+ await expect(
+ Math.abs((bounds.top + bounds.bottom) / 2 - barCenter),
+ ).toBeLessThan(2);
+ }
}
},
});
@@ -61,28 +164,12 @@ export const LayoutAndCopy = meta.story({
const widths = Array.from(bars, (bar) => Number(bar.getAttribute("width")));
await expect(widths[0]).toBeCloseTo((widths[1] ?? 0) / 2);
await expect(widths[2]).toBeCloseTo((widths[1] ?? 0) / 4);
- const rightTick = canvasElement.querySelector<SVGLineElement>(
- "[data-axis-tick]:last-child line",
- );
- const plotRight = Number(rightTick?.getAttribute("x1"));
- await expect(plotRight).toBeGreaterThan(
- Number(bars[1]?.getAttribute("width")),
- );
- const values = canvasElement.querySelectorAll<SVGTextElement>(
- 'text[text-anchor="end"]',
- );
- await expect(values[0]?.getAttribute("x")).toBe(
- values[1]?.getAttribute("x"),
- );
const bar = canvas.getByRole("graphics-symbol", { name: "Beta: -24" });
const hoverArea = bar.parentElement?.querySelector<SVGRectElement>(
"rect[fill='transparent'][aria-hidden='true']",
);
if (!hoverArea) throw new Error("Row hover area not found");
- await expect(Number(hoverArea.getAttribute("width"))).toBeGreaterThan(
- Number(bar.getAttribute("width")),
- );
await userEvent.hover(hoverArea);
const hoveredTooltip = await within(
canvasElement.ownerDocument.body,
@@ -92,17 +179,9 @@ export const LayoutAndCopy = meta.story({
const tooltip = await within(canvasElement.ownerDocument.body).findByRole(
"tooltip",
);
- await expect(tooltip).toHaveTextContent("Beta");
await expect(tooltip).toHaveTextContent(
"Click or press Enter to copy label",
);
- await expect(
- tooltip.querySelector("svg.lucide-check")?.parentElement,
- ).toHaveClass("invisible");
- await expect(bars[0]).toHaveAttribute(
- "fill",
- expect.stringContaining("20%"),
- );
const copy = spyOn(navigator.clipboard, "writeText").mockResolvedValue();
try {
@@ -178,6 +257,20 @@ export const NarrowWithLongValues = meta.story({
await expect(value.getBoundingClientRect().right).toBeLessThanOrEqual(
canvasElement.getBoundingClientRect().right,
);
+ const rightGridline = canvasElement.querySelector<SVGLineElement>(
+ "[data-axis-tick]:last-child line",
+ );
+ const nothing = within(canvasElement).getByRole("graphics-symbol", {
+ name: "Nothing: 0 units",
+ });
+ const row = nothing.parentElement;
+ const leader = row?.querySelector<SVGLineElement>("[data-leader-line]");
+ if (!rightGridline || !leader) {
+ throw new Error("Leader or gridline not found");
+ }
+ await expect(Number(leader.getAttribute("x2"))).toBeGreaterThan(
+ Number(rightGridline.getAttribute("x1")),
+ );
},
});
@@ -247,6 +340,43 @@ export const LongAndDuplicateLabels = meta.story({
},
});
+export const LabelOnRoomierSide = meta.story({
+ name: "(Test) Label On Roomier Side",
+ args: {
+ data: [
+ { label: "A long label that cannot fit in this bar", value: 100 },
+ { label: "A long label that cannot fit in this bar", value: 70 },
+ { label: "A long label that cannot fit in this bar", value: 10 },
+ ],
+ },
+ decorators: [
+ (Story) => (
+ <div className="h-40 w-[440px]">
+ <Story />
+ </div>
+ ),
+ ],
+ play: async ({ canvasElement }) => {
+ const bars =
+ canvasElement.querySelectorAll<SVGRectElement>("[data-bar-fill]");
+ const labels =
+ canvasElement.querySelectorAll<SVGTextElement>("[data-row-label]");
+ const large = bars[1];
+ const largeLabel = labels[1];
+ const small = bars[2];
+ const smallLabel = labels[2];
+ if (!large || !largeLabel || !small || !smallLabel) {
+ throw new Error("Chart rows not found");
+ }
+ await expect(largeLabel.getBoundingClientRect().left).toBeLessThan(
+ large.getBoundingClientRect().right,
+ );
+ await expect(
+ smallLabel.getBoundingClientRect().left,
+ ).toBeGreaterThanOrEqual(small.getBoundingClientRect().right);
+ },
+});
+
export const TinyBarsBesideOutlier = meta.story({
name: "(Test) Tiny Bars Beside Outlier",
args: {
@@ -296,6 +426,41 @@ export const TinyBarsBesideOutlier = meta.story({
},
});
+export const LeaderEndpoints = meta.story({
+ name: "(Test) Leader Endpoints",
+ args: {
+ data: [
+ { label: "[email protected]", value: 2032.81 },
+ { label: "tobias.wo...", value: 1762 },
+ { label: "[email protected]", value: 442.94 },
+ { label: "n/a", value: 77.15 },
+ { label: "fair-regression", value: 0.191997 },
+ ],
+ valueFormatter: (value: number) => `$${value.toLocaleString()}`,
+ },
+ decorators: [
+ (Story) => (
+ <div className="h-72 w-[800px]">
+ <Story />
+ </div>
+ ),
+ ],
+ play: async ({ canvasElement }) => {
+ const bars =
+ canvasElement.querySelectorAll<SVGRectElement>("[data-bar-fill]");
+ let visibleLeaders = 0;
+ for (const bar of bars) {
+ const row = bar.parentElement;
+ const leader = row?.querySelector<SVGLineElement>("[data-leader-line]");
+ if (!leader) throw new Error("Leader not found");
+ if (leader.getAttribute("visibility") === "visible") {
+ visibleLeaders++;
+ }
+ }
+ await expect(visibleLeaders).toBeGreaterThan(0);
+ },
+});
+
export const ManyRows = meta.story({
name: "(Test) Many Rows",
args: {
@@ -320,7 +485,6 @@ export const ManyRows = meta.story({
const lastBar = within(canvasElement).getByRole("graphics-symbol", {
name: "Category 30: 1",
});
- await expect(Number(lastBar.getAttribute("height"))).toBeCloseTo(14, 0);
lastBar.focus();
const tooltip = await within(canvasElement.ownerDocument.body).findByRole(
"tooltip",
diff --git a/web/src/components/design-system/charts/HorizontalBarChart/HorizontalBarChart.tsx b/web/src/components/design-system/charts/HorizontalBarChart/HorizontalBarChart.tsx
index 4bd9850a03..e44fb2d436 100644
--- a/web/src/components/design-system/charts/HorizontalBarChart/HorizontalBarChart.tsx
+++ b/web/src/components/design-system/charts/HorizontalBarChart/HorizontalBarChart.tsx
@@ -3,13 +3,17 @@
import { scaleLinear } from "d3-scale";
import { ChartContainer } from "@/src/components/design-system/charts/ChartContainer";
-import { INACTIVE_CHART_COLOR_STRENGTH } from "@/src/components/design-system/charts/constants";
+import {
+ CHART_TRANSITION_DURATION,
+ INACTIVE_CHART_COLOR_STRENGTH,
+} from "@/src/components/design-system/charts/constants";
import type { BarChartDatum } from "@/src/components/design-system/internal/charts/BarChartCore";
import { CARTESIAN_CHART_INSETS } from "@/src/components/design-system/internal/charts/CartesianLayout";
import { ChartTooltip } from "@/src/components/design-system/internal/charts/ChartTooltip";
const MIN_ROW_PX = 14;
const CHARACTER_WIDTH = 7;
+const MAX_GRIDLINE_TO_VALUE_GAP = 24;
export function HorizontalBarChart({
data,
@@ -83,19 +87,26 @@ export function HorizontalBarChart({
});
return (
- <ChartTooltip>
- {({ activeIndex, getReferenceProps }) => (
+ <ChartTooltip placementStrategy="horizontal">
+ {({ activeIndex, hideTooltip, getReferenceProps }) => (
<div
className="size-full overflow-x-hidden overflow-y-auto"
data-testid="top-list-chart"
>
<svg
+ onPointerLeave={hideTooltip}
width={width}
height={contentHeight}
role="group"
aria-label="Horizontal bar chart"
className="block"
>
+ <rect
+ width={width}
+ height={contentHeight}
+ fill="transparent"
+ aria-hidden="true"
+ />
<g aria-hidden="true">
{visibleTicks.map((tick) => {
const x = left + scale(tick) * plotWidth;
@@ -127,16 +138,17 @@ export function HorizontalBarChart({
const barWidth =
maxMagnitude > 0 ? scale(Math.abs(value)) * plotWidth : 0;
const y = top + gap + index * (rowHeight + gap);
- const outsideLabelWidth = Math.min(
- datum.label.length * CHARACTER_WIDTH + 8,
- Math.max(0, plotWidth - barWidth - 16),
+ const insideLabelRoom = Math.max(0, barWidth - 16);
+ const outsideLabelRoom = Math.max(
+ 0,
+ plotWidth - barWidth - 24,
);
const labelOutside =
- barWidth < datum.label.length * CHARACTER_WIDTH + 16 &&
- outsideLabelWidth >= 16;
+ insideLabelRoom < datum.label.length * CHARACTER_WIDTH &&
+ outsideLabelRoom > insideLabelRoom;
const labelRoom = labelOutside
- ? outsideLabelWidth - 8
- : Math.max(0, barWidth - 16);
+ ? outsideLabelRoom
+ : insideLabelRoom;
const maxCharacters = Math.floor(
labelRoom / CHARACTER_WIDTH,
);
@@ -146,11 +158,6 @@ export function HorizontalBarChart({
visibleLabel = `${datum.label.slice(0, Math.max(0, maxCharacters - 1))}…`;
}
const labelX = left + barWidth + 8;
- const leaderStart = labelOutside
- ? labelX + outsideLabelWidth + 8
- : labelX;
- const leaderEnd =
- valueRight - formattedValue.length * CHARACTER_WIDTH - 8;
const inactive =
activeIndex !== undefined && activeIndex !== index;
const inactiveTextColor = inactive
@@ -158,6 +165,7 @@ export function HorizontalBarChart({
: "hsl(var(--foreground))";
const tooltipData = {
type: "primary" as const,
+ anchor: { type: "element" as const },
index,
label: datum.label,
value: formattedValue,
@@ -167,13 +175,48 @@ export function HorizontalBarChart({
hint: "Click or press Enter to copy label",
copyLabel: datum.label,
};
- const { onPointerLeave, ...referenceProps } =
- getReferenceProps(tooltipData);
+ const {
+ onPointerLeave: _onPointerLeave,
+ ...referenceProps
+ } = getReferenceProps(tooltipData);
return (
<g
key={`${datum.label}-${index}`}
- onPointerLeave={onPointerLeave}
+ ref={(row) => {
+ if (!row) return;
+ const label =
+ row.querySelector<SVGTextElement>(
+ "[data-row-label]",
+ );
+ const value =
+ row.querySelector<SVGTextElement>(
+ "[data-row-value]",
+ );
+ const leader =
+ row.querySelector<SVGLineElement>(
+ "[data-leader-line]",
+ );
+ if (!label || !value || !leader) return;
+ const labelBounds = label.getBBox();
+ const valueBounds = value.getBBox();
+ const start = Math.max(
+ left + barWidth + 4,
+ labelBounds.x + labelBounds.width + 4,
+ );
+ const valueEnd = valueBounds.x - 4;
+ const gridlineX = left + plotWidth;
+ const end =
+ valueEnd - gridlineX > MAX_GRIDLINE_TO_VALUE_GAP
+ ? valueEnd
+ : Math.min(valueEnd, gridlineX);
+ leader.setAttribute("x1", String(start));
+ leader.setAttribute("x2", String(end));
+ leader.setAttribute(
+ "visibility",
+ end - start > 24 ? "visible" : "hidden",
+ );
+ }}
>
<rect
x={left}
@@ -196,6 +239,10 @@ export function HorizontalBarChart({
? `color-mix(in srgb, ${datum.color ?? color} ${INACTIVE_CHART_COLOR_STRENGTH}%, hsl(var(--background)))`
: (datum.color ?? color)
}
+ className="transition-[fill]"
+ style={{
+ transitionDuration: CHART_TRANSITION_DURATION,
+ }}
pointerEvents="none"
aria-hidden="true"
/>
@@ -209,13 +256,13 @@ export function HorizontalBarChart({
tabIndex={0}
aria-label={`${datum.label}: ${formattedValue}`}
className="outline-hidden focus-visible:outline-2 focus-visible:outline-offset-2"
- {...getReferenceProps(tooltipData)}
- onPointerLeave={undefined}
+ {...referenceProps}
/>
<text
+ data-row-label=""
x={labelOutside ? labelX : left + 8}
y={y + rowHeight / 2}
- dominantBaseline="middle"
+ dominantBaseline="central"
fontSize={12}
fill={
labelOutside || inactive
@@ -230,24 +277,21 @@ export function HorizontalBarChart({
>
{visibleLabel}
</text>
- {leaderEnd - leaderStart > 24 ? (
- <line
- data-leader-line=""
- x1={leaderStart}
- x2={leaderEnd}
- y1={y + rowHeight / 2}
- y2={y + rowHeight / 2}
- stroke="hsl(var(--muted-foreground))"
- strokeOpacity={inactive ? 0.2 : 0.4}
- strokeDasharray="3 3"
- aria-hidden="true"
- />
- ) : null}
+ <line
+ data-leader-line=""
+ y1={y + rowHeight / 2}
+ y2={y + rowHeight / 2}
+ stroke="hsl(var(--muted-foreground))"
+ strokeOpacity={inactive ? 0.2 : 0.4}
+ strokeDasharray="3 3"
+ aria-hidden="true"
+ />
<text
+ data-row-value=""
x={valueRight}
y={y + rowHeight / 2}
textAnchor="end"
- dominantBaseline="middle"
+ dominantBaseline="central"
fontSize={12}
fill={inactiveTextColor}
{...referenceProps}
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 e129f4d84b..ce90209927 100644
--- a/web/src/components/design-system/charts/LineChart/LineChart.stories.tsx
+++ b/web/src/components/design-system/charts/LineChart/LineChart.stories.tsx
@@ -1,5 +1,5 @@
import preview from "../../../../../.storybook/preview";
-import { expect, userEvent, waitFor, within } from "storybook/test";
+import { expect, fireEvent, userEvent, waitFor, within } from "storybook/test";
import {
LineChart,
type LineChartLegend,
@@ -16,6 +16,10 @@ type LineChartStoryProps = {
| "many-lines"
| "boundary-points"
| "negative-values"
+ | "intermittent"
+ | "intraday"
+ | "year-boundary"
+ | "monthly"
| "category-short-labels"
| "category-long-labels"
| "category-hidden-labels";
@@ -51,6 +55,10 @@ const LineChartDemo = (props: LineChartStoryProps) => {
if (props.variant === "many-lines") chartData = manyLinesData;
if (props.variant === "boundary-points") chartData = boundaryPointData;
if (props.variant === "negative-values") chartData = negativeData;
+ if (props.variant === "intermittent") chartData = intermittentData;
+ if (props.variant === "intraday") chartData = intradayData;
+ if (props.variant === "year-boundary") chartData = yearBoundaryData;
+ if (props.variant === "monthly") chartData = monthlyData;
if (props.variant === "empty") chartData = [];
const chartSeries = props.variant === "many-lines" ? manyLinesSeries : series;
@@ -90,6 +98,27 @@ const negativeData = [
{ x: new Date(Date.UTC(2026, 8, 2)), values: { api: -3, worker: null } },
];
+const intermittentData = [
+ { x: new Date(Date.UTC(2026, 8, 1)), values: { api: 8, worker: 3 } },
+ { 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 } },
+];
+
+const intradayData = Array.from({ length: 8 }, (_, index) => ({
+ x: new Date(Date.UTC(2026, 8, 1, index * 3)),
+ values: { api: index + 1, worker: index + 2 },
+}));
+
+const yearBoundaryData = [
+ { x: new Date(Date.UTC(2025, 11, 31)), values: { api: 8, worker: 3 } },
+ { x: new Date(Date.UTC(2026, 0, 1)), values: { api: 12, worker: 4 } },
+];
+
+const monthlyData = Array.from({ length: 12 }, (_, index) => ({
+ x: new Date(Date.UTC(2026, index, 1)),
+ values: { api: index + 1, worker: index + 2 },
+}));
+
const manyLinesSeries: LineChartSeries[] = Array.from(
{ length: 24 },
(_, index) => ({
@@ -141,6 +170,70 @@ const meta = preview.meta({
export const Default = meta.story({});
+export const TooltipBelowChart = meta.story({
+ name: "(Test) Tooltip Below Chart",
+ decorators: [
+ (Story) => (
+ <div className="h-40 w-[420px]">
+ <Story />
+ </div>
+ ),
+ ],
+ play: async ({ canvasElement }) => {
+ const hoverArea = canvasElement.querySelector<SVGRectElement>(
+ 'rect[fill="transparent"]',
+ );
+ if (!hoverArea) throw new Error("Chart hover area not found");
+ fireEvent.pointerMove(hoverArea, {
+ clientX: hoverArea.getBoundingClientRect().left + 4,
+ clientY: hoverArea.getBoundingClientRect().top + 40,
+ });
+ const tooltip = await within(canvasElement.ownerDocument.body).findByRole(
+ "tooltip",
+ );
+ await waitFor(() => {
+ const hoverBottom = hoverArea.getBoundingClientRect().bottom;
+ const tooltipBounds = tooltip.getBoundingClientRect();
+ expect(tooltipBounds.top).toBeLessThan(hoverBottom);
+ expect(tooltipBounds.bottom).toBeGreaterThan(hoverBottom);
+ });
+ },
+});
+
+export const OnCardSurface = meta.story({
+ name: "(Test) On Card Surface",
+ decorators: [
+ (Story) => (
+ <div className="bg-card h-dvh w-full">
+ <Story />
+ </div>
+ ),
+ ],
+ play: async ({ canvasElement }) => {
+ const hoverArea = canvasElement.querySelector<SVGRectElement>(
+ 'rect[fill="transparent"]',
+ );
+ if (!hoverArea) throw new Error("Hover area not found");
+ await userEvent.hover(hoverArea);
+ const activeLabel = canvasElement.querySelector<SVGTextElement>(
+ "[data-active-x-axis-label]",
+ );
+ if (!activeLabel) throw new Error("Active label not found");
+ await expect(
+ canvasElement.querySelector("[data-active-x-axis-label-background]"),
+ ).not.toBeInTheDocument();
+ const activeBounds = activeLabel.getBoundingClientRect();
+ for (const label of canvasElement.querySelectorAll<SVGTextElement>(
+ "[data-x-axis-label]:not([data-active-x-axis-label])",
+ )) {
+ const bounds = label.getBoundingClientRect();
+ await expect(
+ bounds.right <= activeBounds.left || bounds.left >= activeBounds.right,
+ ).toBe(true);
+ }
+ },
+});
+
export const BoundaryPoints = meta.story({
name: "(Test) Boundary Points",
args: { variant: "boundary-points" },
@@ -183,6 +276,72 @@ export const Empty = meta.story({
},
});
+export const Intermittent = meta.story({
+ name: "(Test) Intermittent",
+ args: { variant: "intermittent" },
+ play: async ({ canvasElement }) => {
+ const tickLabels = Array.from(
+ canvasElement.querySelectorAll('[data-x-axis-label=""]'),
+ (label) => label.textContent,
+ );
+ await expect(tickLabels).toEqual(["Sep 1", "Sep 2", "Sep 3"]);
+ const assertLabelsDoNotOverlap = () => {
+ const labels = Array.from(
+ canvasElement.querySelectorAll<SVGTextElement>(
+ '[data-x-axis-label=""]',
+ ),
+ (label) => label.getBoundingClientRect(),
+ ).sort((left, right) => left.left - right.left);
+ for (let index = 1; index < labels.length; index++) {
+ expect(labels[index]!.left).toBeGreaterThanOrEqual(
+ labels[index - 1]!.right,
+ );
+ }
+ };
+ assertLabelsDoNotOverlap();
+ const hoverArea = canvasElement.querySelectorAll<SVGRectElement>(
+ 'rect[fill="transparent"]',
+ )[1];
+ if (!hoverArea) throw new Error("Missing hover area for data gap");
+ await userEvent.hover(hoverArea);
+ await expect(within(document.body).getByRole("tooltip")).toHaveTextContent(
+ "No data available",
+ );
+ assertLabelsDoNotOverlap();
+ },
+});
+
+export const Intraday = meta.story({
+ args: { variant: "intraday" },
+});
+
+export const YearBoundary = meta.story({
+ name: "(Test) Year Boundary",
+ args: { variant: "year-boundary" },
+ play: async ({ canvasElement }) => {
+ const labels = Array.from(
+ canvasElement.querySelectorAll('[data-x-axis-label=""]'),
+ (label) => label.textContent,
+ );
+ await expect(labels.some((label) => label?.includes("2025"))).toBe(true);
+ await expect(labels.some((label) => label?.includes("2026"))).toBe(true);
+ },
+});
+
+export const Monthly = meta.story({
+ name: "(Test) Monthly",
+ args: { variant: "monthly" },
+ play: async ({ canvasElement }) => {
+ const labels = Array.from(
+ canvasElement.querySelectorAll('[data-x-axis-label=""]'),
+ (label) => label.textContent,
+ );
+ await expect(labels.length).toBeGreaterThan(1);
+ await expect(new Set(labels).size).toBe(labels.length);
+ await expect(labels.every((label) => label?.includes("2026"))).toBe(true);
+ },
+});
+
export const ManyLines = meta.story({
args: { variant: "many-lines" },
});
@@ -252,15 +411,13 @@ export const CategoryLongLabels = meta.story({
await expect(activeLabel).toHaveTextContent(categoryData[0]?.x ?? "");
await expect(activeLabel).toHaveAttribute("font-weight", "700");
await expect(
- canvasElement
- .querySelector("[data-active-x-axis-label-background]")
- ?.getAttribute("fill"),
- ).toContain("url(#");
+ canvasElement.querySelector("[data-active-x-axis-label-background]"),
+ ).not.toBeInTheDocument();
const renderedLabels = canvasElement.querySelectorAll(
"[data-x-axis-label]",
);
- await expect(renderedLabels).toHaveLength(categoryData.length);
+ await expect(renderedLabels.length).toBeLessThan(categoryData.length);
Array.from(renderedLabels)
.filter((label) => !label.hasAttribute("data-active-x-axis-label"))
.forEach((label) => {
@@ -313,10 +470,8 @@ export const KeyboardFocus = meta.story({
});
await expect(activeLabel).toHaveAttribute("font-weight", "700");
await expect(
- canvasElement
- .querySelector("[data-active-x-axis-label-background]")
- ?.getAttribute("fill"),
- ).toContain("url(#");
+ canvasElement.querySelector("[data-active-x-axis-label-background]"),
+ ).not.toBeInTheDocument();
const tooltip = await within(canvasElement.ownerDocument.body).findByRole(
"tooltip",
diff --git a/web/src/components/design-system/charts/PieChart/PieChart.stories.tsx b/web/src/components/design-system/charts/PieChart/PieChart.stories.tsx
index 90ecf1971f..b241d10503 100644
--- a/web/src/components/design-system/charts/PieChart/PieChart.stories.tsx
+++ b/web/src/components/design-system/charts/PieChart/PieChart.stories.tsx
@@ -39,11 +39,7 @@ export const HoverColors = meta.story({
name: "Claude Sonnet: 31",
});
- await expect(first).toHaveAttribute("fill", chartColors[0]);
- await expect(second).toHaveAttribute("fill", chartColors[1]);
-
await userEvent.hover(first);
- await expect(first).toHaveAttribute("fill", chartColors[0]);
await expect(second).toHaveAttribute(
"fill",
expect.stringContaining("20%"),
@@ -125,7 +121,6 @@ export const CombinedSmallSlices = meta.story({
const canvas = within(canvasElement);
const combinedSlice = canvas.getByLabelText("Other: 2");
- await expect(canvasElement.querySelectorAll("path")).toHaveLength(3);
combinedSlice.focus();
const tooltip = await within(canvasElement.ownerDocument.body).findByRole(
@@ -154,7 +149,6 @@ export const Empty = meta.story({
play: async ({ canvasElement }) => {
const canvas = within(canvasElement);
- await expect(canvasElement.querySelectorAll("circle")).toHaveLength(1);
await expect(canvas.getByText("0")).toBeInTheDocument();
await expect(canvas.getByText("Total")).toBeInTheDocument();
},
diff --git a/web/src/components/design-system/charts/PieChart/PieChart.tsx b/web/src/components/design-system/charts/PieChart/PieChart.tsx
index b18fa4c476..ea454d317c 100644
--- a/web/src/components/design-system/charts/PieChart/PieChart.tsx
+++ b/web/src/components/design-system/charts/PieChart/PieChart.tsx
@@ -9,6 +9,7 @@ import { ChartTooltip } from "@/src/components/design-system/internal/charts/Cha
import {
chartColors,
INACTIVE_CHART_COLOR_STRENGTH,
+ CHART_TRANSITION_DURATION,
} from "@/src/components/design-system/charts/constants";
import { cn } from "@/src/utils/tailwind";
@@ -183,13 +184,17 @@ function PieChartContent({
fill={fill}
stroke="hsl(var(--background))"
strokeWidth={isActive ? 4 : 3}
- className="outline-hidden transition-[fill] duration-100 focus-visible:outline-2 focus-visible:outline-offset-2"
+ className="outline-hidden transition-[fill] focus-visible:outline-2 focus-visible:outline-offset-2"
+ style={{
+ transitionDuration: CHART_TRANSITION_DURATION,
+ }}
role="graphics-symbol"
tabIndex={0}
aria-label={`${slice.data.label}: ${valueFormatter(slice.data.value)}`}
{...getReferenceProps({
type: "primary",
index,
+ anchor: { type: "pointer" },
label: slice.data.label,
value: `${valueFormatter(slice.data.value)} (${percentageFormatter.format(slice.data.value / totalValue)})`,
color,
diff --git a/web/src/components/design-system/charts/StackedBarChart/StackedBarChart.stories.tsx b/web/src/components/design-system/charts/StackedBarChart/StackedBarChart.stories.tsx
index 4f746063fb..a637890629 100644
--- a/web/src/components/design-system/charts/StackedBarChart/StackedBarChart.stories.tsx
+++ b/web/src/components/design-system/charts/StackedBarChart/StackedBarChart.stories.tsx
@@ -28,6 +28,28 @@ const meta = preview.meta({
export const Default = meta.story({});
+export const NoRoomForLabels = meta.story({
+ name: "(Test) No Room For Labels",
+ args: {
+ data: Array.from({ length: 20 }, (_, index) => ({
+ key: `A very long category label that cannot fit on the x axis ${index}`,
+ values: { api: 12, worker: 8 },
+ })),
+ },
+ decorators: [
+ (Story) => (
+ <div className="h-40 w-[320px]">
+ <Story />
+ </div>
+ ),
+ ],
+ play: async ({ canvasElement }) => {
+ await expect(
+ canvasElement.querySelectorAll("[data-x-axis-label]"),
+ ).toHaveLength(0);
+ },
+});
+
export const StackingAndTooltip = meta.story({
name: "(Test) Stacking and Tooltip",
play: async ({ canvasElement }) => {
@@ -45,7 +67,6 @@ export const StackingAndTooltip = meta.story({
await expect(tooltip).toHaveTextContent("Monday");
await expect(tooltip).toHaveTextContent("API");
await expect(tooltip).toHaveTextContent("Worker");
- await expect(canvas.getAllByRole("graphics-symbol")).toHaveLength(5);
},
});
@@ -102,7 +123,6 @@ export const LegendHighlight = meta.story({
play: async ({ canvasElement }) => {
const canvas = within(canvasElement);
const api = canvas.getByRole("graphics-symbol", { name: "API: 12" });
- const worker = canvas.getByRole("graphics-symbol", { name: "Worker: 8" });
await userEvent.click(
canvas.getByRole("button", { name: "Show only Worker" }),
);
@@ -110,12 +130,9 @@ export const LegendHighlight = meta.story({
"fill",
"color-mix(in srgb, hsl(var(--chart-1)) 20%, hsl(var(--background)))",
);
- await expect(worker).toHaveAttribute("fill", "hsl(var(--chart-2))");
- await expect(canvas.getAllByRole("graphics-symbol")).toHaveLength(5);
await userEvent.click(
canvas.getByRole("button", { name: "Show all series" }),
);
- await expect(api).toHaveAttribute("fill", "hsl(var(--chart-1))");
},
});
@@ -170,15 +187,24 @@ export const MissingBuckets = meta.story({
play: async ({ canvasElement }) => {
const canvas = within(canvasElement);
await expect(canvas.getAllByRole("graphics-symbol")).toHaveLength(3);
- const zero = canvas.getByRole("graphics-symbol", { name: "API: 0" });
- await expect(zero).not.toHaveAttribute("clip-path");
- await expect(zero).toHaveAttribute("height", "1");
+ canvas.getByRole("graphics-symbol", { name: "API: 0" });
await expect(
canvas.getByRole("button", { name: "Hide API" }),
).toHaveTextContent("Sum: 10");
await expect(
canvas.getByRole("button", { name: "Hide Worker" }),
).toHaveTextContent("Sum: 5");
+ const emptyBucket = canvasElement.querySelectorAll<SVGRectElement>(
+ 'rect[fill="transparent"]',
+ )[0];
+ if (!emptyBucket) throw new Error("Missing empty bucket hover area");
+ await userEvent.hover(emptyBucket);
+ await expect(
+ within(canvasElement.ownerDocument.body).getByRole("tooltip"),
+ ).toHaveTextContent("No data available");
+ await expect(
+ canvasElement.querySelector("[data-active-reference-line]"),
+ ).toBeInTheDocument();
},
});
@@ -195,9 +221,6 @@ export const NegativeStack = meta.story({
Number(api.getAttribute("y")) + Number(api.getAttribute("height")),
0,
);
- await expect(
- canvasElement.querySelector("[data-zero-baseline]"),
- ).toBeInTheDocument();
},
});
@@ -244,7 +267,7 @@ export const SyncedBucket = meta.story({
).toHaveTextContent("Tuesday");
await expect(
canvasElement.querySelector("[data-active-reference-line]"),
- ).not.toBeInTheDocument();
+ ).toBeInTheDocument();
},
});
diff --git a/web/src/components/design-system/charts/constants.ts b/web/src/components/design-system/charts/constants.ts
index 7b9ea2e2d5..57210e2007 100644
--- a/web/src/components/design-system/charts/constants.ts
+++ b/web/src/components/design-system/charts/constants.ts
@@ -1,12 +1,13 @@
export const chartColors = [
- "#3a3dee",
- "#07b9d5",
- "#71717a",
- "#a855f7",
- "#ebbd05",
- "#ef4343",
- "#82cb15",
- "#ec4699",
+ "#5f62f1",
+ "#058194",
+ "#76767f",
+ "#9f41f6",
+ "#917503",
+ "#eb1414",
+ "#53810e",
+ "#e2187d",
] as const;
export const INACTIVE_CHART_COLOR_STRENGTH = 20;
+export const CHART_TRANSITION_DURATION = "150ms";
diff --git a/web/src/components/design-system/internal/charts/BarChartCore.tsx b/web/src/components/design-system/internal/charts/BarChartCore.tsx
index 917cf0e2fe..8855808183 100644
--- a/web/src/components/design-system/internal/charts/BarChartCore.tsx
+++ b/web/src/components/design-system/internal/charts/BarChartCore.tsx
@@ -1,10 +1,13 @@
"use client";
-import { useId, useState } from "react";
+import { useId, useMemo, useState } from "react";
import { scaleLinear } from "d3-scale";
import { ChartContainer } from "@/src/components/design-system/charts/ChartContainer";
-import { INACTIVE_CHART_COLOR_STRENGTH } from "@/src/components/design-system/charts/constants";
+import {
+ CHART_TRANSITION_DURATION,
+ INACTIVE_CHART_COLOR_STRENGTH,
+} from "@/src/components/design-system/charts/constants";
import { CartesianChart } from "@/src/components/design-system/internal/charts/CartesianChart";
import { CartesianLayout } from "@/src/components/design-system/internal/charts/CartesianLayout";
import {
@@ -26,7 +29,6 @@ export type SingleBarChartCoreProps = {
data: BarChartDatum[];
valueFormatter?: (value: number) => string;
color?: string;
- variant?: "default" | "subtle";
hideXAxisLabels?: boolean;
zeroBaseline?: boolean;
ariaLabel?: string;
@@ -67,7 +69,6 @@ function SingleBarChart({
data,
valueFormatter = (value) => value.toLocaleString(),
color = "hsl(var(--chart-1))",
- variant = "default",
hideXAxisLabels = false,
zeroBaseline = true,
ariaLabel = "Bar chart",
@@ -106,7 +107,7 @@ function SingleBarChart({
max,
);
const domainPadding = Math.max(Math.abs(domainMin) * 0.1, 1);
- const plotHeight = measuredPlot.height;
+ let plotHeight = measuredPlot.height;
const yScale = scaleLinear()
.domain(
domainMin === domainMax
@@ -116,7 +117,7 @@ function SingleBarChart({
.nice(maxYTicks)
.range([measuredPlot.top + plotHeight, measuredPlot.top]);
const yTicks = yScale.ticks(maxYTicks);
- const plot = plotForTicks(yTicks.map(valueFormatter));
+ let plot = plotForTicks(yTicks.map(valueFormatter));
const leftMargin = plot.left;
const plotWidth = plot.width;
const xScale = createBarBandScale(
@@ -125,15 +126,30 @@ function SingleBarChart({
plotWidth,
barSpacing,
);
- const baseline = yScale(
- zeroBaseline || min < 0 ? 0 : (yScale.domain()[0] ?? 0),
- );
const xTicks = data.map((datum, index) => ({
key: String(index),
x: (xScale(index) ?? leftMargin) + xScale.bandwidth() / 2,
label: datum.label,
maxWidth: xScale.bandwidth() - 8,
}));
+ if (
+ !hideXAxisLabels &&
+ (xTicks.length === 0 ||
+ xTicks.every(
+ (tick) =>
+ Math.floor(tick.maxWidth / 7) <= 1 &&
+ tick.label.length > 1,
+ ))
+ ) {
+ plot = plotForTicks(yTicks.map(valueFormatter), {
+ showXAxisLabels: false,
+ });
+ plotHeight = plot.height;
+ yScale.range([plot.top + plotHeight, plot.top]);
+ }
+ const baseline = yScale(
+ zeroBaseline || min < 0 ? 0 : (yScale.domain()[0] ?? 0),
+ );
if (
width <= 0 ||
@@ -170,15 +186,21 @@ function SingleBarChart({
y={yScale}
valueFormatter={valueFormatter}
zeroY={min < 0 ? yScale(0) : undefined}
+ activeX={
+ activeIndex === undefined ||
+ barSpacing === "histogram"
+ ? undefined
+ : {
+ key: String(activeIndex),
+ x: xTicks[activeIndex]?.x ?? plot.left,
+ label: data[activeIndex]?.label ?? "",
+ }
+ }
xAxis={
hideXAxisLabels
? undefined
: {
ticks: xTicks,
- activeKey:
- activeIndex === undefined
- ? undefined
- : String(activeIndex),
showCategoryTicks: true,
alignment: "center",
}
@@ -195,16 +217,10 @@ function SingleBarChart({
const barTop = Math.min(y, baseline);
const barHeight = Math.abs(y - baseline);
const active = activeIndex === index;
- let colorStrength = 100;
- if (variant === "subtle") {
- colorStrength = active ? 60 : 30;
- }
- if (activeIndex !== undefined && !active) {
- colorStrength =
- variant === "subtle"
- ? 15
- : INACTIVE_CHART_COLOR_STRENGTH;
- }
+ const colorStrength =
+ activeIndex !== undefined && !active
+ ? INACTIVE_CHART_COLOR_STRENGTH
+ : 100;
const fill =
colorStrength === 100
? barColor
@@ -223,6 +239,11 @@ function SingleBarChart({
: (centerX + nextX + xScale.bandwidth() / 2) / 2;
const tooltipData = {
type: "primary" as const,
+ anchor: {
+ type: "bar" as const,
+ x: centerX,
+ y: barTop,
+ },
index,
label: tooltipValueLabel ?? datum.label,
value: valueFormatter(datum.value ?? 0),
@@ -266,7 +287,11 @@ function SingleBarChart({
role="graphics-symbol"
tabIndex={0}
aria-label={`${datum.label}: ${valueFormatter(datum.value)}`}
- className="outline-hidden transition-[fill] duration-150 focus-visible:outline-2 focus-visible:outline-offset-2"
+ className="outline-hidden transition-[fill] focus-visible:outline-2 focus-visible:outline-offset-2"
+ style={{
+ transitionDuration:
+ CHART_TRANSITION_DURATION,
+ }}
{...getReferenceProps(tooltipData)}
onPointerLeave={undefined}
/>
@@ -303,19 +328,25 @@ function MultiSeriesBarChart({
}: MultiSeriesBarChartCoreProps) {
const [hoveredIndex, setHoveredIndex] = useState<number>();
const clipId = useId();
- const summaries = new Map(
- series.map((item) => {
- const values = data.flatMap((datum) => {
- const value = datum.values[item.id];
- return typeof value === "number" && Number.isFinite(value)
- ? [value]
- : [];
- });
- return [
- item.id,
- values.length ? values.reduce((sum, value) => sum + value, 0) : null,
- ] as const;
- }),
+ const summaries = useMemo(
+ () =>
+ new Map(
+ series.map((item) => {
+ const values = data.flatMap((datum) => {
+ const value = datum.values[item.id];
+ return typeof value === "number" && Number.isFinite(value)
+ ? [value]
+ : [];
+ });
+ return [
+ item.id,
+ values.length
+ ? values.reduce((sum, value) => sum + value, 0)
+ : null,
+ ] as const;
+ }),
+ ),
+ [data, series],
);
const initialHidden = new Set<string>();
if (
@@ -356,27 +387,43 @@ function MultiSeriesBarChart({
if (hidden) hiddenIds.add(id);
else hiddenIds.delete(id);
}
- const visibleSeries = series.filter((item) => !hiddenIds.has(item.id));
+ const hiddenKey = series
+ .map((item) => (hiddenIds.has(item.id) ? "1" : "0"))
+ .join("");
+ const visibleSeries = useMemo(
+ () => series.filter((_, index) => hiddenKey[index] === "0"),
+ [series, hiddenKey],
+ );
const showLegend =
legend?.visibility === "visible" ||
(legend?.visibility === "auto" &&
(series.length > 1 || hiddenIds.size > 0));
- const totals = data.map((datum) => {
- let positive = 0;
- let negative = 0;
- for (const item of visibleSeries) {
- const value = datum.values[item.id];
- if (typeof value !== "number" || !Number.isFinite(value)) continue;
- if (value >= 0) positive += value;
- else negative += value;
- }
- return { positive, negative };
- });
- const individualValues = data.flatMap((datum) =>
- visibleSeries.flatMap((item) => {
- const value = datum.values[item.id];
- return typeof value === "number" && Number.isFinite(value) ? [value] : [];
- }),
+ const totals = useMemo(
+ () =>
+ data.map((datum) => {
+ let positive = 0;
+ let negative = 0;
+ for (const item of visibleSeries) {
+ const value = datum.values[item.id];
+ if (typeof value !== "number" || !Number.isFinite(value)) continue;
+ if (value >= 0) positive += value;
+ else negative += value;
+ }
+ return { positive, negative };
+ }),
+ [data, visibleSeries],
+ );
+ const individualValues = useMemo(
+ () =>
+ data.flatMap((datum) =>
+ visibleSeries.flatMap((item) => {
+ const value = datum.values[item.id];
+ return typeof value === "number" && Number.isFinite(value)
+ ? [value]
+ : [];
+ }),
+ ),
+ [data, visibleSeries],
);
const min =
layout === "grouped"
@@ -406,7 +453,7 @@ function MultiSeriesBarChart({
measuredPlot.top,
]);
const yTicks = y.ticks(maxYTicks);
- const plot = plotForTicks(yTicks.map(valueFormatter));
+ let plot = plotForTicks(yTicks.map(valueFormatter));
const x = createBarBandScale(
data.length,
plot.left,
@@ -492,6 +539,12 @@ function MultiSeriesBarChart({
previousTickRight = center + labelWidth / 2;
xTicks.push({ key: datum.key, x: center, label });
});
+ if (!hideXAxisLabels && xTicks.length === 0) {
+ plot = plotForTicks(yTicks.map(valueFormatter), {
+ showXAxisLabels: false,
+ });
+ y.range([plot.top + plot.height, plot.top]);
+ }
if (
width <= 0 ||
@@ -520,15 +573,22 @@ function MultiSeriesBarChart({
y={y}
valueFormatter={valueFormatter}
zeroY={min < 0 ? y(0) : undefined}
+ activeX={
+ activeIndex >= 0 && data[activeIndex]
+ ? {
+ key: data[activeIndex].key,
+ x:
+ (x(activeIndex) ?? plot.left) +
+ x.bandwidth() / 2,
+ label: tickFormatter(data[activeIndex].key),
+ }
+ : undefined
+ }
xAxis={
hideXAxisLabels
? undefined
: {
ticks: xTicks,
- activeKey:
- activeIndex >= 0
- ? data[activeIndex]?.key
- : undefined,
showCategoryTicks: layout === "grouped",
alignment: "center",
}
@@ -553,16 +613,47 @@ function MultiSeriesBarChart({
]
: [];
});
- const referenceProps = getReferenceProps({
- type: "items",
- index,
- heading: tooltipFormatter(datum.key),
- items: items.sort(
- (a, b) =>
- (datum.values[b.id] ?? 0) -
- (datum.values[a.id] ?? 0),
- ),
- });
+ const referenceProps = getReferenceProps(
+ items.length
+ ? {
+ type: "items",
+ index,
+ heading: tooltipFormatter(datum.key),
+ anchor: {
+ type: "point",
+ x: left + x.bandwidth() / 2,
+ y:
+ layout === "grouped"
+ ? Math.min(
+ y(0),
+ ...visibleSeries.flatMap((item) => {
+ const value =
+ datum.values[item.id];
+ return typeof value ===
+ "number" &&
+ Number.isFinite(value)
+ ? [y(value)]
+ : [];
+ }),
+ )
+ : y(totals[index]?.positive ?? 0),
+ },
+ items: items.sort(
+ (a, b) =>
+ (datum.values[b.id] ?? 0) -
+ (datum.values[a.id] ?? 0),
+ ),
+ }
+ : {
+ type: "empty",
+ index,
+ heading: tooltipFormatter(datum.key),
+ anchor: {
+ type: "chart-column",
+ x: left + x.bandwidth() / 2,
+ },
+ },
+ );
return (
<g key={`${datum.key}-${index}`}>
<defs>
@@ -674,7 +765,11 @@ function MultiSeriesBarChart({
tabIndex: 0,
"aria-label": `${item.label}: ${valueFormatter(value)}`,
className:
- "outline-hidden transition-[fill] duration-150 focus-visible:outline-2 focus-visible:outline-offset-2",
+ "outline-hidden transition-[fill] focus-visible:outline-2 focus-visible:outline-offset-2",
+ style: {
+ transitionDuration:
+ CHART_TRANSITION_DURATION,
+ },
...referenceProps,
onPointerEnter: (
event: React.PointerEvent<SVGElement>,
diff --git a/web/src/components/design-system/internal/charts/CartesianChart.tsx b/web/src/components/design-system/internal/charts/CartesianChart.tsx
index 144a5c0900..a5a145cdb7 100644
--- a/web/src/components/design-system/internal/charts/CartesianChart.tsx
+++ b/web/src/components/design-system/internal/charts/CartesianChart.tsx
@@ -1,6 +1,6 @@
"use client";
-import { useId, type ReactNode } from "react";
+import type { ReactNode } from "react";
import type { CartesianPlot } from "@/src/components/design-system/internal/charts/CartesianLayout";
@@ -51,7 +51,7 @@ function ChartGrid({
function ChartXAxis({
ticks,
- activeKey,
+ activeTick,
y,
width,
showCategoryTicks = false,
@@ -64,13 +64,12 @@ function ChartXAxis({
maxWidth?: number;
textAnchor?: "end";
}[];
- activeKey?: string;
+ activeTick?: { key: string; x: number; label: string };
y: number;
width: number;
showCategoryTicks?: boolean;
alignment?: "endpoints" | "center";
}) {
- const gradientId = useId();
const characterWidth = 7;
const hideLabels =
ticks.length > 0 &&
@@ -80,16 +79,87 @@ function ChartXAxis({
Math.floor(tick.maxWidth / characterWidth) <= 1 &&
tick.label.length > 1,
);
+ const axisTicks: typeof ticks = activeTick
+ ? [...ticks.filter((tick) => tick.key !== activeTick.key), activeTick].sort(
+ (left, right) => left.x - right.x,
+ )
+ : ticks;
+ const labels = axisTicks.map((tick, index) => {
+ let textAnchor: "start" | "middle" | "end" = "middle";
+ if (alignment === "endpoints" && axisTicks.length > 1) {
+ if (index === 0) textAnchor = "start";
+ else if (index === axisTicks.length - 1) textAnchor = "end";
+ }
+ const anchor = tick.textAnchor ?? textAnchor;
+ const maxCharacters = tick.maxWidth
+ ? Math.max(1, Math.floor(tick.maxWidth / characterWidth))
+ : undefined;
+ const label =
+ maxCharacters && tick.label.length > maxCharacters
+ ? `${tick.label.slice(0, Math.max(0, maxCharacters - 1))}…`
+ : tick.label;
+ const labelWidth = label.length * characterWidth;
+ const x = tick.x;
+ let left = x;
+ if (anchor === "middle") left = x - labelWidth / 2;
+ else if (anchor === "end") left = x - labelWidth;
+ return { tick, index, active: false, anchor, label, labelWidth, x, left };
+ });
+ const active = labels.find(({ tick }) => tick.key === activeTick?.key);
+ const activeLabelWidth = active
+ ? Math.min(width - 32, active.tick.label.length * characterWidth)
+ : 0;
+ const activeX = active
+ ? Math.max(
+ 16 + activeLabelWidth / 2,
+ Math.min(width - 16 - activeLabelWidth / 2, active.x),
+ )
+ : 0;
+ const activeLabel = active
+ ? {
+ ...active,
+ active: true,
+ label: active.tick.label,
+ labelWidth: activeLabelWidth,
+ x: activeX,
+ left: activeX - activeLabelWidth / 2,
+ }
+ : undefined;
+ const baseLabels = labels
+ .sort((left, right) => {
+ const leftEndpoint =
+ left.index === 0 || left.index === axisTicks.length - 1;
+ const rightEndpoint =
+ right.index === 0 || right.index === axisTicks.length - 1;
+ return Number(rightEndpoint) - Number(leftEndpoint);
+ })
+ .reduce<typeof labels>((visible, label) => {
+ if (
+ visible.some(
+ (other) =>
+ label.left < other.left + other.labelWidth + 8 &&
+ label.left + label.labelWidth + 8 > other.left,
+ )
+ ) {
+ return visible;
+ }
+ visible.push(label);
+ return visible;
+ }, []);
+ // Keep the resting tick selection stable while hovering: only remove labels
+ // that actually overlap the active label, without filling vacated slots.
+ const visibleLabels = [
+ ...baseLabels.filter(
+ (label) =>
+ !activeLabel ||
+ (label.tick.key !== activeLabel.tick.key &&
+ (label.left >= activeLabel.left + activeLabel.labelWidth + 8 ||
+ label.left + label.labelWidth + 8 <= activeLabel.left)),
+ ),
+ ...(activeLabel ? [activeLabel] : []),
+ ].sort((left, right) => left.index - right.index);
return (
<g>
- <defs>
- <linearGradient id={gradientId} x1="0" x2="1">
- <stop offset="0" stopColor="hsl(var(--background))" stopOpacity="0" />
- <stop offset="0.12" stopColor="hsl(var(--background))" />
- <stop offset="0.88" stopColor="hsl(var(--background))" />
- <stop offset="1" stopColor="hsl(var(--background))" stopOpacity="0" />
- </linearGradient>
- </defs>
{showCategoryTicks
? ticks.map((tick) => (
<line
@@ -105,89 +175,32 @@ function ChartXAxis({
))
: null}
{!hideLabels &&
- ticks
- .map((tick, index) => ({ tick, index }))
- .sort(
- (left, right) =>
- Number(left.tick.key === activeKey) -
- Number(right.tick.key === activeKey),
- )
- .map(({ tick, index }) => {
- const active = tick.key === activeKey;
- let textAnchor: "start" | "middle" | "end" = "middle";
- if (alignment === "endpoints") {
- if (ticks.length > 1 && index === 0) textAnchor = "start";
- else if (ticks.length > 1 && index === ticks.length - 1)
- textAnchor = "end";
- }
- const maxCharacters = tick.maxWidth
- ? Math.max(1, Math.floor(tick.maxWidth / characterWidth))
- : undefined;
- const label =
- !active && maxCharacters && tick.label.length > maxCharacters
- ? `${tick.label.slice(0, Math.max(0, maxCharacters - 1))}…`
- : tick.label;
- const activeLabelWidth = Math.min(
- width - 16,
- tick.label.length * characterWidth + 96,
- );
- const activeLabelX = Math.max(
- 8,
- Math.min(
- width - 8 - activeLabelWidth,
- tick.x - activeLabelWidth / 2,
- ),
- );
- const activeTextWidth = Math.min(
- width - 32,
- tick.label.length * characterWidth,
- );
- const activeTextX = Math.max(
- 16 + activeTextWidth / 2,
- Math.min(width - 16 - activeTextWidth / 2, tick.x),
- );
-
- return (
- <g key={tick.key}>
- {active ? (
- <rect
- data-active-x-axis-label-background=""
- x={activeLabelX}
- y={y + 4}
- width={activeLabelWidth}
- height={17}
- rx={2}
- fill={`url(#${gradientId})`}
- />
- ) : null}
- <text
- data-x-axis-label=""
- data-active-x-axis-label={active ? "" : undefined}
- x={active ? activeTextX : tick.x}
- y={y + 16}
- textAnchor={
- active ? "middle" : (tick.textAnchor ?? textAnchor)
- }
- textLength={
- active &&
- tick.label.length * characterWidth > activeTextWidth
- ? activeTextWidth
- : undefined
- }
- lengthAdjust="spacingAndGlyphs"
- fill={
- active
- ? "hsl(var(--foreground))"
- : "hsl(var(--muted-foreground))"
- }
- fontSize={12}
- fontWeight={active ? 700 : undefined}
- >
- {label}
- </text>
- </g>
- );
- })}
+ visibleLabels.map(({ tick, active, anchor, label, x, labelWidth }) => (
+ <g key={tick.key}>
+ <text
+ data-x-axis-label=""
+ data-active-x-axis-label={active ? "" : undefined}
+ x={x}
+ y={y + 16}
+ textAnchor={active ? "middle" : anchor}
+ textLength={
+ active && tick.label.length * characterWidth > labelWidth
+ ? labelWidth
+ : undefined
+ }
+ lengthAdjust="spacingAndGlyphs"
+ fill={
+ active
+ ? "hsl(var(--foreground))"
+ : "hsl(var(--muted-foreground))"
+ }
+ fontSize={12}
+ fontWeight={active ? 700 : undefined}
+ >
+ {label}
+ </text>
+ </g>
+ ))}
</g>
);
}
@@ -237,6 +250,7 @@ export function CartesianChart({
categoryBoundaries = false,
zeroY,
xAxis,
+ activeX,
children,
}: {
width: number;
@@ -257,10 +271,10 @@ export function CartesianChart({
maxWidth?: number;
textAnchor?: "end";
}[];
- activeKey?: string;
showCategoryTicks?: boolean;
alignment?: "endpoints" | "center";
};
+ activeX?: { key: string; x: number; label: string };
children: ReactNode;
}) {
return (
@@ -303,11 +317,24 @@ export function CartesianChart({
left={plot.left}
valueFormatter={valueFormatter}
/>
+ {activeX ? (
+ <line
+ data-active-reference-line=""
+ x1={activeX.x}
+ x2={activeX.x}
+ y1={plot.top}
+ y2={plot.top + plot.height}
+ stroke="hsl(var(--foreground))"
+ strokeDasharray="3 3"
+ opacity={0.35}
+ pointerEvents="none"
+ />
+ ) : null}
{children}
{xAxis ? (
<ChartXAxis
ticks={xAxis.ticks}
- activeKey={xAxis.activeKey}
+ activeTick={activeX}
y={plot.top + plot.height}
width={width}
showCategoryTicks={xAxis.showCategoryTicks}
diff --git a/web/src/components/design-system/internal/charts/CartesianLayout.tsx b/web/src/components/design-system/internal/charts/CartesianLayout.tsx
index 0ddcf5f9a7..e23e37cab3 100644
--- a/web/src/components/design-system/internal/charts/CartesianLayout.tsx
+++ b/web/src/components/design-system/internal/charts/CartesianLayout.tsx
@@ -62,7 +62,10 @@ export function CartesianLayout({
children: (layout: {
measuredPlot: CartesianPlot;
maxYTicks: number;
- plotForTicks: (labels: string[]) => CartesianPlot;
+ plotForTicks: (
+ labels: string[],
+ options?: { showXAxisLabels: boolean },
+ ) => CartesianPlot;
}) => ReactNode;
}) {
const measuredPlot = getCartesianLayout({
@@ -74,11 +77,11 @@ export function CartesianLayout({
return children({
measuredPlot,
maxYTicks: getCartesianTickCount(measuredPlot.height),
- plotForTicks: (yTickLabels) =>
+ plotForTicks: (yTickLabels, options) =>
getCartesianLayout({
width,
height,
- showXAxisLabels,
+ showXAxisLabels: options?.showXAxisLabels ?? showXAxisLabels,
yTickLabels,
}),
});
diff --git a/web/src/components/design-system/internal/charts/ChartLegend.tsx b/web/src/components/design-system/internal/charts/ChartLegend.tsx
index c563c2ac6a..2dce287505 100644
--- a/web/src/components/design-system/internal/charts/ChartLegend.tsx
+++ b/web/src/components/design-system/internal/charts/ChartLegend.tsx
@@ -9,6 +9,7 @@ import {
} from "react";
import { DropdownMenu } from "@/src/components/design-system/DropdownMenu/DropdownMenu";
+import { CHART_TRANSITION_DURATION } from "@/src/components/design-system/charts/constants";
import { getPlainTextFromReactNode } from "@/src/utils/react-node-plain-text";
import { cn } from "@/src/utils/tailwind";
@@ -71,13 +72,19 @@ function LegendItem({ item }: { item: ChartLegendItem }) {
type="button"
onClick={item.action.onClick}
className={cn(className, "cursor-pointer hover:opacity-80")}
+ style={{ transitionDuration: CHART_TRANSITION_DURATION }}
aria-pressed={item.action.pressed}
aria-label={item.action.label}
>
{content}
</button>
) : (
- <div className={className}>{content}</div>
+ <div
+ className={className}
+ style={{ transitionDuration: CHART_TRANSITION_DURATION }}
+ >
+ {content}
+ </div>
);
}
diff --git a/web/src/components/design-system/internal/charts/ChartTooltip.tsx b/web/src/components/design-system/internal/charts/ChartTooltip.tsx
index 2c4bec16cf..854b15ac04 100644
--- a/web/src/components/design-system/internal/charts/ChartTooltip.tsx
+++ b/web/src/components/design-system/internal/charts/ChartTooltip.tsx
@@ -6,7 +6,6 @@ import {
FloatingPortal,
offset,
shift,
- useClientPoint,
useFloating,
} from "@floating-ui/react";
import { Check } from "lucide-react";
@@ -23,6 +22,7 @@ import {
} from "react";
import { useLayerContainer } from "@/src/context/LayerContext/LayerContext";
+import { CHART_TRANSITION_DURATION } from "@/src/components/design-system/charts/constants";
import { copyTextToClipboard } from "@/src/utils/clipboard";
type TooltipItem = {
@@ -36,7 +36,12 @@ type TooltipData = {
heading?: string;
hint?: string;
copyLabel?: string;
- focusPoint?: { x: number; y: number };
+ anchor:
+ | { type: "element" }
+ | { type: "point"; x: number; y: number }
+ | { type: "bar"; x: number; y: number }
+ | { type: "chart-column"; x: number }
+ | { type: "pointer" };
} & (
| {
type: "items";
@@ -56,13 +61,25 @@ type TooltipData = {
details?: Array<Omit<TooltipItem, "color">>;
emphasizedItemId?: never;
}
+ | {
+ type: "empty";
+ items?: never;
+ emphasizedItemId?: never;
+ label?: never;
+ value?: never;
+ color?: never;
+ details?: never;
+ }
);
export function ChartTooltip({
children,
+ placementStrategy = "chart-top",
}: {
+ placementStrategy?: "chart-top" | "chart-bottom" | "horizontal";
children: (controller: {
activeIndex: number | undefined;
+ hideTooltip: () => void;
getReferenceProps: (data: TooltipData) => {
onPointerEnter: (event: PointerEvent<SVGElement | HTMLElement>) => void;
onPointerMove: (event: PointerEvent<SVGElement | HTMLElement>) => void;
@@ -79,8 +96,11 @@ export function ChartTooltip({
const [activeTooltip, setActiveTooltip] = useState<
TooltipData & {
reference: SVGElement | HTMLElement;
+ chart: SVGElement | HTMLElement;
clientPoint?: { x: number; y: number };
- placement: "left" | "right";
+ pointerY?: number;
+ placement?: "left" | "right";
+ side?: "top" | "bottom";
}
>();
const [copyFeedback, setCopyFeedback] = useState<{
@@ -113,36 +133,177 @@ export function ChartTooltip({
}, [activeTooltip, children]);
const layerContainer = useLayerContainer("tooltip");
- const { context, floatingStyles, refs } = useFloating({
+ const chartAnchored =
+ placementStrategy === "chart-bottom" &&
+ activeTooltip?.anchor.type === "chart-column";
+ let fallbackPlacements: Array<"top" | "bottom" | "left" | "right"> = [
+ "bottom",
+ "left",
+ "right",
+ ];
+ if (placementStrategy === "horizontal") {
+ fallbackPlacements = ["left", "top", "bottom"];
+ } else if (chartAnchored) {
+ fallbackPlacements = [activeTooltip.side === "top" ? "bottom" : "top"];
+ }
+ let placement: "top" | "bottom" | "left" | "right" = "top";
+ if (placementStrategy === "horizontal") placement = "right";
+ if (chartAnchored) placement = activeTooltip.side ?? "bottom";
+ if (activeTooltip?.placement) placement = activeTooltip.placement;
+ const { floatingStyles, refs } = useFloating({
elements: { reference: activeTooltip?.reference },
- placement: activeTooltip?.placement ?? "right",
+ placement,
strategy: "fixed",
- middleware: [offset(12), flip(), shift({ padding: 8 })],
+ middleware: [
+ offset(({ placement, rects }) => {
+ if (!activeTooltip || activeTooltip.placement) {
+ return 12;
+ }
+ if (chartAnchored) {
+ const chartBounds = activeTooltip.chart.getBoundingClientRect();
+ const spaceAbove = chartBounds.top - rects.floating.height - 8;
+ const spaceBelow =
+ window.innerHeight - chartBounds.bottom - rects.floating.height - 8;
+ const fitsAbove = spaceAbove >= 0;
+ const fitsBelow = spaceBelow >= 0;
+ if (
+ !fitsAbove &&
+ !fitsBelow &&
+ activeTooltip.pointerY !== undefined
+ ) {
+ if (placement === "top") {
+ return chartBounds.top - activeTooltip.pointerY + 12;
+ }
+ if (placement === "bottom") {
+ return activeTooltip.pointerY - chartBounds.bottom - 2;
+ }
+ }
+ if (placement === "top") {
+ return Math.min(12, Math.max(0, spaceAbove));
+ }
+ if (placement === "bottom") {
+ return -2;
+ }
+ return 12;
+ }
+ if (placementStrategy === "chart-bottom") return 12;
+ if (activeTooltip.anchor.type === "bar") return 12;
+ const chartBounds = activeTooltip.chart.getBoundingClientRect();
+ if (placement === "top") {
+ return rects.reference.y - chartBounds.top + 12;
+ }
+ if (placement === "bottom") {
+ return (
+ chartBounds.bottom -
+ (rects.reference.y + rects.reference.height) +
+ 12
+ );
+ }
+ return 12;
+ }),
+ flip({
+ fallbackPlacements: activeTooltip?.placement
+ ? undefined
+ : fallbackPlacements,
+ fallbackStrategy: chartAnchored ? "initialPlacement" : "bestFit",
+ }),
+ shift({ padding: 8 }),
+ ],
transform: false,
whileElementsMounted: autoUpdate,
});
- useClientPoint(context, {
- enabled: activeTooltip?.clientPoint !== undefined,
- x: activeTooltip?.clientPoint?.x,
- y: activeTooltip?.clientPoint?.y,
- });
+ useLayoutEffect(() => {
+ if (!activeTooltip) return;
+ const { clientPoint, reference, chart } = activeTooltip;
+ if (chartAnchored && clientPoint) {
+ refs.setPositionReference({
+ contextElement: reference,
+ getBoundingClientRect: () => {
+ const bounds = chart.getBoundingClientRect();
+ return new DOMRect(clientPoint.x, bounds.top, 0, bounds.height);
+ },
+ });
+ return;
+ }
+ if (!clientPoint) {
+ refs.setPositionReference(reference);
+ return;
+ }
+ refs.setPositionReference({
+ contextElement: reference,
+ getBoundingClientRect: () =>
+ new DOMRect(clientPoint.x, clientPoint.y, 0, 0),
+ });
+ }, [activeTooltip, chartAnchored, refs]);
const getReferenceProps = (data: TooltipData) => {
const labelToCopy = data.copyLabel;
const showAtPointer = (event: PointerEvent<SVGElement | HTMLElement>) => {
- const { clientX, clientY, currentTarget } = event;
- const chartBounds =
+ const { currentTarget } = event;
+ let chart: SVGElement | HTMLElement = currentTarget;
+ if (
+ placementStrategy !== "chart-bottom" ||
+ data.anchor.type !== "chart-column" ||
+ !(currentTarget instanceof SVGRectElement)
+ ) {
+ chart =
+ currentTarget instanceof SVGElement
+ ? (currentTarget.ownerSVGElement ?? currentTarget)
+ : (currentTarget.parentElement ?? currentTarget);
+ }
+ const svg =
currentTarget instanceof SVGElement
- ? currentTarget.ownerSVGElement?.getBoundingClientRect()
- : currentTarget.parentElement?.getBoundingClientRect();
+ ? currentTarget.ownerSVGElement
+ : undefined;
+ const focusPoint = svg?.createSVGPoint();
+ if (
+ focusPoint &&
+ (data.anchor.type === "point" ||
+ data.anchor.type === "bar" ||
+ data.anchor.type === "chart-column")
+ ) {
+ focusPoint.x = data.anchor.x;
+ focusPoint.y = data.anchor.type === "chart-column" ? 0 : data.anchor.y;
+ }
+ const screenMatrix = svg?.getScreenCTM();
+ const transformedFocusPoint =
+ focusPoint &&
+ (data.anchor.type === "point" ||
+ data.anchor.type === "bar" ||
+ data.anchor.type === "chart-column") &&
+ screenMatrix
+ ? focusPoint.matrixTransform(screenMatrix)
+ : undefined;
+ let clientPoint = transformedFocusPoint
+ ? { x: transformedFocusPoint.x, y: transformedFocusPoint.y }
+ : undefined;
+ let placement: "left" | "right" | undefined;
+ if (data.anchor.type === "pointer") {
+ clientPoint = { x: event.clientX, y: event.clientY };
+ const chartBounds = chart.getBoundingClientRect();
+ placement =
+ event.clientX < chartBounds.left + chartBounds.width / 2
+ ? "left"
+ : "right";
+ }
+ let side: "top" | "bottom" | undefined;
+ if (
+ placementStrategy === "chart-bottom" &&
+ data.anchor.type === "chart-column"
+ ) {
+ const bounds = chart.getBoundingClientRect();
+ side =
+ bounds.top > window.innerHeight - bounds.bottom ? "top" : "bottom";
+ }
setActiveTooltip({
...data,
reference: currentTarget,
- clientPoint: { x: clientX, y: clientY },
- placement:
- chartBounds && clientX < chartBounds.left + chartBounds.width / 2
- ? "left"
- : "right",
+ chart,
+ clientPoint,
+ pointerY:
+ data.anchor.type === "chart-column" ? event.clientY : undefined,
+ placement,
+ side,
});
};
@@ -151,36 +312,58 @@ export function ChartTooltip({
onPointerMove: showAtPointer,
onPointerLeave: () => setActiveTooltip(undefined),
onFocus: (event: FocusEvent<SVGElement | HTMLElement>) => {
- const sliceBounds = event.currentTarget.getBoundingClientRect();
+ let chart: SVGElement | HTMLElement = event.currentTarget;
+ if (
+ placementStrategy !== "chart-bottom" ||
+ data.anchor.type !== "chart-column" ||
+ !(event.currentTarget instanceof SVGRectElement)
+ ) {
+ chart =
+ event.currentTarget instanceof SVGElement
+ ? (event.currentTarget.ownerSVGElement ?? event.currentTarget)
+ : (event.currentTarget.parentElement ?? event.currentTarget);
+ }
const svg =
event.currentTarget instanceof SVGElement
? event.currentTarget.ownerSVGElement
: undefined;
- const chartBounds =
- svg?.getBoundingClientRect() ??
- event.currentTarget.parentElement?.getBoundingClientRect();
const focusPoint = svg?.createSVGPoint();
- if (focusPoint && data.focusPoint) {
- focusPoint.x = data.focusPoint.x;
- focusPoint.y = data.focusPoint.y;
+ if (
+ focusPoint &&
+ (data.anchor.type === "point" ||
+ data.anchor.type === "bar" ||
+ data.anchor.type === "chart-column")
+ ) {
+ focusPoint.x = data.anchor.x;
+ focusPoint.y =
+ data.anchor.type === "chart-column" ? 0 : data.anchor.y;
}
const screenMatrix = svg?.getScreenCTM();
const transformedFocusPoint =
- focusPoint && data.focusPoint && screenMatrix
+ focusPoint &&
+ (data.anchor.type === "point" ||
+ data.anchor.type === "bar" ||
+ data.anchor.type === "chart-column") &&
+ screenMatrix
? focusPoint.matrixTransform(screenMatrix)
: undefined;
- const referenceX =
- transformedFocusPoint?.x ?? sliceBounds.left + sliceBounds.width / 2;
+ let side: "top" | "bottom" | undefined;
+ if (
+ placementStrategy === "chart-bottom" &&
+ data.anchor.type === "chart-column"
+ ) {
+ const bounds = chart.getBoundingClientRect();
+ side =
+ bounds.top > window.innerHeight - bounds.bottom ? "top" : "bottom";
+ }
setActiveTooltip({
...data,
reference: event.currentTarget,
+ chart,
clientPoint: transformedFocusPoint
? { x: transformedFocusPoint.x, y: transformedFocusPoint.y }
: undefined,
- placement:
- chartBounds && referenceX < chartBounds.left + chartBounds.width / 2
- ? "left"
- : "right",
+ side,
});
},
onBlur: () => setActiveTooltip(undefined),
@@ -244,6 +427,7 @@ export function ChartTooltip({
<>
{children({
activeIndex: activeTooltip?.index,
+ hideTooltip: () => setActiveTooltip(undefined),
getReferenceProps,
})}
{activeTooltip ? (
@@ -266,7 +450,8 @@ export function ChartTooltip({
<div role="separator" className="border-border/50 border-t" />
) : null}
<div
- className={`flex min-w-0 items-center gap-2 leading-tight transition-opacity duration-150 ${item.emphasis === "dimmed" ? "opacity-30" : "opacity-100"}`}
+ className={`flex min-w-0 items-center gap-2 leading-tight transition-opacity ${item.emphasis === "dimmed" ? "opacity-30" : "opacity-100"}`}
+ style={{ transitionDuration: CHART_TRANSITION_DURATION }}
>
{item.kind !== "detail" && item.color ? (
<svg
@@ -296,6 +481,9 @@ export function ChartTooltip({
</div>
</Fragment>
))}
+ {activeTooltip.type === "empty" ? (
+ <div className="text-muted-foreground">No data available</div>
+ ) : null}
{activeTooltip.hint ? (
<div
className="border-border/50 text-muted-foreground/70 grid border-t pt-1.5 text-[10px]"
diff --git a/web/src/components/design-system/internal/charts/SeriesChartCore.tsx b/web/src/components/design-system/internal/charts/SeriesChartCore.tsx
index d1061d4ee2..3d80e29883 100644
--- a/web/src/components/design-system/internal/charts/SeriesChartCore.tsx
+++ b/web/src/components/design-system/internal/charts/SeriesChartCore.tsx
@@ -5,6 +5,7 @@ import { scaleLinear, scalePoint, scaleUtc } from "d3-scale";
import { area, line } from "d3-shape";
import { ChartContainer } from "@/src/components/design-system/charts/ChartContainer";
+import { CHART_TRANSITION_DURATION } from "@/src/components/design-system/charts/constants";
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";
@@ -66,8 +67,6 @@ type LineChartProps = CommonLineChartProps &
data: TimeLineChartDatum[];
xAxis: {
type: "time";
- tickFormatter?: (value: Date) => string;
- tooltipFormatter?: (value: Date) => string;
};
}
| {
@@ -86,17 +85,10 @@ type NormalizedDatum = LineChartValues & {
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"],
@@ -524,14 +516,61 @@ function LineChartContent(
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 timeDataDates = data.flatMap((datum) =>
+ datum.x instanceof Date ? [datum.x] : [],
+ );
+ const timeTickDates = timeDataDates.filter(
+ (date, index) =>
+ index === 0 || date.getTime() !== timeDataDates[index - 1]!.getTime(),
+ );
+ const sortedTimes = timeTickDates.map((date) => date.getTime());
+ const minTickGap = sortedTimes.reduce((gap, time, index) => {
+ const distance = time - (sortedTimes[index - 1] ?? time);
+ return distance > 0 ? Math.min(gap, distance) : gap;
+ }, Infinity);
+ // UTC-midnight date buckets must keep their calendar date; intraday instants use local time.
+ const showTooltipTime = timeDataDates.some(
+ (date, index) =>
+ date.getUTCHours() !== 0 ||
+ date.getUTCMinutes() !== 0 ||
+ date.getUTCSeconds() !== 0 ||
+ (index > 0 &&
+ date.getTime() - timeDataDates[index - 1]!.getTime() <
+ 24 * 60 * 60 * 1000),
+ );
+ const crossesYear =
+ (showTooltipTime
+ ? timeTickDates[0]?.getFullYear()
+ : timeTickDates[0]?.getUTCFullYear()) !==
+ (showTooltipTime
+ ? timeTickDates[timeTickDates.length - 1]?.getFullYear()
+ : timeTickDates[timeTickDates.length - 1]?.getUTCFullYear());
+ const distinctTickMonths = new Set(
+ timeTickDates.map((date) =>
+ showTooltipTime
+ ? `${date.getFullYear()}-${date.getMonth()}`
+ : `${date.getUTCFullYear()}-${date.getUTCMonth()}`,
+ ),
+ ).size;
+ const formatTimeTick = (value: Date) =>
+ value.toLocaleString("en-US", {
+ ...(!showTooltipTime ? { timeZone: "UTC" } : {}),
+ ...(Number.isFinite(minTickGap) &&
+ minTickGap >= 28 * 24 * 60 * 60 * 1000 &&
+ distinctTickMonths === timeTickDates.length
+ ? { month: "short" as const, year: "numeric" as const }
+ : {
+ month: "short" as const,
+ day: "numeric" as const,
+ ...(crossesYear ? { year: "numeric" as const } : {}),
+ ...(minTickGap < 24 * 60 * 60 * 1000
+ ? { hour: "numeric" as const, minute: "2-digit" as const }
+ : {}),
+ ...(minTickGap < 60 * 60 * 1000
+ ? { second: "2-digit" as const }
+ : {}),
+ }),
+ });
const categoryTickStep = Math.max(
1,
Math.ceil((80 * Math.max(1, data.length - 1)) / Math.max(1, plotWidth)),
@@ -547,30 +586,11 @@ function LineChartContent(
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),
- }))
+ ? timeTickDates.map((value) => ({
+ key: String(value.getTime()),
+ x: timeScale(value),
+ label: formatTimeTick(value),
+ }))
: categoryTickIndices.map((index, tickIndex) => {
const datum = data[index]!;
const previous = categoryTickIndices[tickIndex - 1];
@@ -596,9 +616,7 @@ function LineChartContent(
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)
- );
+ return formatTimeTick(datum.x);
}
if (xAxis.type === "category" && typeof datum.x === "string") {
return xAxis.tickFormatter?.(datum.x) ?? datum.x;
@@ -612,15 +630,19 @@ function LineChartContent(
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 showTooltipSeconds = timeDataDates.some(
+ (date) => date.getUTCSeconds() !== 0,
+ );
const formatXTooltip = (datum: NormalizedDatum) => {
if (xAxis.type === "time" && datum.x instanceof Date) {
- return xAxis.tooltipFormatter?.(datum.x) ?? datum.x.toLocaleString();
+ return datum.x.toLocaleString("en-US", {
+ ...(!showTooltipTime ? { timeZone: "UTC" } : {}),
+ month: "short",
+ day: "numeric",
+ year: "numeric",
+ ...(showTooltipTime ? { hour: "numeric", minute: "2-digit" } : {}),
+ ...(showTooltipSeconds ? { second: "2-digit" } : {}),
+ });
}
if (xAxis.type === "category" && typeof datum.x === "string") {
return xAxis.tooltipFormatter?.(datum.x) ?? datum.x;
@@ -691,7 +713,7 @@ function LineChartContent(
}
return (
- <ChartTooltip>
+ <ChartTooltip placementStrategy="chart-bottom">
{({ activeIndex, getReferenceProps }) => (
<CartesianChart
width={width}
@@ -710,11 +732,11 @@ function LineChartContent(
? yScale(0)
: undefined
}
+ activeX={activeXAxisTick}
xAxis={
showXAxisLabels
? {
- ticks: visibleXTicks,
- activeKey,
+ ticks: xTicks,
showCategoryTicks: xAxis.type === "category",
}
: undefined
@@ -802,7 +824,8 @@ function LineChartContent(
return (
<g
key={item.id}
- className="transition-opacity duration-150"
+ className="transition-opacity"
+ style={{ transitionDuration: CHART_TRANSITION_DURATION }}
opacity={areaVariant || !dimmed ? 1 : 0.2}
>
{areaVariant ? (
@@ -874,19 +897,6 @@ function LineChartContent(
);
})}
- {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 =
@@ -904,7 +914,6 @@ function LineChartContent(
})
.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,
@@ -912,19 +921,39 @@ function LineChartContent(
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,
- });
+ const referenceProps = getReferenceProps(
+ first
+ ? {
+ type: "items",
+ index,
+ heading,
+ anchor:
+ values.length === 1
+ ? {
+ type: "point" as const,
+ x: currentX,
+ y: yScale(
+ stackedValues[index]?.get(first.item.id)?.top ??
+ first.value,
+ ),
+ }
+ : { type: "chart-column" as const, x: currentX },
+ emphasizedItemId:
+ series.find((item) => item.emphasis === "emphasized")
+ ?.id ??
+ (!hasConfiguredEmphasis ? hoveredSeriesId : undefined),
+ items: tooltipItems,
+ }
+ : {
+ type: "empty",
+ index,
+ heading,
+ anchor: {
+ type: "chart-column",
+ x: currentX,
+ },
+ },
+ );
return (
<g key={datum.key}>
<rect
@@ -962,7 +991,7 @@ function LineChartContent(
type: "items",
index,
heading,
- focusPoint: { x: currentX, y: pointY },
+ anchor: { type: "point", x: currentX, y: pointY },
emphasizedItemId: item.id,
items: tooltipItems,
});
diff --git a/web/src/features/score-analytics/components/cards/TimelineChartCard.tsx b/web/src/features/score-analytics/components/cards/TimelineChartCard.tsx
index 8eeb55d9f6..2ff4691b6a 100644
--- a/web/src/features/score-analytics/components/cards/TimelineChartCard.tsx
+++ b/web/src/features/score-analytics/components/cards/TimelineChartCard.tsx
@@ -236,13 +236,7 @@ export function TimelineChartCard() {
const { metadata } = data;
const { mode, dataType } = metadata;
- const { score1, score2, interval, fromTimestamp, toTimestamp } = params;
-
- // Construct TimeRange from params timestamps
- const timeRange = {
- from: fromTimestamp,
- to: toTimestamp,
- };
+ const { score1, score2 } = params;
const hasData = chartData.length > 0;
const showTabs = mode === "two";
@@ -319,8 +313,6 @@ export function TimelineChartCard() {
? `${score2.name} (${score2.source})`
: undefined
}
- interval={interval}
- timeRange={timeRange}
colors={chartColors}
/>
) : (
diff --git a/web/src/features/score-analytics/components/charts/ScoreTimeSeriesCategoricalChart.tsx b/web/src/features/score-analytics/components/charts/ScoreTimeSeriesCategoricalChart.tsx
index 7994569dc9..26c45a98bd 100644
--- a/web/src/features/score-analytics/components/charts/ScoreTimeSeriesCategoricalChart.tsx
+++ b/web/src/features/score-analytics/components/charts/ScoreTimeSeriesCategoricalChart.tsx
@@ -1,20 +1,10 @@
import { useMemo } from "react";
import { LineChart } from "@/src/components/design-system/charts/LineChart/LineChart";
-import {
- type IntervalConfig,
- type TimeRange,
-} from "@/src/utils/date-range-utils";
-import {
- formatChartTimestamp,
- formatChartTooltipTimestamp,
-} from "../../lib/chart-formatters";
export interface CategoricalTimeSeriesChartProps {
data: Array<{ timestamp: Date; category: string; count: number }>;
score1Name: string;
score2Name?: string;
- interval: IntervalConfig;
- timeRange: TimeRange;
colors: Record<string, string>;
}
@@ -22,8 +12,6 @@ export function ScoreTimeSeriesCategoricalChart({
data,
score1Name: _score1Name,
score2Name: _score2Name,
- interval,
- timeRange,
colors,
}: CategoricalTimeSeriesChartProps) {
const { chartData, series } = useMemo(() => {
@@ -80,10 +68,6 @@ export function ScoreTimeSeriesCategoricalChart({
series={series}
xAxis={{
type: "time",
- tickFormatter: (value) =>
- formatChartTimestamp(value, interval, timeRange),
- tooltipFormatter: (value) =>
- formatChartTooltipTimestamp(value, interval, timeRange),
}}
valueFormatter={(value) => value.toLocaleString()}
showDataPointDots
diff --git a/web/src/features/score-analytics/components/charts/ScoreTimeSeriesChart.tsx b/web/src/features/score-analytics/components/charts/ScoreTimeSeriesChart.tsx
index 299984003f..feea863aaf 100644
--- a/web/src/features/score-analytics/components/charts/ScoreTimeSeriesChart.tsx
+++ b/web/src/features/score-analytics/components/charts/ScoreTimeSeriesChart.tsx
@@ -1,7 +1,3 @@
-import {
- type IntervalConfig,
- type TimeRange,
-} from "@/src/utils/date-range-utils";
import { ScoreTimeSeriesNumericChart } from "./ScoreTimeSeriesNumericChart";
import { ScoreTimeSeriesBooleanChart } from "./ScoreTimeSeriesBooleanChart";
import { ScoreTimeSeriesCategoricalChart } from "./ScoreTimeSeriesCategoricalChart";
@@ -26,8 +22,6 @@ export interface ScoreTimeSeriesChartProps {
dataType: "NUMERIC" | "CATEGORICAL" | "BOOLEAN";
score1Name: string;
score2Name?: string;
- interval: IntervalConfig;
- timeRange: TimeRange;
colors: Record<string, string> | { score1: string; score2?: string };
}
@@ -43,8 +37,6 @@ export function ScoreTimeSeriesChart({
dataType,
score1Name,
score2Name,
- interval,
- timeRange,
colors,
}: ScoreTimeSeriesChartProps) {
switch (dataType) {
@@ -54,8 +46,6 @@ export function ScoreTimeSeriesChart({
data={data as NumericTimeSeriesData}
score1Name={score1Name}
score2Name={score2Name}
- interval={interval}
- timeRange={timeRange}
colors={colors as { score1: string; score2?: string }}
/>
);
@@ -65,8 +55,6 @@ export function ScoreTimeSeriesChart({
data={data as CategoricalTimeSeriesData}
score1Name={score1Name}
score2Name={score2Name}
- interval={interval}
- timeRange={timeRange}
colors={colors as Record<string, string>}
/>
);
@@ -76,8 +64,6 @@ export function ScoreTimeSeriesChart({
data={data as CategoricalTimeSeriesData}
score1Name={score1Name}
score2Name={score2Name}
- interval={interval}
- timeRange={timeRange}
colors={colors as Record<string, string>}
/>
);
diff --git a/web/src/features/score-analytics/components/charts/ScoreTimeSeriesNumericChart.tsx b/web/src/features/score-analytics/components/charts/ScoreTimeSeriesNumericChart.tsx
index 3e2378a47f..7a106c90e2 100644
--- a/web/src/features/score-analytics/components/charts/ScoreTimeSeriesNumericChart.tsx
+++ b/web/src/features/score-analytics/components/charts/ScoreTimeSeriesNumericChart.tsx
@@ -1,14 +1,6 @@
import { useMemo } from "react";
import { LineChart } from "@/src/components/design-system/charts/LineChart/LineChart";
-import {
- type IntervalConfig,
- type TimeRange,
-} from "@/src/utils/date-range-utils";
import { compactNumberFormatter } from "@/src/utils/numbers";
-import {
- formatChartTimestamp,
- formatChartTooltipTimestamp,
-} from "../../lib/chart-formatters";
export interface NumericTimeSeriesChartProps {
data: Array<{
@@ -19,8 +11,6 @@ export interface NumericTimeSeriesChartProps {
}>;
score1Name: string;
score2Name?: string;
- interval: IntervalConfig;
- timeRange: TimeRange;
colors: { score1: string; score2?: string };
}
@@ -28,8 +18,6 @@ export function ScoreTimeSeriesNumericChart({
data,
score1Name,
score2Name,
- interval,
- timeRange,
colors,
}: NumericTimeSeriesChartProps) {
const chartData = useMemo(
@@ -86,10 +74,6 @@ export function ScoreTimeSeriesNumericChart({
series={series}
xAxis={{
type: "time",
- tickFormatter: (value) =>
- formatChartTimestamp(value, interval, timeRange),
- tooltipFormatter: (value) =>
- formatChartTooltipTimestamp(value, interval, timeRange),
}}
valueFormatter={compactNumberFormatter}
showDataPointDots
diff --git a/web/src/features/score-analytics/lib/chart-formatters.ts b/web/src/features/score-analytics/lib/chart-formatters.ts
deleted file mode 100644
index 624535df40..0000000000
--- a/web/src/features/score-analytics/lib/chart-formatters.ts
+++ /dev/null
@@ -1,40 +0,0 @@
-import { format } from "date-fns";
-import {
- getChartAxisFormat,
- getChartTooltipFormat,
- type IntervalConfig,
- type TimeRange,
-} from "@/src/utils/date-range-utils";
-
-/**
- * Format a timestamp for chart X-axis labels using dynamic formatting
- * based on the interval unit and time range duration.
- *
- * Examples:
- * - "10:30:45" for second intervals
- * - "10:30" for minute/hour intervals (< 1 day)
- * - "Jan 15, 10:30" for hour intervals (> 1 day)
- * - "Jan 15" for day intervals
- * - "Jan 2025" for month intervals
- *
- * @param date - The timestamp to format
- * @param interval - The interval configuration (unit and count)
- * @param timeRange - The time range (relative or absolute)
- * @returns Formatted timestamp string for axis label
- */
-export function formatChartTimestamp(
- date: Date,
- interval: IntervalConfig,
- timeRange: TimeRange,
-): string {
- const formatString = getChartAxisFormat(interval, timeRange);
- return format(date, formatString);
-}
-
-export function formatChartTooltipTimestamp(
- date: Date,
- interval: IntervalConfig,
- timeRange: TimeRange,
-) {
- return format(date, getChartTooltipFormat(interval, timeRange));
-}
diff --git a/web/src/features/widgets/chart-library/AreaChartTimeSeries.tsx b/web/src/features/widgets/chart-library/AreaChartTimeSeries.tsx
index 6d6a6695a3..a62e92673f 100644
--- a/web/src/features/widgets/chart-library/AreaChartTimeSeries.tsx
+++ b/web/src/features/widgets/chart-library/AreaChartTimeSeries.tsx
@@ -40,7 +40,7 @@ export function AreaChartTimeSeries({
missingValue = "gap",
connectNulls = false,
hideXAxisLabels = false,
-}: Omit<ChartProps, "subtleFill">) {
+}: ChartProps) {
const allDimensions = useMemo(() => getUniqueDimensions(data), [data]);
const groupedData = useMemo(
() =>
@@ -152,8 +152,6 @@ export function AreaChartTimeSeries({
legend={chartLegend}
xAxis={{
type: "time",
- tickFormatter: (value) => timeAxis.formatTick(value.getTime()),
- tooltipFormatter: (value) => timeAxis.formatTooltip(value.getTime()),
}}
/>
);
diff --git a/web/src/features/widgets/chart-library/Chart.tsx b/web/src/features/widgets/chart-library/Chart.tsx
index 016ed25b43..756958f423 100644
--- a/web/src/features/widgets/chart-library/Chart.tsx
+++ b/web/src/features/widgets/chart-library/Chart.tsx
@@ -84,7 +84,6 @@ const ChartComponent = ({
defaultSort?: OrderByState;
show_value_labels?: boolean;
show_data_point_dots?: boolean;
- subtle_fill?: boolean;
};
config?: ChartProps["config"];
sortState?: OrderByState | null;
@@ -241,7 +240,6 @@ const ChartComponent = ({
data={renderedData.slice(0, rowLimit)}
config={resolvedConfig}
metricFormatter={metricFormatter}
- subtleFill={chartConfig?.subtle_fill}
hideXAxisLabels={hideXAxisLabels}
colorBarsByCategory={colorBarsByCategory}
legendPosition={legendPosition}
@@ -261,7 +259,6 @@ const ChartComponent = ({
data={renderedData}
config={resolvedConfig}
metricFormatter={metricFormatter}
- subtleFill={chartConfig?.subtle_fill}
/>
);
case "NUMBER": {
diff --git a/web/src/features/widgets/chart-library/HistogramChart.tsx b/web/src/features/widgets/chart-library/HistogramChart.tsx
index 4c89cd0117..e86bfad704 100644
--- a/web/src/features/widgets/chart-library/HistogramChart.tsx
+++ b/web/src/features/widgets/chart-library/HistogramChart.tsx
@@ -17,12 +17,10 @@ const HistogramChart = ({
color: "hsl(var(--chart-1))",
},
},
- subtleFill = false,
metricFormatter = (value, options) => formatMetric(value, options),
}: {
data: DataPoint[];
config?: ChartProps["config"];
- subtleFill?: boolean;
metricFormatter?: MetricFormatterFunction;
}) => {
const formatBinEdge = (value: number) =>
@@ -61,7 +59,6 @@ const HistogramChart = ({
<DesignSystemHistogramChart
data={histogramData}
color={config.count?.color ?? "hsl(var(--chart-1))"}
- variant={subtleFill ? "subtle" : "default"}
valueFormatter={(value) =>
toFullMetricString(formatMetric(value, { style: "compact" }))
}
diff --git a/web/src/features/widgets/chart-library/LineChartTimeSeries.tsx b/web/src/features/widgets/chart-library/LineChartTimeSeries.tsx
index 961f4eeec2..8cb85e2094 100644
--- a/web/src/features/widgets/chart-library/LineChartTimeSeries.tsx
+++ b/web/src/features/widgets/chart-library/LineChartTimeSeries.tsx
@@ -27,6 +27,15 @@ import {
} from "@/src/features/widgets/chart-library/TimeSeriesLegend";
import { getPlainTextFromReactNode } from "@/src/utils/react-node-plain-text";
+const defaultConfig: NonNullable<ChartProps["config"]> = {
+ metric: {
+ theme: {
+ light: "hsl(var(--chart-1))",
+ dark: "hsl(var(--chart-1))",
+ },
+ },
+};
+
function toDesignSystemThreshold(
threshold: ChartThreshold,
): LineChartThreshold {
@@ -62,15 +71,8 @@ function toDesignSystemThreshold(
*/
export function LineChartTimeSeries({
data,
- config = {
- metric: {
- theme: {
- light: "hsl(var(--chart-1))",
- dark: "hsl(var(--chart-1))",
- },
- },
- },
- metricFormatter = (value, options) => formatMetric(value, options),
+ config = defaultConfig,
+ metricFormatter = formatMetric,
legendPosition = "auto",
legendSummary = "none",
legendInteraction = "highlight",
@@ -117,8 +119,11 @@ export function LineChartTimeSeries({
});
return dates.length ? prepareTimeAxis(dates) : timeAxis;
}, [groupedData, timeAxis]);
- const formatValue = (value: number) =>
- toFullMetricString(metricFormatter(value, { style: "compact" }));
+ const formatValue = useMemo(
+ () => (value: number) =>
+ toFullMetricString(metricFormatter(value, { style: "compact" })),
+ [metricFormatter],
+ );
const chartData = useMemo(
() =>
groupedData.map((datum) => ({
@@ -132,13 +137,29 @@ export function LineChartTimeSeries({
})),
[dimensions, groupedData],
);
- const chartSeries = dimensions.map((dimension, index) => ({
- id: dimension,
- label:
- getPlainTextFromReactNode(config?.[dimension]?.label ?? dimension) ??
- dimension,
- color: seriesColor(index),
- }));
+ const chartSeries = useMemo(
+ () =>
+ dimensions.map((dimension, index) => ({
+ id: dimension,
+ label:
+ getPlainTextFromReactNode(config?.[dimension]?.label ?? dimension) ??
+ dimension,
+ color: seriesColor(index),
+ })),
+ [dimensions, config],
+ );
+ const timeChartData = useMemo(
+ () =>
+ chartData.flatMap((datum) => {
+ const date = parseChartTimestamp(datum.x);
+ return date ? [{ ...datum, x: date }] : [];
+ }),
+ [chartData],
+ );
+ const chartThresholds = useMemo(
+ () => thresholds?.map(toDesignSystemThreshold),
+ [thresholds],
+ );
let chartLegend: LineChartLegend = { visibility: "hidden" };
if (legendPosition !== "none" && legendInteraction === "toggle") {
chartLegend = {
@@ -162,7 +183,7 @@ export function LineChartTimeSeries({
valueFormatter={formatValue}
showDataPointDots={showDataPointDots}
connectNulls={connectNulls}
- thresholds={thresholds?.map(toDesignSystemThreshold)}
+ thresholds={chartThresholds}
sync={sync}
legend={chartLegend}
xAxis={{
@@ -184,21 +205,16 @@ export function LineChartTimeSeries({
/>
) : (
<DesignSystemLineChart
- data={chartData.flatMap((datum) => {
- const date = parseChartTimestamp(datum.x);
- return date ? [{ ...datum, x: date }] : [];
- })}
+ data={timeChartData}
series={chartSeries}
valueFormatter={formatValue}
showDataPointDots={showDataPointDots}
connectNulls={connectNulls}
- thresholds={thresholds?.map(toDesignSystemThreshold)}
+ thresholds={chartThresholds}
sync={sync}
legend={chartLegend}
xAxis={{
type: "time",
- tickFormatter: (value) => timeAxis.formatTick(value.getTime()),
- tooltipFormatter: (value) => timeAxis.formatTooltip(value.getTime()),
}}
/>
);
diff --git a/web/src/features/widgets/chart-library/VerticalBarChart.tsx b/web/src/features/widgets/chart-library/VerticalBarChart.tsx
index 13993de181..ed5b454e9e 100644
--- a/web/src/features/widgets/chart-library/VerticalBarChart.tsx
+++ b/web/src/features/widgets/chart-library/VerticalBarChart.tsx
@@ -12,7 +12,6 @@ export function VerticalBarChart({
data,
config,
metricFormatter = formatMetric,
- subtleFill = false,
hideXAxisLabels = false,
colorBarsByCategory = false,
legendPosition,
@@ -39,7 +38,6 @@ export function VerticalBarChart({
data={chartData}
color={config?.metric?.color ?? "hsl(var(--chart-1))"}
valueFormatter={formatValue}
- variant={subtleFill ? "subtle" : "default"}
hideXAxisLabels={hideXAxisLabels}
zeroBaseline={zeroBaseline}
legend={
diff --git a/web/src/features/widgets/chart-library/VerticalBarChartTimeSeries.tsx b/web/src/features/widgets/chart-library/VerticalBarChartTimeSeries.tsx
index 06f2427c88..c5a2ff5d93 100644
--- a/web/src/features/widgets/chart-library/VerticalBarChartTimeSeries.tsx
+++ b/web/src/features/widgets/chart-library/VerticalBarChartTimeSeries.tsx
@@ -30,7 +30,7 @@ export function VerticalBarChartTimeSeries({
maxVisibleSeries,
sync,
hideXAxisLabels = false,
-}: Omit<ChartProps, "subtleFill">) {
+}: ChartProps) {
const groupedData = useMemo(() => groupDataByTimeDimension(data), [data]);
const dimensions = useMemo(() => getUniqueDimensions(data), [data]);
const visibleSeries = useMemo(
@@ -48,24 +48,35 @@ export function VerticalBarChartTimeSeries({
),
[groupedData, hideXAxisLabels],
);
- const formatValue = (value: number) =>
- toFullMetricString(metricFormatter(value, { style: "compact" }));
- const chartData = groupedData.map((datum) => ({
- key: String(datum.time_dimension ?? ""),
- values: Object.fromEntries(
- visibleSeries.visible.map((dimension) => [
- dimension,
- typeof datum[dimension] === "number" ? datum[dimension] : null,
- ]),
- ),
- }));
- const chartSeries = visibleSeries.visible.map((dimension, index) => ({
- id: dimension,
- label:
- getPlainTextFromReactNode(config?.[dimension]?.label ?? dimension) ??
- dimension,
- color: seriesColor(index),
- }));
+ const formatValue = useMemo(
+ () => (value: number) =>
+ toFullMetricString(metricFormatter(value, { style: "compact" })),
+ [metricFormatter],
+ );
+ const chartData = useMemo(
+ () =>
+ groupedData.map((datum) => ({
+ key: String(datum.time_dimension ?? ""),
+ values: Object.fromEntries(
+ visibleSeries.visible.map((dimension) => [
+ dimension,
+ typeof datum[dimension] === "number" ? datum[dimension] : null,
+ ]),
+ ),
+ })),
+ [groupedData, visibleSeries],
+ );
+ const chartSeries = useMemo(
+ () =>
+ visibleSeries.visible.map((dimension, index) => ({
+ id: dimension,
+ label:
+ getPlainTextFromReactNode(config?.[dimension]?.label ?? dimension) ??
+ dimension,
+ color: seriesColor(index),
+ })),
+ [visibleSeries, config],
+ );
let chartLegend: LineChartLegend = { visibility: "hidden" };
if (legendPosition !== "none" && legendInteraction === "toggle") {
chartLegend = {
diff --git a/web/src/features/widgets/chart-library/chart-props.ts b/web/src/features/widgets/chart-library/chart-props.ts
index 05bebd6891..4098c24703 100644
--- a/web/src/features/widgets/chart-library/chart-props.ts
+++ b/web/src/features/widgets/chart-library/chart-props.ts
@@ -142,7 +142,6 @@ export interface ChartProps {
};
showValueLabels?: boolean;
showDataPointDots?: boolean;
- subtleFill?: boolean;
thresholds?: ChartThreshold[];
/** See {@link MissingBucketValue}. Defaults to `"gap"`. */
missingValue?: MissingBucketValue;
diff --git a/web/src/styles/globals.css b/web/src/styles/globals.css
index c433576b39..2268a5fc36 100644
--- a/web/src/styles/globals.css
+++ b/web/src/styles/globals.css
@@ -448,14 +448,14 @@
--find-match-selected-background: 60 100% 50%;
--find-match-selected-foreground: 0 0% 0%;
- --chart-1: 239 84% 58%;
- --chart-2: 188 94% 43%;
- --chart-3: 240 4% 46%;
- --chart-4: 271 91% 65%;
- --chart-5: 48 96% 47%;
- --chart-6: 0 84% 60%;
- --chart-7: 84 81% 44%;
- --chart-8: 330 81% 60%;
+ --chart-1: 239 84% 66%;
+ --chart-2: 188 94% 30%;
+ --chart-3: 240 4% 48%;
+ --chart-4: 271 91% 61%;
+ --chart-5: 48 96% 29%;
+ --chart-6: 0 84% 50%;
+ --chart-7: 84 81% 28%;
+ --chart-8: 330 81% 49%;
--chart-grid: var(--muted-gray);
--color-1: oklch(66.2% 0.225 25.9);
--color-2: oklch(60.4% 0.26 302);
@@ -642,14 +642,14 @@
--find-match-selected-background: 60 100% 50%;
--find-match-selected-foreground: 0 0% 0%;
- --chart-1: 239 84% 58%;
- --chart-2: 188 94% 43%;
- --chart-3: 240 4% 46%;
- --chart-4: 271 91% 65%;
- --chart-5: 48 96% 47%;
- --chart-6: 0 84% 60%;
- --chart-7: 84 81% 44%;
- --chart-8: 330 81% 60%;
+ --chart-1: 239 96% 69%;
+ --chart-2: 188 94% 30%;
+ --chart-3: 240 4% 48%;
+ --chart-4: 271 91% 61%;
+ --chart-5: 48 96% 29%;
+ --chart-6: 0 84% 50%;
+ --chart-7: 84 81% 28%;
+ --chart-8: 330 81% 49%;
--chart-grid: var(--muted-gray);
--color-1: oklch(66.2% 0.225 25.9);
--color-2: oklch(60.4% 0.26 302);
diff --git a/web/src/utils/date-range-utils.ts b/web/src/utils/date-range-utils.ts
index c50d56b454..0394ecfcdf 100644
--- a/web/src/utils/date-range-utils.ts
+++ b/web/src/utils/date-range-utils.ts
@@ -449,87 +449,4 @@ export function resolveTimeRange<T extends string>(
return rangeFromString(source, allowedRanges, fallback);
}
-/**
- * =======================
- * Chart Formatting
- * =======================
- */
-
-/**
- * Get the appropriate date-fns format string for chart X-axis labels
- * based on the interval unit and time range duration.
- *
- * This function returns format strings optimized for axis labels (concise).
- *
- * @param interval - The interval configuration (unit and count)
- * @param timeRange - The time range (relative or absolute)
- * @returns date-fns format string for axis labels
- */
-export function getChartAxisFormat(
- interval: IntervalConfig,
- timeRange: TimeRange,
-): string {
- const { unit } = interval;
-
- // Calculate duration for context-aware formatting
- const absoluteRange = toAbsoluteTimeRange(timeRange);
- let durationHours: number | null = null;
-
- if (absoluteRange) {
- const durationMs =
- absoluteRange.to.getTime() - absoluteRange.from.getTime();
- durationHours = durationMs / (1000 * 60 * 60);
- }
-
- switch (unit) {
- case "second":
- // < 5 minutes: show time with seconds only
- return "HH:mm:ss";
-
- case "minute":
- // 5 min - 3 hours: show time only (no date)
- return "HH:mm";
-
- case "hour":
- // 3 hours - 7 days
- if (durationHours !== null && durationHours <= 24) {
- // Within 1 day: time only
- return "HH:mm";
- }
- // Multiple days: date + time
- return "MMM dd, HH:mm";
-
- case "day":
- // 7 days - 90 days: date without time
- return "MMM dd";
-
- case "month":
- // > 90 days: month and year
- return "MMM yyyy";
-
- case "year":
- // Multi-year ranges: year only
- return "yyyy";
-
- default:
- // Fallback to day format
- return "MMM dd";
- }
-}
-
-export function getChartTooltipFormat(
- interval: IntervalConfig,
- timeRange: TimeRange,
-) {
- const formats = {
- second: "MMM dd, HH:mm:ss",
- minute: "MMM dd, HH:mm",
- hour: "MMM dd, HH:mm",
- day: "MMM dd, yyyy",
- month: "MMM yyyy",
- year: "yyyy",
- } satisfies Record<IntervalConfig["unit"], string>;
- return formats[interval.unit] ?? getChartAxisFormat(interval, timeRange);
-}
-
// Re-export fillTimeSeriesGaps from its own module