Skip to content

An open source design system that's fully customizable and agent ready

TypeScript

test: route charts/vega into the ui vitest project and cover the untested viz packages and hooks (#4295) (#4377)

AK1581b0900091
diff --git a/packages/charts/src/Chart.test.tsx b/packages/charts/src/Chart.test.tsx
index 9644955756..b95446c102 100644
--- a/packages/charts/src/Chart.test.tsx
+++ b/packages/charts/src/Chart.test.tsx
@@ -2,15 +2,18 @@
/**
* @file Chart.test.tsx
- * @input Uses vitest, @testing-library/react, Chart root + bar mark
- * @output Unit tests for Chart accessibility (WCAG 1.1.1)
+ * @input Uses vitest, @testing-library/react, Chart root + bar/line marks
+ * @output Unit tests for Chart accessibility (WCAG 1.1.1) and the chart
+ * root's functional contract — measurement gate, per-series render
+ * delegation, event layer geometry, palette assignment, and the
+ * declarative legend/tooltip slots (issue #4295 viz coverage)
* @position Testing; validates Chart.tsx accessible name + data-table fallback
*/
import {describe, it, expect, beforeEach, afterEach, vi} from 'vitest';
-import {render, screen, act} from '@testing-library/react';
+import {render, screen, act, within} from '@testing-library/react';
import {Chart} from './Chart';
-import {bar} from './marks';
+import {bar, line} from './marks';
const data = [
{month: 'Jan', revenue: 100, profit: 20},
@@ -80,6 +83,25 @@ describe('Chart accessible name', () => {
screen.getByRole('img', {name: 'Quarterly revenue'}),
).toBeInTheDocument();
});
+
+ it('describes the svg from the subtitle and mirrors the title in an svg <title>', () => {
+ const {container} = render(
+ <Chart
+ data={data}
+ xKey="month"
+ series={[bar('revenue')]}
+ title="Quarterly revenue"
+ subtitle="Revenue per month"
+ />,
+ );
+ reportWidth(600);
+
+ const svg = container.querySelector('svg')!;
+ expect(svg.querySelector('title')!.textContent).toBe('Quarterly revenue');
+ const desc = svg.querySelector('desc')!;
+ expect(desc.textContent).toBe('Revenue per month');
+ expect(svg.getAttribute('aria-describedby')).toBe(desc.id);
+ });
});
describe('Chart data table fallback', () => {
@@ -127,3 +149,113 @@ describe('Chart data table fallback', () => {
expect(screen.queryByRole('table')).not.toBeInTheDocument();
});
});
+
+describe('Chart measurement gate', () => {
+ it('renders only an empty height-reserving placeholder until the container reports a width', () => {
+ const {container} = render(
+ <Chart data={data} xKey="month" series={[bar('revenue')]} height={300} />,
+ );
+
+ expect(container.querySelector('svg')).toBeNull();
+ const placeholder = container.firstElementChild as HTMLElement;
+ expect(placeholder.tagName).toBe('DIV');
+ expect(placeholder.style.height).toBe('300px');
+ expect(placeholder.childElementCount).toBe(0);
+ });
+});
+
+describe('Chart render delegation', () => {
+ it('renders one clipped group per series', () => {
+ const {container} = render(
+ <Chart
+ data={data}
+ xKey="month"
+ series={[bar('revenue'), line('profit')]}
+ />,
+ );
+ reportWidth(600);
+
+ const plot = container.querySelector('g[clip-path]');
+ expect(plot).not.toBeNull();
+ const seriesGroups = Array.from(plot!.children).filter(
+ el => el.tagName === 'g',
+ );
+ expect(seriesGroups).toHaveLength(2);
+ // Each series' render() output lands in its own group: bar paths in the
+ // first, the line's stroke path in the second.
+ expect(seriesGroups[0].querySelectorAll('path').length).toBeGreaterThan(0);
+ expect(seriesGroups[1].querySelectorAll('path').length).toBeGreaterThan(0);
+ });
+
+ it('sizes the transparent event-capture rect to the plot area inside the default margins', () => {
+ const {container} = render(
+ <Chart data={data} xKey="month" series={[bar('revenue')]} height={300} />,
+ );
+ reportWidth(600);
+
+ // 600 - 48 (left) - 24 (right) = 528; 300 - 24 (top) - 32 (bottom) = 244.
+ const eventRect = container.querySelector(
+ 'svg > g > rect[fill="transparent"]',
+ );
+ expect(eventRect).not.toBeNull();
+ expect(eventRect).toHaveAttribute('width', '528');
+ expect(eventRect).toHaveAttribute('height', '244');
+ });
+
+ it('assigns distinct palette colors to series that do not declare one', () => {
+ const {container} = render(
+ <Chart
+ data={data}
+ xKey="month"
+ series={[line('revenue'), line('profit')]}
+ />,
+ );
+ reportWidth(600);
+
+ const strokes = Array.from(
+ container.querySelectorAll('g[clip-path] path[stroke]'),
+ ).map(p => p.getAttribute('stroke'));
+ expect(strokes).toHaveLength(2);
+ expect(strokes[0]).toBeTruthy();
+ expect(strokes[1]).toBeTruthy();
+ expect(strokes[0]).not.toBe(strokes[1]);
+ });
+});
+
+describe('Chart legend slot', () => {
+ it('derives legend items from series labels when legend is enabled', () => {
+ render(
+ <Chart
+ data={data}
+ xKey="month"
+ series={[bar('revenue', {label: 'Revenue'}), line('profit')]}
+ legend
+ />,
+ );
+ reportWidth(600);
+
+ const list = screen.getByRole('list', {name: 'Chart legend'});
+ const rows = within(list).getAllByRole('listitem');
+ expect(rows).toHaveLength(2);
+ expect(within(rows[0]).getByText('Revenue')).toBeInTheDocument();
+ // Label falls back to the dataKey when not provided.
+ expect(within(rows[1]).getByText('profit')).toBeInTheDocument();
+ });
+});
+
+describe('Chart tooltip slot', () => {
+ it('mounts the grouped tooltip portal only when tooltip is enabled', () => {
+ const {unmount} = render(
+ <Chart data={data} xKey="month" series={[bar('revenue')]} />,
+ );
+ reportWidth(600);
+ expect(document.querySelector('[role="tooltip"]')).toBeNull();
+ unmount();
+
+ render(
+ <Chart data={data} xKey="month" series={[bar('revenue')]} tooltip />,
+ );
+ reportWidth(600);
+ expect(document.querySelector('[role="tooltip"]')).not.toBeNull();
+ });
+});
diff --git a/packages/charts/src/ChartAxis.test.tsx b/packages/charts/src/ChartAxis.test.tsx
new file mode 100644
index 0000000000..d298f54848
--- /dev/null
+++ b/packages/charts/src/ChartAxis.test.tsx
@@ -0,0 +1,131 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file ChartAxis.test.tsx
+ * @input Uses vitest, @testing-library/react, Chart, ChartAxis, bar mark
+ * @output Functional tests for axis rendering — group semantics, band/linear
+ * tick labels, default edge-line rules, custom formatting, truncation,
+ * and label capping
+ * @position Colocated test for ChartAxis.tsx (issue #4295 viz coverage)
+ */
+
+import {describe, it, expect, vi, beforeEach, afterEach} from 'vitest';
+import {render, screen, act, within} from '@testing-library/react';
+import {Chart} from './Chart';
+import {ChartAxis} from './ChartAxis';
+import {bar} from './marks/bar';
+
+const DATA = [
+ {month: 'Jan', sales: 4},
+ {month: 'Feb', sales: 10},
+ {month: 'Mar', sales: 2},
+];
+
+// Capture the ResizeObserver callback so tests can drive the reported width.
+let resizeCallback: ResizeObserverCallback | undefined;
+
+beforeEach(() => {
+ resizeCallback = undefined;
+ vi.stubGlobal(
+ 'ResizeObserver',
+ class {
+ constructor(cb: ResizeObserverCallback) {
+ resizeCallback = cb;
+ }
+ observe() {}
+ unobserve() {}
+ disconnect() {}
+ },
+ );
+});
+
+afterEach(() => {
+ vi.unstubAllGlobals();
+});
+
+function reportWidth(width: number) {
+ act(() => {
+ resizeCallback?.(
+ [{contentRect: {width}} as unknown as ResizeObserverEntry],
+ {} as ResizeObserver,
+ );
+ });
+}
+
+function renderChart(axes: React.ReactNode, data = DATA) {
+ const utils = render(
+ <Chart data={data} xKey="month" series={[bar('sales')]} axes={axes} />,
+ );
+ reportWidth(600);
+ return utils;
+}
+
+describe('ChartAxis bottom (band scale)', () => {
+ it('renders a labeled group with one tick label per category', () => {
+ renderChart(<ChartAxis position="bottom" />);
+ const axis = screen.getByRole('group', {name: 'bottom axis'});
+ expect(within(axis).getByText('Jan')).toBeInTheDocument();
+ expect(within(axis).getByText('Feb')).toBeInTheDocument();
+ expect(within(axis).getByText('Mar')).toBeInTheDocument();
+ });
+
+ it('is translated to the bottom edge of the plot and draws its edge line by default', () => {
+ renderChart(<ChartAxis position="bottom" />);
+ const axis = screen.getByRole('group', {name: 'bottom axis'});
+ // Inner height for the default 300px chart: 300 - 24 - 32 = 244.
+ expect(axis).toHaveAttribute('transform', 'translate(0,244)');
+ const edge = axis.querySelector('line')!;
+ expect(edge).not.toBeNull();
+ expect(edge).toHaveAttribute('x2', '528');
+ });
+
+ it('caps labels to maxTicks by evenly skipping categories', () => {
+ renderChart(<ChartAxis position="bottom" maxTicks={2} />);
+ const axis = screen.getByRole('group', {name: 'bottom axis'});
+ // 3 categories capped at 2 → step 2 → indices 0 and 2 survive.
+ expect(within(axis).getByText('Jan')).toBeInTheDocument();
+ expect(within(axis).getByText('Mar')).toBeInTheDocument();
+ expect(within(axis).queryByText('Feb')).not.toBeInTheDocument();
+ });
+
+ it('truncates long category labels with an ellipsis', () => {
+ renderChart(<ChartAxis position="bottom" truncate={4} />, [
+ {month: 'January', sales: 4},
+ {month: 'Feb', sales: 10},
+ ]);
+ const axis = screen.getByRole('group', {name: 'bottom axis'});
+ expect(within(axis).getByText('Janu…')).toBeInTheDocument();
+ // Short labels are left alone.
+ expect(within(axis).getByText('Feb')).toBeInTheDocument();
+ });
+});
+
+describe('ChartAxis left (linear scale)', () => {
+ it('renders d3-formatted value ticks without an edge line by default', () => {
+ renderChart(<ChartAxis position="left" />);
+ const axis = screen.getByRole('group', {name: 'left axis'});
+ // Bar series pins a zero baseline → domain [0, 10] → ticks 0,2,...,10.
+ expect(within(axis).getByText('0')).toBeInTheDocument();
+ expect(within(axis).getByText('4')).toBeInTheDocument();
+ expect(within(axis).getByText('10')).toBeInTheDocument();
+ // Documented default: only the bottom axis draws its edge line.
+ expect(axis.querySelector('line')).toBeNull();
+ });
+
+ it('applies a custom tick formatter', () => {
+ renderChart(
+ <ChartAxis position="left" tickFormat={v => `$${String(v)}`} />,
+ );
+ const axis = screen.getByRole('group', {name: 'left axis'});
+ expect(within(axis).getByText('$0')).toBeInTheDocument();
+ expect(within(axis).getByText('$10')).toBeInTheDocument();
+ });
+
+ it('showTicks draws a perpendicular mark per tick and forces the axis line on', () => {
+ renderChart(<ChartAxis position="left" showTicks />);
+ const axis = screen.getByRole('group', {name: 'left axis'});
+ const lines = axis.querySelectorAll('line');
+ // 6 ticks (0..10 by 2) + the forced edge line.
+ expect(lines).toHaveLength(7);
+ });
+});
diff --git a/packages/charts/src/ChartGrid.test.tsx b/packages/charts/src/ChartGrid.test.tsx
new file mode 100644
index 0000000000..06e0a7de7b
--- /dev/null
+++ b/packages/charts/src/ChartGrid.test.tsx
@@ -0,0 +1,121 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file ChartGrid.test.tsx
+ * @input Uses vitest, @testing-library/react, Chart, ChartGrid, bar mark
+ * @output Functional tests for grid lines — horizontal default, the skipped
+ * y=0 line, and vertical lines at band centers
+ * @position Colocated test for ChartGrid.tsx (issue #4295 viz coverage)
+ */
+
+import {describe, it, expect, vi, beforeEach, afterEach} from 'vitest';
+import {render, act} from '@testing-library/react';
+import {Chart} from './Chart';
+import {ChartGrid} from './ChartGrid';
+import {bar} from './marks/bar';
+
+const DATA = [
+ {month: 'Jan', sales: 4},
+ {month: 'Feb', sales: 10},
+ {month: 'Mar', sales: 2},
+];
+
+// Capture the ResizeObserver callback so tests can drive the reported width.
+let resizeCallback: ResizeObserverCallback | undefined;
+
+beforeEach(() => {
+ resizeCallback = undefined;
+ vi.stubGlobal(
+ 'ResizeObserver',
+ class {
+ constructor(cb: ResizeObserverCallback) {
+ resizeCallback = cb;
+ }
+ observe() {}
+ unobserve() {}
+ disconnect() {}
+ },
+ );
+});
+
+afterEach(() => {
+ vi.unstubAllGlobals();
+});
+
+function reportWidth(width: number) {
+ act(() => {
+ resizeCallback?.(
+ [{contentRect: {width}} as unknown as ResizeObserverEntry],
+ {} as ResizeObserver,
+ );
+ });
+}
+
+function renderGrid(grid: React.ReactNode) {
+ const utils = render(
+ <Chart data={DATA} xKey="month" series={[bar('sales')]} grid={grid} />,
+ );
+ reportWidth(600);
+ // Marks render paths and the event layer is a rect, so every <line> in the
+ // svg belongs to the grid (no axes are mounted in these tests).
+ const lines = Array.from(utils.container.querySelectorAll('svg line'));
+ return {...utils, lines};
+}
+
+describe('ChartGrid', () => {
+ it('draws horizontal lines across the plot for every y tick except the y=0 baseline', () => {
+ const {lines} = renderGrid(<ChartGrid />);
+ // Domain [0, 10] → ticks 0,2,4,6,8,10; the 0 line is skipped → 5 lines.
+ expect(lines).toHaveLength(5);
+ for (const l of lines) {
+ expect(l.getAttribute('x1')).toBe('0');
+ expect(l.getAttribute('x2')).toBe('528'); // full plot width
+ expect(l.getAttribute('y1')).toBe(l.getAttribute('y2')); // horizontal
+ // y=0 maps to the plot bottom (244) — never double-drawn over the axis.
+ expect(l.getAttribute('y1')).not.toBe('244');
+ }
+ });
+
+ it('draws a vertical line at each band center when vertical is enabled', () => {
+ const {lines} = renderGrid(<ChartGrid horizontal={false} vertical />);
+ expect(lines).toHaveLength(3); // one per category
+ for (const l of lines) {
+ expect(l.getAttribute('x1')).toBe(l.getAttribute('x2')); // vertical
+ expect(l.getAttribute('y1')).toBe('0');
+ expect(l.getAttribute('y2')).toBe('244'); // full plot height
+ }
+ // Band centers are strictly increasing across categories.
+ const xs = lines.map(l => Number(l.getAttribute('x1')));
+ expect(xs[0]).toBeLessThan(xs[1]);
+ expect(xs[1]).toBeLessThan(xs[2]);
+ });
+
+ it('combines horizontal and vertical lines when both are enabled', () => {
+ const {lines} = renderGrid(<ChartGrid horizontal vertical />);
+ expect(lines).toHaveLength(8); // 5 horizontal + 3 vertical
+ });
+
+ it('places vertical lines at d3 tick values on a linear x scale', () => {
+ const numeric = [
+ {month: 0, sales: 1},
+ {month: 5, sales: 7},
+ {month: 10, sales: 3},
+ ];
+ const utils = render(
+ <Chart
+ data={numeric}
+ xKey="month"
+ series={[bar('sales')]}
+ grid={<ChartGrid horizontal={false} vertical />}
+ />,
+ );
+ reportWidth(600);
+ const lines = Array.from(utils.container.querySelectorAll('svg line'));
+ // Linear domain [0, 10] → ticks 0,2,4,6,8,10 → 6 evenly spaced lines.
+ expect(lines).toHaveLength(6);
+ const xs = lines.map(l => Number(l.getAttribute('x1')));
+ expect(xs[0]).toBe(0);
+ expect(xs[5]).toBe(528);
+ expect(xs[1] - xs[0]).toBeCloseTo(528 / 5);
+ });
+});
diff --git a/packages/charts/src/ChartLegend.test.tsx b/packages/charts/src/ChartLegend.test.tsx
new file mode 100644
index 0000000000..b950ee3cc8
--- /dev/null
+++ b/packages/charts/src/ChartLegend.test.tsx
@@ -0,0 +1,54 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file ChartLegend.test.tsx
+ * @input Uses vitest, @testing-library/react, ChartLegend
+ * @output Functional tests for the standalone chart legend
+ * @position Colocated test for ChartLegend.tsx (issue #4295 viz coverage)
+ */
+
+import {describe, it, expect} from 'vitest';
+import {render, screen, within} from '@testing-library/react';
+import {ChartLegend} from './ChartLegend';
+
+const items = [
+ {label: 'Revenue', color: '#ff0000', type: 'bar'},
+ {label: 'Profit', color: '#00ff00', type: 'line'},
+];
+
+describe('ChartLegend', () => {
+ it('exposes list semantics with one item per legend entry', () => {
+ render(<ChartLegend items={items} />);
+ const list = screen.getByRole('list', {name: 'Chart legend'});
+ const rows = within(list).getAllByRole('listitem');
+ expect(rows).toHaveLength(2);
+ expect(within(rows[0]).getByText('Revenue')).toBeInTheDocument();
+ expect(within(rows[1]).getByText('Profit')).toBeInTheDocument();
+ });
+
+ it('renders a decorative swatch in each entry with the item color', () => {
+ render(<ChartLegend items={items} />);
+ const rows = screen.getAllByRole('listitem');
+ const firstSwatch = rows[0].querySelector('[aria-hidden="true"]');
+ const secondSwatch = rows[1].querySelector('[aria-hidden="true"]');
+ expect(firstSwatch).not.toBeNull();
+ expect(firstSwatch!.getAttribute('style')).toContain('#ff0000');
+ expect(secondSwatch!.getAttribute('style')).toContain('#00ff00');
+ });
+
+ it('renders nothing when there are no items', () => {
+ const {container} = render(<ChartLegend items={[]} />);
+ expect(container.firstChild).toBeNull();
+ });
+
+ it('renders nothing when items are omitted entirely', () => {
+ const {container} = render(<ChartLegend />);
+ expect(container.firstChild).toBeNull();
+ });
+
+ it('keeps list semantics in the vertical (start/end) orientation', () => {
+ render(<ChartLegend items={items} position="end" />);
+ const list = screen.getByRole('list', {name: 'Chart legend'});
+ expect(within(list).getAllByRole('listitem')).toHaveLength(2);
+ });
+});
diff --git a/packages/charts/src/ChartSwatch.test.tsx b/packages/charts/src/ChartSwatch.test.tsx
new file mode 100644
index 0000000000..93d9c8486a
--- /dev/null
+++ b/packages/charts/src/ChartSwatch.test.tsx
@@ -0,0 +1,50 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file ChartSwatch.test.tsx
+ * @input Uses vitest, @testing-library/react, ChartSwatch
+ * @output Functional tests for the ChartSwatch color primitive
+ * @position Colocated test for ChartSwatch.tsx (issue #4295 viz coverage)
+ */
+
+import {describe, it, expect} from 'vitest';
+import {render} from '@testing-library/react';
+import {ChartSwatch, swatchVariantForType} from './ChartSwatch';
+
+describe('ChartSwatch', () => {
+ it('renders a decorative element hidden from the accessibility tree', () => {
+ const {container} = render(<ChartSwatch color="#ff0000" />);
+ const swatch = container.firstElementChild;
+ expect(swatch).not.toBeNull();
+ expect(swatch).toHaveAttribute('aria-hidden', 'true');
+ });
+
+ it('applies the given color through a dynamic style', () => {
+ const {container} = render(<ChartSwatch color="#ff0000" />);
+ const swatch = container.firstElementChild as HTMLElement;
+ expect(swatch.getAttribute('style')).toContain('#ff0000');
+ });
+
+ it('styles the square and line variants differently', () => {
+ const {container: square} = render(<ChartSwatch color="#000" />);
+ const {container: line} = render(
+ <ChartSwatch color="#000" variant="line" />,
+ );
+ expect(square.firstElementChild!.className).not.toBe(
+ line.firstElementChild!.className,
+ );
+ });
+});
+
+describe('swatchVariantForType', () => {
+ it('maps bar series to the square chip', () => {
+ expect(swatchVariantForType('bar')).toBe('square');
+ });
+
+ it('maps every non-bar series (and unknown types) to the line stroke', () => {
+ expect(swatchVariantForType('line')).toBe('line');
+ expect(swatchVariantForType('dot')).toBe('line');
+ expect(swatchVariantForType('area')).toBe('line');
+ expect(swatchVariantForType(undefined)).toBe('line');
+ });
+});
diff --git a/packages/charts/src/ChartTooltip.test.tsx b/packages/charts/src/ChartTooltip.test.tsx
new file mode 100644
index 0000000000..fe6c820ec3
--- /dev/null
+++ b/packages/charts/src/ChartTooltip.test.tsx
@@ -0,0 +1,282 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file ChartTooltip.test.tsx
+ * @input Uses vitest, @testing-library/react, ChartTooltip, ChartProvider,
+ * d3-scale
+ * @output Functional tests for the grouped tooltip — portal lifecycle, pointer
+ * subscription, card content/visibility, hover dots, crosshair vs band
+ * highlight, and the custom render contract
+ * @position Colocated test for ChartTooltip.tsx (issue #4295 viz coverage).
+ * Renders under a hand-built ChartProvider so the pointer stream can
+ * be driven directly (jsdom has no SVG geometry for the real one).
+ */
+
+import {describe, it, expect, vi} from 'vitest';
+import {render, act} from '@testing-library/react';
+import {scaleLinear, scaleBand} from 'd3-scale';
+import {ChartTooltip} from './ChartTooltip';
+import {ChartProvider} from './ChartContext';
+import type {
+ ChartContext,
+ ChartPointerEvent,
+ ResolvedPoint,
+ SeriesDef,
+} from './types';
+
+const DATA = [
+ {month: 'Jan', sales: 3, profit: 1},
+ {month: 'Feb', sales: 7, profit: 2},
+ {month: 'Mar', sales: 5, profit: 4},
+];
+
+const SALES_POINTS: ResolvedPoint[] = [
+ {px: 50, py: 120, py0: 200, dataIndex: 0},
+ {px: 250, py: 40, py0: 200, dataIndex: 1},
+ {px: 450, py: 80, py0: 200, dataIndex: 2},
+];
+
+/** Minimal post-layout series def, annotated the way computeLayout would. */
+function makeSeries(overrides: Partial<SeriesDef> = {}): SeriesDef {
+ return {
+ type: 'line',
+ key: 'sales',
+ dataKeys: ['sales'],
+ label: 'Sales',
+ color: '#ff0000',
+ layout: {},
+ resolve: () => [],
+ render: () => null,
+ _uid: '0:sales',
+ ...overrides,
+ } as SeriesDef;
+}
+
+interface Harness {
+ ctx: ChartContext;
+ handlers: Set<(e: ChartPointerEvent) => void>;
+ dispatch: (e: ChartPointerEvent) => void;
+}
+
+function makeHarness(overrides: Partial<ChartContext> = {}): Harness {
+ const handlers = new Set<(e: ChartPointerEvent) => void>();
+ const ctx: ChartContext = {
+ width: 500,
+ height: 200,
+ margin: {top: 24, right: 24, bottom: 32, left: 48},
+ data: DATA,
+ xKey: 'month',
+ xScale: scaleBand<string>()
+ .domain(['Jan', 'Feb', 'Mar'])
+ .range([0, 500])
+ .padding(0.2),
+ yScale: scaleLinear().domain([0, 10]).range([200, 0]),
+ resolved: new Map([['0:sales', SALES_POINTS]]),
+ onPointer: handler => {
+ handlers.add(handler);
+ return () => {
+ handlers.delete(handler);
+ };
+ },
+ svgRef: {current: null},
+ ...overrides,
+ };
+ const dispatch = (e: ChartPointerEvent) => {
+ act(() => {
+ for (const h of handlers) {
+ h(e);
+ }
+ });
+ };
+ return {ctx, handlers, dispatch};
+}
+
+function renderTooltip(
+ harness: Harness,
+ props: React.ComponentProps<typeof ChartTooltip> = {},
+) {
+ return render(
+ <ChartProvider value={harness.ctx}>
+ <svg>
+ <g>
+ <ChartTooltip series={[makeSeries()]} {...props} />
+ </g>
+ </svg>
+ </ChartProvider>,
+ );
+}
+
+const hoverAt = (index: number): ChartPointerEvent => ({
+ x: SALES_POINTS[index].px,
+ y: 100,
+ nearest: {...SALES_POINTS[index], seriesKey: 'sales'},
+ active: false,
+});
+
+const pointerLeave: ChartPointerEvent = {
+ x: -1,
+ y: -1,
+ nearest: null,
+ active: false,
+};
+
+const card = () => document.querySelector('[role="tooltip"]') as HTMLElement;
+
+describe('ChartTooltip card', () => {
+ it('portals an initially empty tooltip card into document.body', () => {
+ const harness = makeHarness();
+ const {container} = renderTooltip(harness);
+ expect(card()).not.toBeNull();
+ expect(card().parentElement).toBe(document.body);
+ // The card lives outside the chart subtree.
+ expect(container.querySelector('[role="tooltip"]')).toBeNull();
+ expect(card().textContent).toBe('');
+ });
+
+ it('shows the hovered x value and the bare value for a single series', () => {
+ const harness = makeHarness();
+ renderTooltip(harness);
+ harness.dispatch(hoverAt(1));
+ expect(card().textContent).toContain('Feb');
+ expect(card().textContent).toContain('7');
+ });
+
+ it('lists a labeled row per series for multi-series charts', () => {
+ const profitPoints = SALES_POINTS.map(p => ({...p, py: p.py + 30}));
+ const harness = makeHarness({
+ resolved: new Map([
+ ['0:sales', SALES_POINTS],
+ ['1:profit', profitPoints],
+ ]),
+ });
+ const series = [
+ makeSeries(),
+ makeSeries({
+ key: 'profit',
+ dataKeys: ['profit'],
+ label: 'Profit',
+ _uid: '1:profit',
+ }),
+ ];
+ renderTooltip(harness, {series});
+ harness.dispatch(hoverAt(1));
+ expect(card().textContent).toContain('Sales');
+ expect(card().textContent).toContain('7');
+ expect(card().textContent).toContain('Profit');
+ expect(card().textContent).toContain('2');
+ });
+
+ it('reveals the card on hover and hides it again when the pointer leaves', () => {
+ const svgEl = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
+ const harness = makeHarness({svgRef: {current: svgEl}});
+ renderTooltip(harness);
+
+ harness.dispatch(hoverAt(0));
+ expect(card().style.display).toBe('block');
+
+ harness.dispatch(pointerLeave);
+ expect(card().style.display).toBe('none');
+ });
+
+ it('pins the card beside the hovered point for placement="right"', () => {
+ const svgEl = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
+ const harness = makeHarness({svgRef: {current: svgEl}});
+ renderTooltip(harness, {placement: 'right'});
+ harness.dispatch(hoverAt(1));
+ // jsdom rects are zero, so left = svgLeft(0) + margin.left(48) + px(250)
+ // + the 8px gap.
+ expect(card().style.display).toBe('block');
+ expect(card().style.left).toBe('306px');
+ });
+
+ it('hides the card when the hovered index no longer exists in data', () => {
+ const svgEl = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
+ const harness = makeHarness({svgRef: {current: svgEl}});
+ renderTooltip(harness);
+ harness.dispatch({
+ x: 0,
+ y: 0,
+ nearest: {px: 50, py: 120, py0: 200, dataIndex: 99, seriesKey: 'sales'},
+ active: false,
+ });
+ expect(card().textContent).toBe('');
+ expect(card().style.display).toBe('none');
+ });
+});
+
+describe('ChartTooltip hover indicators', () => {
+ it('marks the hovered point of each series with a dot in the series color', () => {
+ const harness = makeHarness();
+ const {container} = renderTooltip(harness);
+ harness.dispatch(hoverAt(1));
+ const dot = container.querySelector('circle')!;
+ expect(dot).not.toBeNull();
+ expect(dot).toHaveAttribute('cx', '250');
+ expect(dot).toHaveAttribute('cy', '40');
+ expect(dot).toHaveAttribute('stroke', '#ff0000');
+ });
+
+ it('skips the hover dot when the series value is missing at that index', () => {
+ const gappy = SALES_POINTS.map((p, i) => (i === 1 ? {...p, py: NaN} : p));
+ const harness = makeHarness({resolved: new Map([['0:sales', gappy]])});
+ const {container} = renderTooltip(harness);
+ harness.dispatch(hoverAt(1));
+ expect(container.querySelector('circle')).toBeNull();
+ });
+
+ it('draws a vertical crosshair through the hovered x for line charts', () => {
+ const harness = makeHarness();
+ const {container} = renderTooltip(harness);
+ harness.dispatch(hoverAt(1));
+ const crosshair = container.querySelector('line')!;
+ expect(crosshair).not.toBeNull();
+ expect(crosshair.getAttribute('x1')).toBe(crosshair.getAttribute('x2'));
+ expect(crosshair).toHaveAttribute('y1', '0');
+ expect(crosshair).toHaveAttribute('y2', '200');
+ });
+
+ it('draws a soft band-highlight rect instead of a crosshair when the chart has bars', () => {
+ const harness = makeHarness();
+ const {container} = renderTooltip(harness, {
+ series: [makeSeries({type: 'bar'})],
+ });
+ harness.dispatch(hoverAt(1));
+ expect(container.querySelector('line')).toBeNull();
+ const highlight = container.querySelector('rect')!;
+ expect(highlight).not.toBeNull();
+ expect(Number(highlight.getAttribute('width'))).toBeGreaterThan(0);
+ });
+});
+
+describe('ChartTooltip custom render', () => {
+ it('replaces the card body and receives the x value plus one row per series', () => {
+ const renderFn = vi.fn(() => <span>custom body</span>);
+ const harness = makeHarness();
+ renderTooltip(harness, {render: renderFn});
+ harness.dispatch(hoverAt(1));
+ expect(card().textContent).toBe('custom body');
+ expect(renderFn).toHaveBeenCalledWith('Feb', [
+ expect.objectContaining({key: 'sales', label: 'Sales', value: 7}),
+ ]);
+ });
+
+ it('hides the card when the custom render opts out by returning null', () => {
+ const svgEl = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
+ const harness = makeHarness({svgRef: {current: svgEl}});
+ renderTooltip(harness, {render: () => null});
+ harness.dispatch(hoverAt(1));
+ expect(card().textContent).toBe('');
+ expect(card().style.display).toBe('none');
+ });
+});
+
+describe('ChartTooltip lifecycle', () => {
+ it('removes the portal and unsubscribes from the pointer stream on unmount', () => {
+ const harness = makeHarness();
+ const {unmount} = renderTooltip(harness);
+ expect(harness.handlers.size).toBe(1);
+ unmount();
+ expect(card()).toBeNull();
+ expect(harness.handlers.size).toBe(0);
+ });
+});
diff --git a/packages/charts/src/marks/marks.test.tsx b/packages/charts/src/marks/marks.test.tsx
new file mode 100644
index 0000000000..2adc74b737
--- /dev/null
+++ b/packages/charts/src/marks/marks.test.tsx
@@ -0,0 +1,443 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file marks/marks.test.tsx
+ * @input Uses vitest, @testing-library/react, Chart, all mark factories
+ * @output Functional tests for the mark renderers — SVG shape output per mark
+ * type, missing-value gap handling, and GL marks degrading safely when
+ * WebGL is unavailable (jsdom has no canvas contexts)
+ * @position Colocated test for the marks/ directory (issue #4295 viz coverage)
+ */
+
+import {describe, it, expect, vi, beforeEach, afterEach} from 'vitest';
+import {render, act, screen} from '@testing-library/react';
+import {Chart} from '../Chart';
+import {bar} from './bar';
+import {line} from './line';
+import {dot} from './dot';
+import {area} from './area';
+import {band} from './band';
+import {candlestick} from './candlestick';
+import {errorBar} from './errorBar';
+import {referenceLine} from './referenceLine';
+import {dotGL} from './dotGL';
+import {dotGLInteractive} from './dotGLInteractive';
+import {heatmapGL} from './heatmapGL';
+import {streamGL, type StreamGLHandle} from './streamGL';
+import type {SeriesDef} from '../types';
+
+const DATA = [
+ {m: 'A', v: 4},
+ {m: 'B', v: 7},
+ {m: 'C', v: 2},
+];
+
+// One missing value in the middle — marks must gap, not draw at the baseline.
+const GAPPY = [
+ {m: 'A', v: 4},
+ {m: 'B', v: null},
+ {m: 'C', v: 2},
+];
+
+const BOUNDS = [
+ {m: 'A', hi: 5, lo: 1},
+ {m: 'B', hi: 8, lo: 4},
+ {m: 'C', hi: 6, lo: 2},
+];
+
+// Capture the ResizeObserver callback so tests can drive the reported width.
+let resizeCallback: ResizeObserverCallback | undefined;
+
+beforeEach(() => {
+ resizeCallback = undefined;
+ vi.stubGlobal(
+ 'ResizeObserver',
+ class {
+ constructor(cb: ResizeObserverCallback) {
+ resizeCallback = cb;
+ }
+ observe() {}
+ unobserve() {}
+ disconnect() {}
+ },
+ );
+});
+
+afterEach(() => {
+ vi.unstubAllGlobals();
+});
+
+function reportWidth(width: number) {
+ act(() => {
+ resizeCallback?.(
+ [{contentRect: {width}} as unknown as ResizeObserverEntry],
+ {} as ResizeObserver,
+ );
+ });
+}
+
+/** Render a chart, report a width, and return the clipped plot group. */
+function renderMarks(
+ series: SeriesDef[],
+ data: Record<string, unknown>[] = DATA,
+ xKey = 'm',
+ extraProps: Partial<React.ComponentProps<typeof Chart>> = {},
+) {
+ const utils = render(
+ <Chart data={data} xKey={xKey} series={series} {...extraProps} />,
+ );
+ reportWidth(600);
+ const plot = utils.container.querySelector('g[clip-path]')!;
+ return {...utils, plot};
+}
+
+describe('bar', () => {
+ it('renders one top-rounded path per datum in the configured color', () => {
+ const {plot} = renderMarks([bar('v', {color: '#123456'})]);
+ const paths = plot.querySelectorAll('path');
+ expect(paths).toHaveLength(3);
+ for (const p of paths) {
+ expect(p).toHaveAttribute('fill', '#123456');
+ expect(p.getAttribute('d')).toMatch(/^M/);
+ // Positive bars round the top corners (default radius 4).
+ expect(p.getAttribute('d')).toContain('Q');
+ }
+ });
+
+ it('skips bars whose value is missing instead of drawing them at the baseline', () => {
+ const {plot} = renderMarks([bar('v')], GAPPY);
+ expect(plot.querySelectorAll('path')).toHaveLength(2);
+ });
+
+ it('stacked bars round only the topmost layer', () => {
+ const stacked = [
+ {m: 'A', a: 2, b: 3},
+ {m: 'B', a: 4, b: 1},
+ ];
+ const {plot} = renderMarks(
+ [bar('a', {stack: 'total'}), bar('b', {stack: 'total'})],
+ stacked,
+ );
+ const groups = Array.from(plot.children).filter(el => el.tagName === 'g');
+ const [lowerPaths, upperPaths] = groups.map(g =>
+ Array.from(g.querySelectorAll('path')),
+ );
+ expect(lowerPaths).toHaveLength(2);
+ expect(upperPaths).toHaveLength(2);
+ // The lower layer is drawn square; only the stack top gets rounded corners.
+ for (const p of lowerPaths) {
+ expect(p.getAttribute('d')).not.toContain('Q');
+ }
+ for (const p of upperPaths) {
+ expect(p.getAttribute('d')).toContain('Q');
+ }
+ });
+
+ it('grouped bars render side by side within the band', () => {
+ const grouped = [
+ {m: 'A', a: 2, b: 3},
+ {m: 'B', a: 4, b: 1},
+ ];
+ const {plot} = renderMarks(
+ [bar('a', {group: 'g'}), bar('b', {group: 'g'})],
+ grouped,
+ );
+ const groups = Array.from(plot.children).filter(el => el.tagName === 'g');
+ const firstX = (g: Element) =>
+ Number(
+ g
+ .querySelector('path')!
+ .getAttribute('d')!
+ .match(/^M([\d.]+)/)![1],
+ );
+ // For the same category, the second group's sub-bar starts further right.
+ expect(firstX(groups[1])).toBeGreaterThan(firstX(groups[0]));
+ });
+});
+
+describe('line', () => {
+ it('renders a single stroke path with the configured color and width', () => {
+ const {plot} = renderMarks([line('v', {color: '#ff0000', strokeWidth: 3})]);
+ const paths = plot.querySelectorAll('path');
+ expect(paths).toHaveLength(1);
+ expect(paths[0]).toHaveAttribute('stroke', '#ff0000');
+ expect(paths[0]).toHaveAttribute('stroke-width', '3');
+ expect(paths[0]).toHaveAttribute('fill', 'none');
+ expect(paths[0].getAttribute('d')).toMatch(/^M/);
+ });
+
+ it('draws per-point dots only where the value is finite', () => {
+ const {plot} = renderMarks([line('v', {dots: true})], GAPPY);
+ expect(plot.querySelectorAll('circle')).toHaveLength(2);
+ });
+});
+
+describe('dot', () => {
+ it('renders one circle per datum with the configured radius', () => {
+ const {plot} = renderMarks([dot('v', {radius: 5})]);
+ const circles = plot.querySelectorAll('circle');
+ expect(circles).toHaveLength(3);
+ for (const c of circles) {
+ expect(c).toHaveAttribute('r', '5');
+ expect(c).toHaveAttribute('opacity', '0.8'); // default
+ }
+ });
+
+ it('skips points whose value is missing', () => {
+ const {plot} = renderMarks([dot('v')], GAPPY);
+ expect(plot.querySelectorAll('circle')).toHaveLength(2);
+ });
+
+ it('dodge spreads coincident points horizontally, centered on the shared x', () => {
+ // Two rows in the same category land on the same band center.
+ const coincident = [
+ {m: 'A', v: 4},
+ {m: 'A', v: 6},
+ {m: 'B', v: 2},
+ ];
+ const {plot} = renderMarks(
+ [dot('v', {dodge: true, radius: 4})],
+ coincident,
+ );
+ const circles = Array.from(plot.querySelectorAll('circle'));
+ expect(circles).toHaveLength(3);
+ const [a1, a2] = circles.slice(0, 2).map(c => Number(c.getAttribute('cx')));
+ // Spacing is radius * 2 + 1 = 9px, split symmetrically around the center.
+ expect(a2 - a1).toBeCloseTo(9);
+ const bandCenter = (a1 + a2) / 2;
+ expect(Number(circles[0].getAttribute('cx'))).toBeCloseTo(bandCenter - 4.5);
+ });
+});
+
+describe('area', () => {
+ it('renders a translucent fill path plus a stroke path by default', () => {
+ const {plot} = renderMarks([area('v', {color: '#00aa00'})]);
+ const paths = plot.querySelectorAll('path');
+ expect(paths).toHaveLength(2);
+ expect(paths[0]).toHaveAttribute('fill', '#00aa00');
+ expect(paths[0]).toHaveAttribute('fill-opacity', '0.3');
+ expect(paths[1]).toHaveAttribute('fill', 'none');
+ expect(paths[1]).toHaveAttribute('stroke', '#00aa00');
+ });
+
+ it('omits the stroke path when stroke is disabled', () => {
+ const {plot} = renderMarks([area('v', {stroke: false})]);
+ expect(plot.querySelectorAll('path')).toHaveLength(1);
+ });
+
+ it('gradient mode defines a per-series gradient and fills with it', () => {
+ const {plot} = renderMarks([area('v', {gradient: true})]);
+ const gradient = plot.querySelector('linearGradient')!;
+ expect(gradient).not.toBeNull();
+ expect(gradient.querySelectorAll('stop')).toHaveLength(2);
+ const fillPath = plot.querySelector('path')!;
+ expect(fillPath.getAttribute('fill')).toBe(`url(#${gradient.id})`);
+ });
+});
+
+describe('band', () => {
+ it('fills the region between the upper and lower bounds', () => {
+ const {plot} = renderMarks([band({upper: 'hi', lower: 'lo'})], BOUNDS);
+ const paths = plot.querySelectorAll('path');
+ expect(paths).toHaveLength(1);
+ expect(paths[0]).toHaveAttribute('fill-opacity', '0.15'); // default
+ expect(paths[0].getAttribute('d')).toMatch(/^M/);
+ });
+
+ it('renders nothing when no point has both bounds', () => {
+ const missing = [
+ {m: 'A', lo: 1},
+ {m: 'B', lo: 4},
+ ];
+ const {plot} = renderMarks([band({upper: 'hi', lower: 'lo'})], missing);
+ expect(plot.querySelectorAll('path')).toHaveLength(0);
+ });
+});
+
+describe('candlestick', () => {
+ const OHLC = [
+ {m: 'A', o: 2, h: 6, l: 1, c: 5}, // up: close >= open
+ {m: 'B', o: 6, h: 7, l: 2, c: 3}, // down
+ {m: 'C', o: 3, h: 5, l: 2, c: 4}, // up
+ ];
+ const series = () =>
+ candlestick({open: 'o', high: 'h', low: 'l', close: 'c'});
+
+ it('renders a wick line and a body rect per candle, colored by direction', () => {
+ const {plot} = renderMarks([series()], OHLC);
+ const rects = plot.querySelectorAll('rect');
+ const wicks = plot.querySelectorAll('line');
+ expect(rects).toHaveLength(3);
+ expect(wicks).toHaveLength(3);
+ expect(rects[0]).toHaveAttribute('fill', 'var(--color-success)');
+ expect(rects[1]).toHaveAttribute('fill', 'var(--color-error)');
+ expect(rects[2]).toHaveAttribute('fill', 'var(--color-success)');
+ });
+
+ it('skips candles missing any OHLC field', () => {
+ const gappy = [OHLC[0], {m: 'B', o: 6, l: 2, c: 3}, OHLC[2]];
+ const {plot} = renderMarks([series()], gappy);
+ expect(plot.querySelectorAll('rect')).toHaveLength(2);
+ expect(plot.querySelectorAll('line')).toHaveLength(2);
+ });
+});
+
+describe('errorBar', () => {
+ it('renders a stem plus two whisker caps per point', () => {
+ const {plot} = renderMarks([errorBar({high: 'hi', low: 'lo'})], BOUNDS);
+ const lines = plot.querySelectorAll('line');
+ expect(lines).toHaveLength(9); // 3 points x (stem + upper cap + lower cap)
+ for (const l of lines) {
+ expect(l).toHaveAttribute('stroke', 'var(--color-text-primary)');
+ }
+ });
+
+ it('skips whiskers missing either bound', () => {
+ const gappy = [BOUNDS[0], {m: 'B', hi: 8}, BOUNDS[2]];
+ const {plot} = renderMarks([errorBar({high: 'hi', low: 'lo'})], gappy);
+ expect(plot.querySelectorAll('line')).toHaveLength(6);
+ });
+});
+
+describe('referenceLine', () => {
+ it('draws a dashed horizontal line across the plot with a label badge', () => {
+ const {plot} = renderMarks([
+ line('v'),
+ referenceLine({y: 5, label: 'Target'}),
+ ]);
+ const dashed = plot.querySelector('line[stroke-dasharray="6 3"]')!;
+ expect(dashed).not.toBeNull();
+ expect(dashed).toHaveAttribute('x1', '0');
+ expect(dashed).toHaveAttribute('x2', '528'); // full plot width
+ expect(dashed.getAttribute('y1')).toBe(dashed.getAttribute('y2'));
+ expect(screen.getByText('Target')).toBeInTheDocument();
+ expect(plot.querySelector('rect[rx="3"]')).not.toBeNull(); // badge chip
+ });
+
+ it('shades a band between y and y2 bounded by two dashed lines', () => {
+ const {plot} = renderMarks([line('v'), referenceLine({y: 2, y2: 6})]);
+ expect(plot.querySelectorAll('line[stroke-dasharray="6 3"]')).toHaveLength(
+ 2,
+ );
+ const bandRect = plot.querySelector('rect[opacity="0.1"]')!;
+ expect(bandRect).not.toBeNull();
+ expect(bandRect).toHaveAttribute('width', '528');
+ });
+
+ it('draws a vertical dashed line at a numeric x on a linear scale', () => {
+ const numeric = [
+ {x: 0, v: 1},
+ {x: 5, v: 7},
+ {x: 10, v: 3},
+ ];
+ const {plot} = renderMarks(
+ [line('v'), referenceLine({x: 5})],
+ numeric,
+ 'x',
+ );
+ const dashed = plot.querySelector('line[stroke-dasharray="6 3"]')!;
+ expect(dashed).not.toBeNull();
+ expect(dashed.getAttribute('x1')).toBe(dashed.getAttribute('x2'));
+ expect(dashed).toHaveAttribute('y1', '0');
+ expect(dashed).toHaveAttribute('y2', '244'); // full plot height
+ });
+});
+
+describe('GL marks without WebGL', () => {
+ let getContextSpy: ReturnType<typeof vi.fn>;
+ const canvasProto = HTMLCanvasElement.prototype;
+ let originalGetContext: typeof canvasProto.getContext;
+ // jsdom has no SVG geometry API; give markers a null CTM so
+ // mountCanvasOverSVG takes its documented (0,0) fallback.
+ const svgProto = SVGElement.prototype as unknown as {
+ getScreenCTM?: () => unknown;
+ };
+ let hadGetScreenCTM: boolean;
+
+ beforeEach(() => {
+ originalGetContext = canvasProto.getContext;
+ getContextSpy = vi.fn(() => null);
+ canvasProto.getContext =
+ getContextSpy as unknown as typeof canvasProto.getContext;
+ hadGetScreenCTM = 'getScreenCTM' in svgProto;
+ if (!hadGetScreenCTM) {
+ svgProto.getScreenCTM = () => null;
+ }
+ });
+
+ afterEach(() => {
+ canvasProto.getContext = originalGetContext;
+ if (!hadGetScreenCTM) {
+ delete svgProto.getScreenCTM;
+ }
+ });
+
+ it('dotGL mounts an absolutely-positioned canvas overlay and draws nothing', () => {
+ const {container, unmount} = renderMarks([dotGL('v', {color: '#4f46e5'})]);
+ const canvas = container.querySelector('canvas')!;
+ expect(canvas).not.toBeNull();
+ expect(canvas.style.position).toBe('absolute');
+ expect(getContextSpy).toHaveBeenCalledWith(
+ 'webgl',
+ expect.objectContaining({alpha: true}),
+ );
+ // Every context request failed → no GL drawing could have happened.
+ expect(getContextSpy.mock.results.every(r => r.value === null)).toBe(true);
+ unmount();
+ });
+
+ it('heatmapGL mounts its cell canvas when both axes are categorical', () => {
+ const heat = [
+ {hour: '0', day: 'Mon', count: 1},
+ {hour: '1', day: 'Mon', count: 5},
+ {hour: '0', day: 'Tue', count: 3},
+ {hour: '1', day: 'Tue', count: 2},
+ ];
+ const {container, unmount} = renderMarks(
+ [
+ heatmapGL({
+ xKey: 'hour',
+ yKey: 'day',
+ valueKey: 'count',
+ colorRange: ['#000000', '#ffffff'],
+ }),
+ ],
+ heat,
+ 'hour',
+ );
+ expect(container.querySelector('canvas')).not.toBeNull();
+ expect(getContextSpy.mock.results.every(r => r.value === null)).toBe(true);
+ unmount();
+ });
+
+ it('streamGL exposes an imperative push/clear handle even without WebGL', () => {
+ const handleRef: {current: StreamGLHandle | null} = {current: null};
+ const {container, unmount} = renderMarks(
+ [streamGL({color: '#10b981', handleRef})],
+ [],
+ 'x',
+ {xDomain: [0, 10]},
+ );
+ expect(container.querySelector('canvas')).not.toBeNull();
+ expect(handleRef.current).not.toBeNull();
+ // Pushing and clearing must not crash when the GL context is unavailable.
+ act(() => {
+ handleRef.current!.push(1, 2);
+ handleRef.current!.push(2, 4);
+ handleRef.current!.clear();
+ });
+ unmount();
+ });
+
+ it('dotGLInteractive renders its two canvases and hover hit area without crashing', () => {
+ const {plot, unmount} = renderMarks([
+ dotGLInteractive('v', {color: '#111111'}),
+ ]);
+ const foreignObjects = plot.querySelectorAll('foreignObject');
+ expect(foreignObjects).toHaveLength(2); // visible + offscreen pick canvas
+ expect(foreignObjects[0].querySelector('canvas')).not.toBeNull();
+ expect(foreignObjects[1].querySelector('canvas')).not.toBeNull();
+ expect(plot.querySelector('rect[fill="transparent"]')).not.toBeNull();
+ unmount();
+ });
+});
diff --git a/packages/charts/src/useChartColors.test.ts b/packages/charts/src/useChartColors.test.ts
new file mode 100644
index 0000000000..b6c9a04d43
--- /dev/null
+++ b/packages/charts/src/useChartColors.test.ts
@@ -0,0 +1,51 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file useChartColors.test.ts
+ * @input Uses vitest, @testing-library/react renderHook, useChartColors
+ * @output Functional tests for the theme-aware chart color palette hook
+ * @position Colocated test for useChartColors.ts (issue #4295 viz coverage)
+ */
+
+import {describe, it, expect} from 'vitest';
+import {renderHook} from '@testing-library/react';
+import {useChartColors} from './useChartColors';
+
+describe('useChartColors', () => {
+ it('returns the requested number of categorical colors', () => {
+ const {result} = renderHook(() => useChartColors());
+ const colors = result.current.categorical(4);
+ expect(colors).toHaveLength(4);
+ for (const c of colors) {
+ expect(typeof c).toBe('string');
+ expect(c.length).toBeGreaterThan(0);
+ }
+ });
+
+ it('assigns distinct colors within the first palette cycle', () => {
+ const {result} = renderHook(() => useChartColors());
+ const colors = result.current.categorical(4);
+ expect(new Set(colors).size).toBe(4);
+ });
+
+ it('wraps around the palette when more series than slots are requested', () => {
+ const {result} = renderHook(() => useChartColors());
+ const colors = result.current.categorical(12);
+ expect(colors).toHaveLength(12);
+ // 10 categorical tokens — slot 10 and 11 reuse slot 0 and 1.
+ expect(colors[10]).toBe(colors[0]);
+ expect(colors[11]).toBe(colors[1]);
+ });
+
+ it('returns an empty palette for a non-positive count', () => {
+ const {result} = renderHook(() => useChartColors());
+ expect(result.current.categorical(0)).toEqual([]);
+ });
+
+ it('returns a referentially stable API across rerenders', () => {
+ const {result, rerender} = renderHook(() => useChartColors());
+ const first = result.current;
+ rerender();
+ expect(result.current).toBe(first);
+ });
+});
diff --git a/packages/core/src/AlertDialog/useImperativeAlertDialog.test.tsx b/packages/core/src/AlertDialog/useImperativeAlertDialog.test.tsx
new file mode 100644
index 0000000000..d936852332
--- /dev/null
+++ b/packages/core/src/AlertDialog/useImperativeAlertDialog.test.tsx
@@ -0,0 +1,163 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file useImperativeAlertDialog.test.tsx
+ * @input Uses vitest, @testing-library/react, useImperativeAlertDialog hook
+ * @output Unit tests for the imperative show/hide alert dialog wrapper
+ * @position Testing; validates useImperativeAlertDialog.tsx implementation
+ *
+ * SYNC: When useImperativeAlertDialog.tsx changes, update tests to match
+ */
+
+import {describe, it, expect, vi, beforeEach} from 'vitest';
+import {render, screen, fireEvent, renderHook} from '@testing-library/react';
+import {useImperativeAlertDialog} from './useImperativeAlertDialog';
+
+// jsdom doesn't implement dialog.showModal/close; mirror the open attribute so
+// tests can tell an open dialog from a closed one.
+beforeEach(() => {
+ HTMLDialogElement.prototype.showModal = vi.fn(function (
+ this: HTMLDialogElement,
+ ) {
+ this.setAttribute('open', '');
+ });
+ HTMLDialogElement.prototype.close = vi.fn(function (this: HTMLDialogElement) {
+ this.removeAttribute('open');
+ });
+});
+
+const deleteOptions = {
+ title: 'Delete item?',
+ description: 'This action cannot be undone.',
+ actionLabel: 'Delete',
+ onAction: () => {},
+};
+
+const noop = () => {};
+
+function TestHarness({onAction = noop}: {onAction?: () => void}) {
+ const alert = useImperativeAlertDialog();
+
+ return (
+ <div>
+ <button
+ type="button"
+ onClick={() => alert.show({...deleteOptions, onAction})}>
+ Open
+ </button>
+ <button
+ type="button"
+ onClick={() =>
+ alert.show({
+ title: 'Archive item?',
+ description: 'You can restore it later.',
+ actionLabel: 'Archive',
+ actionVariant: 'primary',
+ onAction: () => {},
+ })
+ }>
+ Open Archive
+ </button>
+ <button type="button" onClick={() => alert.hide()}>
+ Close
+ </button>
+ <span data-testid="status">{alert.isOpen ? 'open' : 'closed'}</span>
+ {alert.element}
+ </div>
+ );
+}
+
+describe('useImperativeAlertDialog', () => {
+ it('starts closed', () => {
+ render(<TestHarness />);
+ expect(screen.getByTestId('status').textContent).toBe('closed');
+ });
+
+ it('renders nothing until the first show()', () => {
+ render(<TestHarness />);
+ expect(document.querySelector('dialog')).toBeNull();
+ });
+
+ it('returns a null element before the first show()', () => {
+ const {result} = renderHook(() => useImperativeAlertDialog());
+ expect(result.current.element).toBeNull();
+ });
+
+ it('opens on show()', () => {
+ render(<TestHarness />);
+ fireEvent.click(screen.getByText('Open'));
+ expect(screen.getByTestId('status').textContent).toBe('open');
+ expect(screen.getByRole('alertdialog')).toHaveAttribute('open');
+ });
+
+ it('renders the title, description and action label passed to show()', () => {
+ render(<TestHarness />);
+ fireEvent.click(screen.getByText('Open'));
+ expect(screen.getByText('Delete item?')).toBeInTheDocument();
+ expect(
+ screen.getByText('This action cannot be undone.'),
+ ).toBeInTheDocument();
+ expect(screen.getByRole('button', {name: 'Delete'})).toBeInTheDocument();
+ });
+
+ it('falls back to the translated cancel label', () => {
+ render(<TestHarness />);
+ fireEvent.click(screen.getByText('Open'));
+ expect(screen.getByRole('button', {name: 'Cancel'})).toBeInTheDocument();
+ });
+
+ it('closes on hide()', () => {
+ render(<TestHarness />);
+ fireEvent.click(screen.getByText('Open'));
+ expect(screen.getByTestId('status').textContent).toBe('open');
+
+ fireEvent.click(screen.getByText('Close'));
+ expect(screen.getByTestId('status').textContent).toBe('closed');
+ expect(document.querySelector('dialog')).not.toHaveAttribute('open');
+ });
+
+ it('keeps the dialog mounted after hide() so it can be reopened', () => {
+ render(<TestHarness />);
+ fireEvent.click(screen.getByText('Open'));
+ fireEvent.click(screen.getByText('Close'));
+ expect(document.querySelector('dialog')).toBeInTheDocument();
+
+ fireEvent.click(screen.getByText('Open'));
+ expect(screen.getByTestId('status').textContent).toBe('open');
+ });
+
+ it('closes when the dialog cancel button is pressed', () => {
+ render(<TestHarness />);
+ fireEvent.click(screen.getByText('Open'));
+
+ fireEvent.click(screen.getByRole('button', {name: 'Cancel'}));
+ expect(screen.getByTestId('status').textContent).toBe('closed');
+ });
+
+ it('runs the onAction passed to show() when the action button is pressed', () => {
+ const onAction = vi.fn();
+ render(<TestHarness onAction={onAction} />);
+ fireEvent.click(screen.getByText('Open'));
+
+ fireEvent.click(screen.getByRole('button', {name: 'Delete'}));
+ expect(onAction).toHaveBeenCalledTimes(1);
+ // The dialog does not auto-close — that is the caller's job.
+ expect(screen.getByTestId('status').textContent).toBe('open');
+ });
+
+ it('replaces the content when show() is called again with new options', () => {
+ render(<TestHarness />);
+ fireEvent.click(screen.getByText('Open'));
+ expect(screen.getByText('Delete item?')).toBeInTheDocument();
+
+ fireEvent.click(screen.getByText('Open Archive'));
+ expect(screen.queryByText('Delete item?')).toBeNull();
+ expect(screen.getByText('Archive item?')).toBeInTheDocument();
+ expect(screen.getByRole('button', {name: 'Archive'})).toBeInTheDocument();
+ });
+
+ // The `if (!open)` guard in the hook's onOpenChange is deliberately not
+ // covered: AlertDialog only ever reports `false`, so the ignored-`true` path
+ // is unreachable through the public surface. Forcing it through the element's
+ // props would assert a value that is already settled.
+});
diff --git a/packages/core/src/Calendar/hooks/useCalendarConstraints.test.ts b/packages/core/src/Calendar/hooks/useCalendarConstraints.test.ts
new file mode 100644
index 0000000000..8cbe432fcf
--- /dev/null
+++ b/packages/core/src/Calendar/hooks/useCalendarConstraints.test.ts
@@ -0,0 +1,153 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file useCalendarConstraints.test.ts
+ * @input Uses vitest, @testing-library/react
+ * @output Unit tests for useCalendarConstraints hook
+ * @position Testing; validates min/max inclusivity and custom constraint
+ * evaluation
+ */
+
+import {describe, it, expect, vi} from 'vitest';
+import {renderHook} from '@testing-library/react';
+import {useCalendarConstraints} from './useCalendarConstraints';
+
+// =============================================================================
+// Defaults
+// =============================================================================
+
+describe('useCalendarConstraints — defaults', () => {
+ it('never disables a date when no options are given', () => {
+ const {result} = renderHook(() => useCalendarConstraints({}));
+
+ expect(result.current.isDateDisabled({year: 2026, month: 6, day: 15})).toBe(
+ false,
+ );
+ expect(result.current.isDateDisabled({year: 1900, month: 1, day: 1})).toBe(
+ false,
+ );
+ expect(result.current.minDate).toBeNull();
+ expect(result.current.maxDate).toBeNull();
+ });
+
+ it('parses min and max ISO strings into PlainDates', () => {
+ const {result} = renderHook(() =>
+ useCalendarConstraints({min: '2026-01-05', max: '2026-11-30'}),
+ );
+
+ expect(result.current.minDate).toEqual({year: 2026, month: 1, day: 5});
+ expect(result.current.maxDate).toEqual({year: 2026, month: 11, day: 30});
+ });
+});
+
+// =============================================================================
+// Min / max bounds (inclusive)
+// =============================================================================
+
+describe('useCalendarConstraints — min/max bounds', () => {
+ it('treats min as inclusive: the min date itself is selectable', () => {
+ const {result} = renderHook(() =>
+ useCalendarConstraints({min: '2026-06-10'}),
+ );
+ const {isDateDisabled} = result.current;
+
+ expect(isDateDisabled({year: 2026, month: 6, day: 9})).toBe(true);
+ expect(isDateDisabled({year: 2026, month: 6, day: 10})).toBe(false);
+ expect(isDateDisabled({year: 2026, month: 6, day: 11})).toBe(false);
+ // Before-min comparison works across month and year boundaries.
+ expect(isDateDisabled({year: 2025, month: 12, day: 31})).toBe(true);
+ });
+
+ it('treats max as inclusive: the max date itself is selectable', () => {
+ const {result} = renderHook(() =>
+ useCalendarConstraints({max: '2026-06-20'}),
+ );
+ const {isDateDisabled} = result.current;
+
+ expect(isDateDisabled({year: 2026, month: 6, day: 20})).toBe(false);
+ expect(isDateDisabled({year: 2026, month: 6, day: 21})).toBe(true);
+ // After-max comparison works across year boundaries.
+ expect(isDateDisabled({year: 2027, month: 1, day: 1})).toBe(true);
+ });
+
+ it('allows only dates inside a min+max window, edges included', () => {
+ const {result} = renderHook(() =>
+ useCalendarConstraints({min: '2026-06-10', max: '2026-06-20'}),
+ );
+ const {isDateDisabled} = result.current;
+
+ expect(isDateDisabled({year: 2026, month: 6, day: 9})).toBe(true);
+ expect(isDateDisabled({year: 2026, month: 6, day: 10})).toBe(false);
+ expect(isDateDisabled({year: 2026, month: 6, day: 15})).toBe(false);
+ expect(isDateDisabled({year: 2026, month: 6, day: 20})).toBe(false);
+ expect(isDateDisabled({year: 2026, month: 6, day: 21})).toBe(true);
+ });
+});
+
+// =============================================================================
+// Custom constraints
+// =============================================================================
+
+describe('useCalendarConstraints — custom constraints', () => {
+ it('disables a date when any single constraint returns false', () => {
+ const {result: failsLast} = renderHook(() =>
+ useCalendarConstraints({dateConstraints: [() => true, () => false]}),
+ );
+ const {result: failsFirst} = renderHook(() =>
+ useCalendarConstraints({dateConstraints: [() => false, () => true]}),
+ );
+
+ expect(
+ failsLast.current.isDateDisabled({year: 2026, month: 6, day: 15}),
+ ).toBe(true);
+ expect(
+ failsFirst.current.isDateDisabled({year: 2026, month: 6, day: 15}),
+ ).toBe(true);
+ });
+
+ it('enables a date only after every constraint passes', () => {
+ const first = vi.fn(() => true);
+ const second = vi.fn(() => true);
+ const {result} = renderHook(() =>
+ useCalendarConstraints({dateConstraints: [first, second]}),
+ );
+
+ expect(result.current.isDateDisabled({year: 2026, month: 6, day: 15})).toBe(
+ false,
+ );
+ expect(first).toHaveBeenCalledTimes(1);
+ expect(second).toHaveBeenCalledTimes(1);
+ });
+
+ it('passes the checked day to constraints as a native Date', () => {
+ const constraint = vi.fn((_date: Date) => true);
+ const {result} = renderHook(() =>
+ useCalendarConstraints({dateConstraints: [constraint]}),
+ );
+
+ result.current.isDateDisabled({year: 2026, month: 6, day: 15});
+
+ expect(constraint).toHaveBeenCalledTimes(1);
+ const received = constraint.mock.calls[0][0];
+ expect(received).toBeInstanceOf(Date);
+ expect(received.getFullYear()).toBe(2026);
+ expect(received.getMonth()).toBe(5); // native Date months are 0-based
+ expect(received.getDate()).toBe(15);
+ });
+
+ it('supports day-of-week rules through the native Date conversion', () => {
+ // No Sundays. 2026-02-01 is a Sunday; 2026-02-02 is a Monday.
+ const {result} = renderHook(() =>
+ useCalendarConstraints({
+ dateConstraints: [date => date.getDay() !== 0],
+ }),
+ );
+
+ expect(result.current.isDateDisabled({year: 2026, month: 2, day: 1})).toBe(
+ true,
+ );
+ expect(result.current.isDateDisabled({year: 2026, month: 2, day: 2})).toBe(
+ false,
+ );
+ });
+});
diff --git a/packages/core/src/Calendar/hooks/useCalendarDays.test.ts b/packages/core/src/Calendar/hooks/useCalendarDays.test.ts
new file mode 100644
index 0000000000..4b6a101217
--- /dev/null
+++ b/packages/core/src/Calendar/hooks/useCalendarDays.test.ts
@@ -0,0 +1,265 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file useCalendarDays.test.ts
+ * @input Uses vitest, @testing-library/react
+ * @output Unit tests for useCalendarDays hook
+ * @position Testing; validates calendar grid generation (offsets, outside
+ * days, row counts, day-name rotation)
+ */
+
+import {describe, it, expect} from 'vitest';
+import {renderHook} from '@testing-library/react';
+import {useCalendarDays} from './useCalendarDays';
+
+// Day-of-week fixture facts (verified independently against the Gregorian
+// calendar, not against the hook):
+// 2026-01-01 = Thursday, 2026-02-01 = Sunday, 2026-03-01 = Sunday,
+// 2024-02-01 = Thursday (leap year), 2025-12-01 = Monday.
+
+// =============================================================================
+// Grid offsets and outside days
+// =============================================================================
+
+describe('useCalendarDays — grid offsets and outside days', () => {
+ it('renders a month starting exactly on weekStartsOn with zero leading cells', () => {
+ // February 2026 starts on a Sunday; weekStartsOn defaults to Sunday.
+ const {result} = renderHook(() =>
+ useCalendarDays({year: 2026, month: 2, hasVariableRowCount: true}),
+ );
+
+ // 28 days, no leading offset → exactly 4 rows, no outside days at all.
+ expect(result.current.totalCells).toBe(28);
+ expect(result.current.days).toHaveLength(28);
+ expect(result.current.weeks).toHaveLength(4);
+ expect(result.current.days.every(d => !d.isOutside)).toBe(true);
+ expect(result.current.days.map(d => d.dayNumber)).toEqual(
+ Array.from({length: 28}, (_, i) => i + 1),
+ );
+ expect(result.current.days[0]).toEqual({
+ date: {year: 2026, month: 2, day: 1},
+ iso: '2026-02-01',
+ isOutside: false,
+ dayNumber: 1,
+ });
+ });
+
+ it('pads the fixed 6-row grid with trailing next-month days', () => {
+ // Same February 2026, but the default fixed grid always has 42 cells.
+ const {result} = renderHook(() => useCalendarDays({year: 2026, month: 2}));
+
+ expect(result.current.totalCells).toBe(42);
+ expect(result.current.weeks).toHaveLength(6);
+ // Last in-month day at index 27, then March spills in.
+ expect(result.current.days[27]).toEqual({
+ date: {year: 2026, month: 2, day: 28},
+ iso: '2026-02-28',
+ isOutside: false,
+ dayNumber: 28,
+ });
+ expect(result.current.days[28]).toEqual({
+ date: {year: 2026, month: 3, day: 1},
+ iso: '2026-03-01',
+ isOutside: true,
+ dayNumber: 1,
+ });
+ expect(result.current.days[41]).toEqual({
+ date: {year: 2026, month: 3, day: 14},
+ iso: '2026-03-14',
+ isOutside: true,
+ dayNumber: 14,
+ });
+ });
+
+ it('wraps a negative starting offset by a full week', () => {
+ // February 2026 starts on Sunday (0); weekStartsOn=1 makes the raw offset
+ // 0 - 1 = -1, which must wrap to 6 leading cells (Mon Jan 26 … Sat Jan 31).
+ const {result} = renderHook(() =>
+ useCalendarDays({
+ year: 2026,
+ month: 2,
+ weekStartsOn: 1,
+ hasVariableRowCount: true,
+ }),
+ );
+
+ expect(result.current.days[0]).toEqual({
+ date: {year: 2026, month: 1, day: 26},
+ iso: '2026-01-26',
+ isOutside: true,
+ dayNumber: 26,
+ });
+ expect(result.current.days[5]).toEqual({
+ date: {year: 2026, month: 1, day: 31},
+ iso: '2026-01-31',
+ isOutside: true,
+ dayNumber: 31,
+ });
+ expect(result.current.days[6]).toEqual({
+ date: {year: 2026, month: 2, day: 1},
+ iso: '2026-02-01',
+ isOutside: false,
+ dayNumber: 1,
+ });
+ // 6 leading + 28 days = 34 → ceil(34/7) = 5 rows = 35 cells.
+ expect(result.current.totalCells).toBe(35);
+ expect(result.current.days[34]).toEqual({
+ date: {year: 2026, month: 3, day: 1},
+ iso: '2026-03-01',
+ isOutside: true,
+ dayNumber: 1,
+ });
+ });
+
+ it('leads with previous-year December days for a January month', () => {
+ // January 2026 starts on Thursday → 4 leading cells from December 2025.
+ const {result} = renderHook(() => useCalendarDays({year: 2026, month: 1}));
+
+ expect(result.current.days[0]).toEqual({
+ date: {year: 2025, month: 12, day: 28},
+ iso: '2025-12-28',
+ isOutside: true,
+ dayNumber: 28,
+ });
+ expect(result.current.days[3]).toEqual({
+ date: {year: 2025, month: 12, day: 31},
+ iso: '2025-12-31',
+ isOutside: true,
+ dayNumber: 31,
+ });
+ expect(result.current.days[4]).toEqual({
+ date: {year: 2026, month: 1, day: 1},
+ iso: '2026-01-01',
+ isOutside: false,
+ dayNumber: 1,
+ });
+ // 4 + 31 = 35 in-use cells; the fixed grid trails into February 2026.
+ expect(result.current.days[35]).toEqual({
+ date: {year: 2026, month: 2, day: 1},
+ iso: '2026-02-01',
+ isOutside: true,
+ dayNumber: 1,
+ });
+ });
+
+ it('trails with next-year January days for a December month', () => {
+ // December 2025 starts on Monday → 1 leading cell (Sun Nov 30).
+ const {result} = renderHook(() => useCalendarDays({year: 2025, month: 12}));
+
+ expect(result.current.days[0]).toEqual({
+ date: {year: 2025, month: 11, day: 30},
+ iso: '2025-11-30',
+ isOutside: true,
+ dayNumber: 30,
+ });
+ expect(result.current.days[31]).toEqual({
+ date: {year: 2025, month: 12, day: 31},
+ iso: '2025-12-31',
+ isOutside: false,
+ dayNumber: 31,
+ });
+ expect(result.current.days[32]).toEqual({
+ date: {year: 2026, month: 1, day: 1},
+ iso: '2026-01-01',
+ isOutside: true,
+ dayNumber: 1,
+ });
+ expect(result.current.days[41]).toEqual({
+ date: {year: 2026, month: 1, day: 10},
+ iso: '2026-01-10',
+ isOutside: true,
+ dayNumber: 10,
+ });
+ });
+
+ it('includes February 29 inside a leap-year month', () => {
+ // February 2024 starts on Thursday → 4 leading cells; 4 + 29 = 33 → 5 rows.
+ const {result} = renderHook(() =>
+ useCalendarDays({year: 2024, month: 2, hasVariableRowCount: true}),
+ );
+
+ expect(result.current.totalCells).toBe(35);
+ expect(result.current.days[32]).toEqual({
+ date: {year: 2024, month: 2, day: 29},
+ iso: '2024-02-29',
+ isOutside: false,
+ dayNumber: 29,
+ });
+ expect(result.current.days[33]).toEqual({
+ date: {year: 2024, month: 3, day: 1},
+ iso: '2024-03-01',
+ isOutside: true,
+ dayNumber: 1,
+ });
+ });
+});
+
+// =============================================================================
+// Day names
+// =============================================================================
+
+describe('useCalendarDays — day names', () => {
+ it('defaults day names to Sunday-first', () => {
+ const {result} = renderHook(() => useCalendarDays({year: 2026, month: 6}));
+
+ expect(result.current.dayNames).toEqual([
+ 'Su',
+ 'Mo',
+ 'Tu',
+ 'We',
+ 'Th',
+ 'Fr',
+ 'Sa',
+ ]);
+ });
+
+ it('rotates day names to Monday-first for weekStartsOn=1', () => {
+ const {result} = renderHook(() =>
+ useCalendarDays({year: 2026, month: 6, weekStartsOn: 1}),
+ );
+
+ expect(result.current.dayNames).toEqual([
+ 'Mo',
+ 'Tu',
+ 'We',
+ 'Th',
+ 'Fr',
+ 'Sa',
+ 'Su',
+ ]);
+ });
+
+ it('rotates day names to Saturday-first for weekStartsOn=6', () => {
+ const {result} = renderHook(() =>
+ useCalendarDays({year: 2026, month: 6, weekStartsOn: 6}),
+ );
+
+ expect(result.current.dayNames).toEqual([
+ 'Sa',
+ 'Su',
+ 'Mo',
+ 'Tu',
+ 'We',
+ 'Th',
+ 'Fr',
+ ]);
+ });
+});
+
+// =============================================================================
+// Week grouping
+// =============================================================================
+
+describe('useCalendarDays — week grouping', () => {
+ it('groups the flat days array into rows of seven without gaps or reordering', () => {
+ const {result} = renderHook(() => useCalendarDays({year: 2026, month: 1}));
+
+ expect(result.current.weeks).toHaveLength(6);
+ for (const week of result.current.weeks) {
+ expect(week).toHaveLength(7);
+ }
+ // Same cell objects, same order — weeks is a view over days.
+ expect(result.current.weeks.flat()).toEqual(result.current.days);
+ expect(result.current.weeks[1][0]).toBe(result.current.days[7]);
+ });
+});
diff --git a/packages/core/src/Calendar/hooks/useCalendarNavigation.test.ts b/packages/core/src/Calendar/hooks/useCalendarNavigation.test.ts
new file mode 100644
index 0000000000..9dcc9b6857
--- /dev/null
+++ b/packages/core/src/Calendar/hooks/useCalendarNavigation.test.ts
@@ -0,0 +1,252 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file useCalendarNavigation.test.ts
+ * @input Uses vitest, @testing-library/react
+ * @output Unit tests for useCalendarNavigation hook
+ * @position Testing; validates focus-month init, month navigation, controlled
+ * mode, and pending keyboard focus
+ *
+ * NOTE: Every test passes `initialValue` or `focusDate` so the hook never
+ * falls back to plainDateToday() — CI has no pinned timezone or clock. Month
+ * labels are asserted as English literals: with no InternationalizationProvider
+ * mounted, useLocale() resolves to 'en', so the hook's formatting is
+ * deterministic and independent of the machine locale.
+ */
+
+import {describe, it, expect, vi} from 'vitest';
+import {act, renderHook} from '@testing-library/react';
+import {useCalendarNavigation} from './useCalendarNavigation';
+
+// =============================================================================
+// Initialization
+// =============================================================================
+
+describe('useCalendarNavigation — initialization', () => {
+ it('starts on the first of the initialValue month', () => {
+ const {result} = renderHook(() =>
+ useCalendarNavigation({initialValue: '2026-01-15'}),
+ );
+
+ expect(result.current.baseMonth).toEqual({year: 2026, month: 1, day: 1});
+ expect(result.current.visibleMonths).toEqual([
+ {year: 2026, month: 1, day: 1},
+ ]);
+ expect(result.current.pendingFocus).toBeNull();
+ });
+
+ it('prefers focusDate over initialValue for the starting month', () => {
+ // focusDate without onFocusDateChange is NOT controlled — it only seeds
+ // the internal state, and it wins over initialValue.
+ const {result} = renderHook(() =>
+ useCalendarNavigation({
+ focusDate: '2026-03-15',
+ initialValue: '2026-06-01',
+ }),
+ );
+
+ expect(result.current.baseMonth).toEqual({year: 2026, month: 3, day: 1});
+ });
+
+ it('labels a single visible month with its formatted month and year', () => {
+ const {result} = renderHook(() =>
+ useCalendarNavigation({initialValue: '2026-04-10'}),
+ );
+
+ expect(result.current.monthYearLabel).toBe('April 2026');
+ });
+});
+
+// =============================================================================
+// Month navigation (uncontrolled)
+// =============================================================================
+
+describe('useCalendarNavigation — uncontrolled navigation', () => {
+ it('navigateMonth(1) advances to the next month', () => {
+ const {result} = renderHook(() =>
+ useCalendarNavigation({initialValue: '2026-05-20'}),
+ );
+
+ act(() => {
+ result.current.navigateMonth(1);
+ });
+
+ expect(result.current.baseMonth).toEqual({year: 2026, month: 6, day: 1});
+ expect(result.current.monthYearLabel).toBe('June 2026');
+ });
+
+ it('navigateMonth(-1) from January rolls back into December of the previous year', () => {
+ const {result} = renderHook(() =>
+ useCalendarNavigation({initialValue: '2026-01-15'}),
+ );
+
+ act(() => {
+ result.current.navigateMonth(-1);
+ });
+
+ expect(result.current.baseMonth).toEqual({year: 2025, month: 12, day: 1});
+ });
+
+ it('navigateMonth(1) from December rolls forward into January of the next year', () => {
+ const {result} = renderHook(() =>
+ useCalendarNavigation({initialValue: '2025-12-10'}),
+ );
+
+ act(() => {
+ result.current.navigateMonth(1);
+ });
+
+ expect(result.current.baseMonth).toEqual({year: 2026, month: 1, day: 1});
+ });
+});
+
+// =============================================================================
+// Controlled mode
+// =============================================================================
+
+describe('useCalendarNavigation — controlled mode', () => {
+ it('reports the new month through the callback without moving itself', () => {
+ const onFocusDateChange = vi.fn();
+ const {result} = renderHook(() =>
+ useCalendarNavigation({focusDate: '2026-05-20', onFocusDateChange}),
+ );
+
+ act(() => {
+ result.current.navigateMonth(1);
+ });
+
+ expect(onFocusDateChange).toHaveBeenCalledTimes(1);
+ expect(onFocusDateChange).toHaveBeenCalledWith('2026-06-01');
+ // Controlled: the visible month only changes when the owner re-renders
+ // with a new focusDate.
+ expect(result.current.baseMonth).toEqual({year: 2026, month: 5, day: 1});
+ });
+
+ it('still records pendingFocus for keyboard navigation while controlled', () => {
+ const onFocusDateChange = vi.fn();
+ const {result} = renderHook(() =>
+ useCalendarNavigation({focusDate: '2026-05-20', onFocusDateChange}),
+ );
+
+ act(() => {
+ result.current.navigateMonth(1, '2026-05-31', 1);
+ });
+
+ expect(result.current.pendingFocus).toBe('2026-06-01');
+ expect(onFocusDateChange).toHaveBeenCalledWith('2026-06-01');
+ expect(result.current.baseMonth).toEqual({year: 2026, month: 5, day: 1});
+ });
+});
+
+// =============================================================================
+// Pending focus
+// =============================================================================
+
+describe('useCalendarNavigation — pending focus', () => {
+ it('moves the pending focus by seven days when no offset is given (vertical default)', () => {
+ const {result} = renderHook(() =>
+ useCalendarNavigation({initialValue: '2026-01-15'}),
+ );
+
+ act(() => {
+ result.current.navigateMonth(1, '2026-01-15');
+ });
+
+ expect(result.current.pendingFocus).toBe('2026-01-22');
+ });
+
+ it('moves the pending focus by delta*offset days across a month boundary', () => {
+ const {result} = renderHook(() =>
+ useCalendarNavigation({initialValue: '2026-01-15'}),
+ );
+
+ act(() => {
+ result.current.navigateMonth(1, '2026-01-31', 1);
+ });
+
+ expect(result.current.pendingFocus).toBe('2026-02-01');
+ expect(result.current.baseMonth).toEqual({year: 2026, month: 2, day: 1});
+ });
+
+ it('moves the pending focus backwards for a negative delta', () => {
+ const {result} = renderHook(() =>
+ useCalendarNavigation({initialValue: '2026-03-10'}),
+ );
+
+ act(() => {
+ result.current.navigateMonth(-1, '2026-03-01', 1);
+ });
+
+ expect(result.current.pendingFocus).toBe('2026-02-28');
+ });
+
+ it('carries the pending focus across a year boundary', () => {
+ const {result} = renderHook(() =>
+ useCalendarNavigation({initialValue: '2026-12-15'}),
+ );
+
+ act(() => {
+ result.current.navigateMonth(1, '2026-12-31', 1);
+ });
+
+ expect(result.current.pendingFocus).toBe('2027-01-01');
+ });
+
+ it('leaves pendingFocus null when navigating without a focused date', () => {
+ const {result} = renderHook(() =>
+ useCalendarNavigation({initialValue: '2026-01-15'}),
+ );
+
+ act(() => {
+ result.current.navigateMonth(1);
+ });
+
+ expect(result.current.pendingFocus).toBeNull();
+ });
+
+ it('clearPendingFocus resets a recorded pending focus', () => {
+ const {result} = renderHook(() =>
+ useCalendarNavigation({initialValue: '2026-01-15'}),
+ );
+
+ act(() => {
+ result.current.navigateMonth(1, '2026-01-15', 1);
+ });
+ expect(result.current.pendingFocus).toBe('2026-01-16');
+
+ act(() => {
+ result.current.clearPendingFocus();
+ });
+ expect(result.current.pendingFocus).toBeNull();
+ });
+});
+
+// =============================================================================
+// Multi-month view
+// =============================================================================
+
+describe('useCalendarNavigation — numberOfMonths=2', () => {
+ it('renders two consecutive months and joins the label with an en dash', () => {
+ const {result} = renderHook(() =>
+ useCalendarNavigation({initialValue: '2026-01-15', numberOfMonths: 2}),
+ );
+
+ expect(result.current.visibleMonths).toEqual([
+ {year: 2026, month: 1, day: 1},
+ {year: 2026, month: 2, day: 1},
+ ]);
+ expect(result.current.monthYearLabel).toBe('January 2026 – February 2026');
+ });
+
+ it('spans the year boundary in the two-month view', () => {
+ const {result} = renderHook(() =>
+ useCalendarNavigation({initialValue: '2026-12-15', numberOfMonths: 2}),
+ );
+
+ expect(result.current.visibleMonths).toEqual([
+ {year: 2026, month: 12, day: 1},
+ {year: 2027, month: 1, day: 1},
+ ]);
+ expect(result.current.monthYearLabel).toBe('December 2026 – January 2027');
+ });
+});
diff --git a/packages/core/src/Chat/ChatSendButton.test.tsx b/packages/core/src/Chat/ChatSendButton.test.tsx
new file mode 100644
index 0000000000..ca77e2f65e
--- /dev/null
+++ b/packages/core/src/Chat/ChatSendButton.test.tsx
@@ -0,0 +1,189 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file ChatSendButton.test.tsx
+ * @input Uses vitest, @testing-library/react, the global icon registry
+ * @output Unit tests for ChatSendButton
+ * @position Colocated unit test; covers the send/stop labels and icons, the
+ * disabled rules, click routing, and the ChatComposer context defaults
+ */
+
+import {describe, it, expect, vi, afterEach} from 'vitest';
+import {render, screen, fireEvent} from '@testing-library/react';
+import {ChatSendButton} from './ChatSendButton';
+import {ChatComposer} from './ChatComposer';
+import {Button} from '../Button';
+import {registerIcons, resetIcons} from '../Icon';
+import {TestIcon} from '../__tests__/TestIcon';
+import {declaredValue} from '../__tests__/stylexDeclarations';
+
+describe('ChatSendButton', () => {
+ afterEach(() => {
+ resetIcons();
+ });
+
+ describe('send state', () => {
+ it('names the button "Send" from the en message catalog', () => {
+ render(<ChatSendButton />);
+ expect(screen.getByRole('button')).toHaveAccessibleName('Send');
+ });
+
+ it('is disabled with no composer context and no isDisabled prop', () => {
+ render(<ChatSendButton />);
+ expect(screen.getByRole('button', {name: 'Send'})).toBeDisabled();
+ });
+
+ it('is enabled when isDisabled is explicitly false', () => {
+ render(<ChatSendButton isDisabled={false} onSend={() => {}} />);
+ expect(screen.getByRole('button', {name: 'Send'})).toBeEnabled();
+ });
+
+ it('calls onSend when clicked', () => {
+ const onSend = vi.fn();
+ render(<ChatSendButton isDisabled={false} onSend={onSend} />);
+ fireEvent.click(screen.getByRole('button', {name: 'Send'}));
+ expect(onSend).toHaveBeenCalledTimes(1);
+ });
+
+ it('swallows the click while disabled', () => {
+ // isDisabled already defaults true here (no composer context), so this
+ // pins the click routing through a disabled Button, not the prop.
+ const onSend = vi.fn();
+ render(<ChatSendButton onSend={onSend} />);
+ fireEvent.click(screen.getByRole('button', {name: 'Send'}));
+ expect(onSend).not.toHaveBeenCalled();
+ });
+
+ it('styles the send state as a primary button', () => {
+ const {container} = render(<ChatSendButton />);
+ const send = container.querySelector('button')!;
+ const {container: primaryRef} = render(
+ <Button
+ label="reference"
+ variant="primary"
+ isIconOnly
+ icon={<TestIcon />}
+ />,
+ );
+ const {container: secondaryRef} = render(
+ <Button
+ label="reference"
+ variant="secondary"
+ isIconOnly
+ icon={<TestIcon />}
+ />,
+ );
+ const primary = declaredValue(
+ primaryRef.querySelector('button')!,
+ 'background-color',
+ );
+ expect(primary).not.toBeNull();
+ expect(
+ declaredValue(
+ secondaryRef.querySelector('button')!,
+ 'background-color',
+ ),
+ ).not.toBe(primary);
+ expect(declaredValue(send, 'background-color')).toBe(primary);
+ });
+
+ it('resolves its default icon from the registry arrowUp entry', () => {
+ registerIcons({
+ arrowUp: (
+ <svg data-testid="registry-arrow-up">
+ <path d="M0 0" />
+ </svg>
+ ),
+ });
+ render(<ChatSendButton />);
+ expect(screen.getByTestId('registry-arrow-up')).toBeInTheDocument();
+ });
+
+ it('renders an explicit sendIcon instead of the registry icon', () => {
+ registerIcons({
+ arrowUp: (
+ <svg data-testid="registry-arrow-up">
+ <path d="M0 0" />
+ </svg>
+ ),
+ });
+ render(<ChatSendButton sendIcon={<TestIcon data-testid="my-send" />} />);
+ expect(screen.getByTestId('my-send')).toBeInTheDocument();
+ expect(screen.queryByTestId('registry-arrow-up')).not.toBeInTheDocument();
+ });
+ });
+
+ describe('stop state', () => {
+ it('names the button "Stop" from the en message catalog', () => {
+ render(<ChatSendButton isStopShown />);
+ expect(screen.getByRole('button')).toHaveAccessibleName('Stop');
+ });
+
+ it('stays enabled even when isDisabled is set', () => {
+ render(<ChatSendButton isStopShown isDisabled onStop={() => {}} />);
+ expect(screen.getByRole('button', {name: 'Stop'})).toBeEnabled();
+ });
+
+ it('routes the click to onStop and never to onSend', () => {
+ const onSend = vi.fn();
+ const onStop = vi.fn();
+ render(<ChatSendButton isStopShown onSend={onSend} onStop={onStop} />);
+ fireEvent.click(screen.getByRole('button', {name: 'Stop'}));
+ expect(onStop).toHaveBeenCalledTimes(1);
+ expect(onSend).not.toHaveBeenCalled();
+ });
+
+ it('resolves its default icon from the registry stop entry', () => {
+ registerIcons({
+ stop: (
+ <svg data-testid="registry-stop">
+ <rect />
+ </svg>
+ ),
+ });
+ render(<ChatSendButton isStopShown />);
+ expect(screen.getByTestId('registry-stop')).toBeInTheDocument();
+ });
+
+ it('renders an explicit stopIcon instead of the registry icon', () => {
+ registerIcons({
+ stop: (
+ <svg data-testid="registry-stop">
+ <rect />
+ </svg>
+ ),
+ });
+ render(
+ <ChatSendButton
+ isStopShown
+ stopIcon={<TestIcon data-testid="my-stop" />}
+ />,
+ );
+ expect(screen.getByTestId('my-stop')).toBeInTheDocument();
+ expect(screen.queryByTestId('registry-stop')).not.toBeInTheDocument();
+ });
+ });
+
+ describe('inside ChatComposer', () => {
+ it('takes canSend and onSubmit from the composer context', () => {
+ const onSubmit = vi.fn();
+ const {rerender} = render(
+ <ChatComposer onSubmit={onSubmit} value="" input={<div />} />,
+ );
+ // Empty composer — nothing to send.
+ expect(screen.getByRole('button', {name: 'Send'})).toBeDisabled();
+
+ rerender(
+ <ChatComposer onSubmit={onSubmit} value="hello" input={<div />} />,
+ );
+ const send = screen.getByRole('button', {name: 'Send'});
+ expect(send).toBeEnabled();
+
+ fireEvent.click(send);
+ // Only that the click reaches the composer's submit path is this
+ // button's behavior. The submitted value comes from the composer's own
+ // state, not from here, so asserting it would pin ChatComposer instead.
+ expect(onSubmit).toHaveBeenCalledTimes(1);
+ });
+ });
+});
diff --git a/packages/core/src/Chat/useChatPasteAsToken.test.ts b/packages/core/src/Chat/useChatPasteAsToken.test.ts
new file mode 100644
index 0000000000..ae50d92a85
--- /dev/null
+++ b/packages/core/src/Chat/useChatPasteAsToken.test.ts
@@ -0,0 +1,191 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file useChatPasteAsToken.test.ts
+ * @input Uses vitest, @testing-library/react, useChatPasteAsToken hook
+ * @output Unit tests for the paste-as-token threshold and token factory
+ * @position Testing; validates useChatPasteAsToken.ts implementation
+ *
+ * SYNC: When useChatPasteAsToken.ts changes, update tests to match new behavior
+ */
+
+import {describe, it, expect, vi} from 'vitest';
+import {renderHook} from '@testing-library/react';
+import {useChatPasteAsToken} from './useChatPasteAsToken';
+import type {
+ ChatComposerInputHandle,
+ ChatComposerToken,
+} from './ChatComposerInput';
+import type {ClipboardEvent} from 'react';
+
+// The hook never reads the event (it only inspects the already-extracted
+// text), so a bare object stands in for the React synthetic event.
+const pasteEvent = {} as ClipboardEvent<HTMLDivElement>;
+
+function makeInputRef() {
+ const insertToken = vi.fn<(token: ChatComposerToken) => string | undefined>();
+ const ref: React.RefObject<ChatComposerInputHandle | null> = {
+ current: {
+ insertToken,
+ expandToken: vi.fn(),
+ insertText: vi.fn(),
+ focus: vi.fn(),
+ getValue: vi.fn(() => ''),
+ },
+ };
+ return {ref, insertToken};
+}
+
+/** A single-line string of exactly `n` characters. */
+const chars = (n: number) => 'a'.repeat(n);
+
+describe('useChatPasteAsToken — threshold', () => {
+ it('passes the paste through when the text is shorter than the threshold', () => {
+ const {ref, insertToken} = makeInputRef();
+ const {result} = renderHook(() => useChatPasteAsToken({inputRef: ref}));
+
+ expect(result.current.onPaste(pasteEvent, chars(199))).toBe(false);
+ expect(insertToken).not.toHaveBeenCalled();
+ });
+
+ it('passes the paste through at exactly the default 200-character threshold', () => {
+ const {ref, insertToken} = makeInputRef();
+ const {result} = renderHook(() => useChatPasteAsToken({inputRef: ref}));
+
+ expect(result.current.onPaste(pasteEvent, chars(200))).toBe(false);
+ expect(insertToken).not.toHaveBeenCalled();
+ });
+
+ it('converts the paste to a token one character past the threshold', () => {
+ const {ref, insertToken} = makeInputRef();
+ const {result} = renderHook(() => useChatPasteAsToken({inputRef: ref}));
+
+ expect(result.current.onPaste(pasteEvent, chars(201))).toBe(true);
+ expect(insertToken).toHaveBeenCalledTimes(1);
+ });
+
+ it('honors a custom threshold on both sides of the boundary', () => {
+ const {ref, insertToken} = makeInputRef();
+ const {result} = renderHook(() =>
+ useChatPasteAsToken({inputRef: ref, threshold: 5}),
+ );
+
+ expect(result.current.onPaste(pasteEvent, chars(5))).toBe(false);
+ expect(insertToken).not.toHaveBeenCalled();
+
+ expect(result.current.onPaste(pasteEvent, chars(6))).toBe(true);
+ expect(insertToken).toHaveBeenCalledTimes(1);
+ });
+
+ it('tokenizes any non-empty paste when the threshold is zero', () => {
+ const {ref, insertToken} = makeInputRef();
+ const {result} = renderHook(() =>
+ useChatPasteAsToken({inputRef: ref, threshold: 0}),
+ );
+
+ expect(result.current.onPaste(pasteEvent, '')).toBe(false);
+ expect(insertToken).not.toHaveBeenCalled();
+
+ expect(result.current.onPaste(pasteEvent, 'a')).toBe(true);
+ expect(insertToken).toHaveBeenCalledTimes(1);
+ });
+});
+
+describe('useChatPasteAsToken — default token', () => {
+ it('labels a single-line paste with the character count only', () => {
+ const {ref, insertToken} = makeInputRef();
+ const {result} = renderHook(() => useChatPasteAsToken({inputRef: ref}));
+
+ result.current.onPaste(pasteEvent, chars(240));
+
+ expect(insertToken).toHaveBeenCalledWith({
+ value: chars(240),
+ label: '240 chars',
+ variant: 'neutral',
+ });
+ });
+
+ it('labels a multi-line paste with both the line and character counts', () => {
+ const {ref, insertToken} = makeInputRef();
+ const {result} = renderHook(() => useChatPasteAsToken({inputRef: ref}));
+
+ // Three lines, 302 characters (3 x 100 'a' + 2 newlines).
+ const text = [chars(100), chars(100), chars(100)].join('\n');
+ expect(text.length).toBe(302);
+
+ result.current.onPaste(pasteEvent, text);
+
+ expect(insertToken).toHaveBeenCalledWith({
+ value: text,
+ label: '3 lines, 302 chars',
+ variant: 'neutral',
+ });
+ });
+
+ it('counts a trailing newline as an extra line', () => {
+ const {ref, insertToken} = makeInputRef();
+ const {result} = renderHook(() => useChatPasteAsToken({inputRef: ref}));
+
+ const text = `${chars(300)}\n`;
+ result.current.onPaste(pasteEvent, text);
+
+ expect(insertToken).toHaveBeenCalledWith(
+ expect.objectContaining({label: '2 lines, 301 chars'}),
+ );
+ });
+
+ it('carries the full pasted text as the token value', () => {
+ const {ref, insertToken} = makeInputRef();
+ const {result} = renderHook(() => useChatPasteAsToken({inputRef: ref}));
+
+ const text = `SECRET-${chars(300)}`;
+ result.current.onPaste(pasteEvent, text);
+
+ expect(insertToken.mock.calls[0][0].value).toBe(text);
+ });
+});
+
+describe('useChatPasteAsToken — custom token factory', () => {
+ it('inserts the token returned by toToken instead of the default', () => {
+ const {ref, insertToken} = makeInputRef();
+ const toToken = vi.fn((text: string) => ({
+ value: text.toUpperCase(),
+ label: 'Pasted snippet',
+ variant: 'success' as const,
+ }));
+ const {result} = renderHook(() =>
+ useChatPasteAsToken({inputRef: ref, toToken}),
+ );
+
+ expect(result.current.onPaste(pasteEvent, chars(201))).toBe(true);
+ expect(toToken).toHaveBeenCalledWith(chars(201));
+ expect(insertToken).toHaveBeenCalledWith({
+ value: chars(201).toUpperCase(),
+ label: 'Pasted snippet',
+ variant: 'success',
+ });
+ });
+
+ it('never calls toToken for a paste under the threshold', () => {
+ const {ref} = makeInputRef();
+ const toToken = vi.fn(() => ({value: 'x', label: 'x'}));
+ const {result} = renderHook(() =>
+ useChatPasteAsToken({inputRef: ref, toToken}),
+ );
+
+ result.current.onPaste(pasteEvent, chars(10));
+
+ expect(toToken).not.toHaveBeenCalled();
+ });
+});
+
+describe('useChatPasteAsToken — unattached input', () => {
+ it('does not throw when the input ref has not been attached yet', () => {
+ const ref: React.RefObject<ChatComposerInputHandle | null> = {
+ current: null,
+ };
+ const {result} = renderHook(() => useChatPasteAsToken({inputRef: ref}));
+
+ expect(() => result.current.onPaste(pasteEvent, chars(201))).not.toThrow();
+ });
+});
diff --git a/packages/core/src/Collapsible/useCollapsible.test.tsx b/packages/core/src/Collapsible/useCollapsible.test.tsx
new file mode 100644
index 0000000000..edaeba3778
--- /dev/null
+++ b/packages/core/src/Collapsible/useCollapsible.test.tsx
@@ -0,0 +1,236 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file useCollapsible.test.tsx
+ * @input Uses vitest, @testing-library/react, CollapsibleGroupContext
+ * @output Unit tests for useCollapsible hook
+ * @position Testing; validates config parsing and the three-mode state
+ * machine (group-controlled / controlled / uncontrolled)
+ */
+
+import {describe, it, expect, vi} from 'vitest';
+import type {ReactNode} from 'react';
+import {act, renderHook} from '@testing-library/react';
+import {useCollapsible} from './useCollapsible';
+import {
+ CollapsibleGroupContext,
+ type CollapsibleGroupContextValue,
+} from './CollapsibleGroupContext';
+
+// =============================================================================
+// Helpers
+// =============================================================================
+
+function withGroup(group: CollapsibleGroupContextValue) {
+ return function GroupWrapper({children}: {children: ReactNode}) {
+ return (
+ <CollapsibleGroupContext value={group}>
+ {children}
+ </CollapsibleGroupContext>
+ );
+ };
+}
+
+// =============================================================================
+// Config parsing
+// =============================================================================
+
+describe('useCollapsible — config parsing', () => {
+ it('treats isCollapsible=true as an enabled config that starts open', () => {
+ const {result} = renderHook(() => useCollapsible({isCollapsible: true}));
+
+ expect(result.current.isEnabled).toBe(true);
+ expect(result.current.isOpen).toBe(true);
+ });
+
+ it('is disabled when isCollapsible is undefined', () => {
+ const {result} = renderHook(() => useCollapsible({}));
+
+ expect(result.current.isEnabled).toBe(false);
+ });
+
+ it('is disabled when isCollapsible is false', () => {
+ const {result} = renderHook(() => useCollapsible({isCollapsible: false}));
+
+ expect(result.current.isEnabled).toBe(false);
+ });
+
+ it('treats an object config as enabled', () => {
+ const {result} = renderHook(() => useCollapsible({isCollapsible: {}}));
+
+ expect(result.current.isEnabled).toBe(true);
+ expect(result.current.isOpen).toBe(true);
+ });
+
+ it('starts closed when defaultIsOpen is false', () => {
+ const {result} = renderHook(() =>
+ useCollapsible({isCollapsible: {defaultIsOpen: false}}),
+ );
+
+ expect(result.current.isEnabled).toBe(true);
+ expect(result.current.isOpen).toBe(false);
+ });
+});
+
+// =============================================================================
+// Uncontrolled mode
+// =============================================================================
+
+describe('useCollapsible — uncontrolled mode', () => {
+ it('toggle flips the state open → closed → open', () => {
+ const {result} = renderHook(() => useCollapsible({isCollapsible: true}));
+
+ act(() => {
+ result.current.toggle();
+ });
+ expect(result.current.isOpen).toBe(false);
+
+ act(() => {
+ result.current.toggle();
+ });
+ expect(result.current.isOpen).toBe(true);
+ });
+
+ it('toggle updates internal state AND notifies onOpenChange', () => {
+ // onOpenChange without isOpen is a notification callback, not a signal
+ // that the component is controlled.
+ const onOpenChange = vi.fn();
+ const {result} = renderHook(() =>
+ useCollapsible({isCollapsible: {onOpenChange}}),
+ );
+
+ act(() => {
+ result.current.toggle();
+ });
+ expect(result.current.isOpen).toBe(false);
+ expect(onOpenChange).toHaveBeenNthCalledWith(1, false);
+
+ act(() => {
+ result.current.toggle();
+ });
+ expect(result.current.isOpen).toBe(true);
+ expect(onOpenChange).toHaveBeenNthCalledWith(2, true);
+ });
+});
+
+// =============================================================================
+// Controlled mode
+// =============================================================================
+
+describe('useCollapsible — controlled mode', () => {
+ it('renders the isOpen prop and only notifies on toggle, never self-toggles', () => {
+ const onOpenChange = vi.fn();
+ const {result} = renderHook(() =>
+ useCollapsible({isCollapsible: {isOpen: true, onOpenChange}}),
+ );
+
+ expect(result.current.isOpen).toBe(true);
+
+ act(() => {
+ result.current.toggle();
+ });
+
+ expect(onOpenChange).toHaveBeenCalledTimes(1);
+ expect(onOpenChange).toHaveBeenCalledWith(false);
+ // The parent owns the state — nothing changed internally.
+ expect(result.current.isOpen).toBe(true);
+ });
+
+ it('reports the inverse of a closed controlled state', () => {
+ const onOpenChange = vi.fn();
+ const {result} = renderHook(() =>
+ useCollapsible({isCollapsible: {isOpen: false, onOpenChange}}),
+ );
+
+ expect(result.current.isOpen).toBe(false);
+
+ act(() => {
+ result.current.toggle();
+ });
+
+ expect(onOpenChange).toHaveBeenCalledWith(true);
+ expect(result.current.isOpen).toBe(false);
+ });
+
+ it('tolerates a controlled config without onOpenChange', () => {
+ const {result} = renderHook(() =>
+ useCollapsible({isCollapsible: {isOpen: true}}),
+ );
+
+ act(() => {
+ result.current.toggle(); // must not throw
+ });
+
+ expect(result.current.isOpen).toBe(true);
+ });
+});
+
+// =============================================================================
+// Group mode
+// =============================================================================
+
+describe('useCollapsible — group mode', () => {
+ it('reads isOpen from the group for its own value', () => {
+ const group: CollapsibleGroupContextValue = {
+ isOpen: vi.fn((value: string) => value === 'a'),
+ toggle: vi.fn(),
+ };
+
+ const {result: itemA} = renderHook(
+ () => useCollapsible({isCollapsible: true, value: 'a'}),
+ {wrapper: withGroup(group)},
+ );
+ const {result: itemB} = renderHook(
+ () => useCollapsible({isCollapsible: true, value: 'b'}),
+ {wrapper: withGroup(group)},
+ );
+
+ expect(itemA.current.isOpen).toBe(true);
+ expect(itemB.current.isOpen).toBe(false);
+ expect(group.isOpen).toHaveBeenCalledWith('a');
+ expect(group.isOpen).toHaveBeenCalledWith('b');
+ });
+
+ it('toggle defers to the group and skips local state and onOpenChange', () => {
+ const onOpenChange = vi.fn();
+ const group: CollapsibleGroupContextValue = {
+ isOpen: vi.fn(() => true),
+ toggle: vi.fn(),
+ };
+ const {result} = renderHook(
+ () => useCollapsible({isCollapsible: {onOpenChange}, value: 'a'}),
+ {wrapper: withGroup(group)},
+ );
+
+ act(() => {
+ result.current.toggle();
+ });
+
+ expect(group.toggle).toHaveBeenCalledTimes(1);
+ expect(group.toggle).toHaveBeenCalledWith('a');
+ // Group owns the state: the config callback is not invoked and the open
+ // state still comes from the group.
+ expect(onOpenChange).not.toHaveBeenCalled();
+ expect(result.current.isOpen).toBe(true);
+ });
+
+ it('falls back to standalone state inside a group when no value is given', () => {
+ const group: CollapsibleGroupContextValue = {
+ isOpen: vi.fn(() => false),
+ toggle: vi.fn(),
+ };
+ const {result} = renderHook(() => useCollapsible({isCollapsible: true}), {
+ wrapper: withGroup(group),
+ });
+
+ // Standalone default: open.
+ expect(result.current.isOpen).toBe(true);
+
+ act(() => {
+ result.current.toggle();
+ });
+
+ expect(result.current.isOpen).toBe(false);
+ expect(group.toggle).not.toHaveBeenCalled();
+ });
+});
diff --git a/packages/core/src/CommandPalette/CommandPaletteEmpty.test.tsx b/packages/core/src/CommandPalette/CommandPaletteEmpty.test.tsx
new file mode 100644
index 0000000000..0effd38a8b
--- /dev/null
+++ b/packages/core/src/CommandPalette/CommandPaletteEmpty.test.tsx
@@ -0,0 +1,101 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file CommandPaletteEmpty.test.tsx
+ * @input Uses vitest, @testing-library/react
+ * @output Unit tests for CommandPaletteEmpty
+ * @position Colocated unit test; covers children rendering, the stable theme
+ * class surface, and className/style/ref/prop forwarding through mergeProps
+ */
+
+import {describe, it, expect} from 'vitest';
+import {createRef, type ReactElement} from 'react';
+import {render, screen} from '@testing-library/react';
+import * as stylex from '@stylexjs/stylex';
+import {CommandPaletteEmpty} from './CommandPaletteEmpty';
+import {declaredValue} from '../__tests__/stylexDeclarations';
+
+const testStyles = stylex.create({
+ wide: {width: '999px'},
+});
+
+/** The component renders exactly one element, so the root is the first child. */
+function renderRoot(ui: ReactElement): HTMLElement {
+ const {container} = render(ui);
+ return container.firstElementChild as HTMLElement;
+}
+
+describe('CommandPaletteEmpty', () => {
+ it('renders its children as the element content', () => {
+ const root = renderRoot(
+ <CommandPaletteEmpty>No results found</CommandPaletteEmpty>,
+ );
+ expect(root.tagName).toBe('DIV');
+ expect(root.textContent).toBe('No results found');
+ });
+
+ it('renders element children, not just text', () => {
+ render(
+ <CommandPaletteEmpty>
+ <span data-testid="empty-illustration" />
+ Start typing to search
+ </CommandPaletteEmpty>,
+ );
+ expect(screen.getByTestId('empty-illustration')).toBeInTheDocument();
+ expect(screen.getByText('Start typing to search')).toBeInTheDocument();
+ });
+
+ it('carries the stable astryx class for theme targeting', () => {
+ const root = renderRoot(<CommandPaletteEmpty>Empty</CommandPaletteEmpty>);
+ expect(root.className.split(' ')).toContain('astryx-command-palette-empty');
+ });
+
+ it('appends a consumer className after the generated classes', () => {
+ const base = renderRoot(
+ <CommandPaletteEmpty>Empty</CommandPaletteEmpty>,
+ ).className.split(' ');
+ const withCustom = renderRoot(
+ <CommandPaletteEmpty className="my-empty">Empty</CommandPaletteEmpty>,
+ ).className.split(' ');
+ // Every generated class survives and the consumer class is added last.
+ expect(withCustom).toEqual([...base, 'my-empty']);
+ });
+
+ it('merges an xstyle into the element styles', () => {
+ const root = renderRoot(
+ <CommandPaletteEmpty xstyle={testStyles.wide}>Empty</CommandPaletteEmpty>,
+ );
+ expect(declaredValue(root, 'width')).toBe('999px');
+ });
+
+ it('applies a consumer style to the element', () => {
+ const root = renderRoot(
+ <CommandPaletteEmpty style={{marginBlockStart: '8px'}}>
+ Empty
+ </CommandPaletteEmpty>,
+ );
+ expect(root).toHaveStyle({marginBlockStart: '8px'});
+ });
+
+ it('forwards ref to the rendered element', () => {
+ const ref = createRef<HTMLDivElement>();
+ const root = renderRoot(
+ <CommandPaletteEmpty ref={ref}>Empty</CommandPaletteEmpty>,
+ );
+ expect(ref.current).toBe(root);
+ });
+
+ it('forwards arbitrary DOM props (id, data-*, role) to the element', () => {
+ const root = renderRoot(
+ <CommandPaletteEmpty
+ id="palette-empty"
+ data-kind="bootstrap"
+ role="status">
+ Empty
+ </CommandPaletteEmpty>,
+ );
+ expect(root.id).toBe('palette-empty');
+ expect(root).toHaveAttribute('data-kind', 'bootstrap');
+ expect(screen.getByRole('status')).toBe(root);
+ });
+});
diff --git a/packages/core/src/Field/InputClearButton.test.tsx b/packages/core/src/Field/InputClearButton.test.tsx
index 37469d9f2f..0f95dcca77 100644
--- a/packages/core/src/Field/InputClearButton.test.tsx
+++ b/packages/core/src/Field/InputClearButton.test.tsx
@@ -2,23 +2,28 @@
/**
* @file InputClearButton.test.tsx
- * @input Uses node:fs, node:path, vitest, @testing-library/react, InputClearButton, Icon,
- * theme
+ * @input Uses node:fs, node:path, vitest, @testing-library/react, @stylexjs/stylex,
+ * InputClearButton, Icon and the global icon registry, theme, and the shared
+ * declaredValue StyleX read-back helper
* @output Unit tests for the shared clear-button primitive
* @position Testing; validates InputClearButton.tsx — the single home for the
- * clearable input family's clear (✕) affordance and its theme target.
+ * clearable input family's clear (✕) affordance and its theme target. Covers
+ * the accessible name, the click callback, the decorative registry glyph,
+ * both theme targets, the touch hit area, and xstyle forwarding.
*
* SYNC: When InputClearButton.tsx changes, update tests to match new behavior.
*/
import {readFileSync} from 'node:fs';
import path from 'node:path';
-import {describe, it, expect, vi} from 'vitest';
+import {describe, it, expect, vi, afterEach} from 'vitest';
import {render, screen, fireEvent} from '@testing-library/react';
+import * as stylex from '@stylexjs/stylex';
import {InputClearButton, type InputClearButtonProps} from './InputClearButton';
-import {Icon} from '../Icon';
+import {Icon, registerIcons, resetIcons} from '../Icon';
import {defineTheme} from '../theme/defineTheme';
import {generateThemeCSS} from '../theme/generateThemeRules';
+import {declaredValue} from '../__tests__/stylexDeclarations';
function generateThemeTestCSS(theme: Parameters<typeof generateThemeCSS>[0]) {
const {prose, component} = generateThemeCSS(theme);
@@ -67,6 +72,10 @@ const getGlyph = (): HTMLElement => {
return icon as HTMLElement;
};
+const testStyles = stylex.create({
+ wide: {width: '999px'},
+});
+
describe('InputClearButton public props', () => {
it('keep popup invoker handlers internal', () => {
const hasPointerDown: 'onPointerDown' extends keyof InputClearButtonProps
@@ -88,12 +97,19 @@ describe('InputClearButton', () => {
expect(button.tagName).toBe('BUTTON');
});
+ it('renders no visible text so the button stays icon-only', () => {
+ // `label` is the accessible name only: Button's isIconOnly drops the
+ // visible label span, so the affordance keeps its square glyph footprint.
+ render(<InputClearButton label="Clear" onClick={() => {}} />);
+ expect(screen.getByRole('button', {name: 'Clear'}).textContent).toBe('');
+ });
+
it('fires onClick with the native event when pressed', () => {
const onClick = vi.fn();
render(<InputClearButton label="Clear" onClick={onClick} />);
fireEvent.click(screen.getByRole('button', {name: 'Clear'}));
expect(onClick).toHaveBeenCalledTimes(1);
- expect(onClick.mock.calls[0][0]).toBeInstanceOf(Object);
+ expect(onClick.mock.calls[0][0]).toMatchObject({type: 'click'});
});
it('renders the astryx-input-clear-icon target on the glyph', () => {
@@ -127,6 +143,14 @@ describe('InputClearButton', () => {
expect(styleClasses(glyph)).toEqual(styleClasses(refIcon));
});
+ it('hides the glyph from assistive tech so the label is the whole name', () => {
+ // The Icon carries no label of its own, so it stays decorative and never
+ // duplicates or dilutes the button's announcement.
+ render(<InputClearButton label="Clear" onClick={() => {}} />);
+ expect(getGlyph()).toHaveAttribute('aria-hidden', 'true');
+ expect(screen.getByRole('button')).toHaveAccessibleName('Clear');
+ });
+
it('merges an extra iconClassName beside the canonical target', () => {
// Consumers that shipped a component-specific target before the family
// converged pass it through here to keep emitting it for a deprecation
@@ -171,6 +195,24 @@ describe('InputClearButton', () => {
expect(button).toHaveClass('astryx-input-clear-button');
});
+ it('keeps its own 20px height when no xstyle is given', () => {
+ // The button pins a 20px box of its own (tighter than Button's sm
+ // default); the coarse-pointer overlay below grows the hit area from it.
+ render(<InputClearButton label="Clear" onClick={() => {}} />);
+ expect(declaredValue(screen.getByRole('button'), 'height')).toBe('20px');
+ });
+
+ it('applies the caller xstyle to the button', () => {
+ render(
+ <InputClearButton
+ label="Clear"
+ onClick={() => {}}
+ xstyle={testStyles.wide}
+ />,
+ );
+ expect(declaredValue(screen.getByRole('button'), 'width')).toBe('999px');
+ });
+
it('grows the hit area to 24px on a coarse pointer only (WCAG 2.5.8 AA)', () => {
// The visual glyph stays 20px; an ::after overlay expands only the
// tappable region, and only under a coarse pointer. Asserted against the
@@ -261,3 +303,23 @@ describe('InputClearButton', () => {
expect(css).toContain('background-image: none');
});
});
+
+describe('InputClearButton glyph source', () => {
+ afterEach(() => {
+ resetIcons();
+ });
+
+ it('renders the close glyph from the global icon registry', () => {
+ // The glyph is resolved by name, so a consumer that swaps the icon set via
+ // registerIcons() gets its own close glyph in every clearable input.
+ registerIcons({
+ close: (
+ <svg data-testid="custom-close">
+ <path d="M0 0" />
+ </svg>
+ ),
+ });
+ render(<InputClearButton label="Clear" onClick={() => {}} />);
+ expect(getGlyph()).toContainElement(screen.getByTestId('custom-close'));
+ });
+});
diff --git a/packages/core/src/Lightbox/useLightbox.test.tsx b/packages/core/src/Lightbox/useLightbox.test.tsx
new file mode 100644
index 0000000000..f1ed69854d
--- /dev/null
+++ b/packages/core/src/Lightbox/useLightbox.test.tsx
@@ -0,0 +1,263 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file useLightbox.test.tsx
+ * @input Uses vitest, @testing-library/react, useLightbox hook
+ * @output Unit tests for lightbox open/close state and trigger props
+ * @position Testing; validates useLightbox.tsx implementation
+ *
+ * SYNC: When useLightbox.tsx changes, update tests to match new behavior
+ */
+
+import {describe, it, expect, vi, beforeEach, afterEach} from 'vitest';
+import {
+ render,
+ screen,
+ fireEvent,
+ renderHook,
+ act,
+} from '@testing-library/react';
+import {useLightbox} from './useLightbox';
+import {__resetLiveRegionsForTest} from '../hooks/useAnnounce';
+
+// jsdom doesn't implement dialog.showModal/close.
+beforeEach(() => {
+ HTMLDialogElement.prototype.showModal = vi.fn(function (
+ this: HTMLDialogElement,
+ ) {
+ this.setAttribute('open', '');
+ });
+ HTMLDialogElement.prototype.close = vi.fn(function (this: HTMLDialogElement) {
+ this.removeAttribute('open');
+ });
+});
+
+// Lightbox announces gallery navigation through the singleton live regions
+// useAnnounce mounts on <body>; reset them so nothing leaks between tests.
+afterEach(() => {
+ __resetLiveRegionsForTest();
+});
+
+// Module scope so the reference stays stable across rerenders.
+const photos = [
+ {src: '/p1.jpg', alt: 'Photo 1'},
+ {src: '/p2.jpg', alt: 'Photo 2'},
+ {src: '/p3.jpg', alt: 'Photo 3'},
+ {src: '/p4.jpg', alt: 'Photo 4'},
+];
+
+/** Renders both trigger flavors plus the lightbox element itself. */
+function Gallery() {
+ const lightbox = useLightbox({media: photos});
+
+ return (
+ <div>
+ <span data-testid="status">{lightbox.isOpen ? 'open' : 'closed'}</span>
+ <span data-testid="index">{lightbox.index}</span>
+ <span data-testid="shared" {...lightbox.triggerProps}>
+ Open gallery
+ </span>
+ {photos.map((photo, i) => (
+ <img
+ key={photo.src}
+ src={photo.src}
+ alt={`thumb ${i}`}
+ data-testid={`thumb-${i}`}
+ {...lightbox.getTriggerProps(i)}
+ />
+ ))}
+ {lightbox.element}
+ </div>
+ );
+}
+
+describe('useLightbox — state', () => {
+ it('starts closed at the first item', () => {
+ const {result} = renderHook(() => useLightbox({media: photos}));
+ expect(result.current.isOpen).toBe(false);
+ expect(result.current.index).toBe(0);
+ });
+
+ it('opens at the first item when open() is called without an index', () => {
+ const {result} = renderHook(() => useLightbox({media: photos}));
+
+ act(() => result.current.open(2));
+ act(() => result.current.close());
+ // A bare open() resets to the start rather than reusing the last index.
+ act(() => result.current.open());
+
+ expect(result.current.isOpen).toBe(true);
+ expect(result.current.index).toBe(0);
+ });
+
+ it('opens at the requested index', () => {
+ const {result} = renderHook(() => useLightbox({media: photos}));
+
+ act(() => result.current.open(2));
+
+ expect(result.current.isOpen).toBe(true);
+ expect(result.current.index).toBe(2);
+ });
+
+ it('close() closes without rewinding the index', () => {
+ const {result} = renderHook(() => useLightbox({media: photos}));
+
+ act(() => result.current.open(3));
+ act(() => result.current.close());
+
+ expect(result.current.isOpen).toBe(false);
+ expect(result.current.index).toBe(3);
+ });
+
+ // The `if (!nextOpen)` guard in the hook's onOpenChange is deliberately not
+ // covered: Lightbox only ever reports `false`, so the ignored-`true` path is
+ // unreachable through the public surface. Reaching into the element's props
+ // to force it would assert a value that is already settled, and it can only
+ // be exercised for real once something emits `true`.
+});
+
+describe('useLightbox — trigger props', () => {
+ it('gives the trigger button semantics', () => {
+ render(<Gallery />);
+ const trigger = screen.getByTestId('shared');
+ expect(trigger).toHaveAttribute('role', 'button');
+ expect(trigger).toHaveAttribute('tabindex', '0');
+ expect(trigger).toHaveAttribute('aria-haspopup', 'dialog');
+ });
+
+ it('gives every indexed trigger the same button semantics', () => {
+ render(<Gallery />);
+ const trigger = screen.getByTestId('thumb-2');
+ expect(trigger).toHaveAttribute('role', 'button');
+ expect(trigger).toHaveAttribute('tabindex', '0');
+ expect(trigger).toHaveAttribute('aria-haspopup', 'dialog');
+ });
+
+ it('opens at the first item when the shared trigger is clicked', () => {
+ render(<Gallery />);
+ fireEvent.click(screen.getByTestId('shared'));
+ expect(screen.getByTestId('status').textContent).toBe('open');
+ expect(screen.getByTestId('index').textContent).toBe('0');
+ });
+
+ it('opens on Enter and swallows the key press', () => {
+ render(<Gallery />);
+ const notDefaultPrevented = fireEvent.keyDown(
+ screen.getByTestId('shared'),
+ {
+ key: 'Enter',
+ },
+ );
+ expect(notDefaultPrevented).toBe(false);
+ expect(screen.getByTestId('status').textContent).toBe('open');
+ });
+
+ it('opens on Space and swallows the key press', () => {
+ render(<Gallery />);
+ const notDefaultPrevented = fireEvent.keyDown(
+ screen.getByTestId('shared'),
+ {
+ key: ' ',
+ },
+ );
+ expect(notDefaultPrevented).toBe(false);
+ expect(screen.getByTestId('status').textContent).toBe('open');
+ });
+
+ it('leaves other keys alone', () => {
+ render(<Gallery />);
+ for (const key of ['a', 'Tab', 'ArrowRight', 'Escape']) {
+ const notDefaultPrevented = fireEvent.keyDown(
+ screen.getByTestId('shared'),
+ {key},
+ );
+ expect(notDefaultPrevented).toBe(true);
+ expect(screen.getByTestId('status').textContent).toBe('closed');
+ }
+ });
+
+ it('opens at the trigger index when an indexed trigger is clicked', () => {
+ render(<Gallery />);
+ fireEvent.click(screen.getByTestId('thumb-2'));
+ expect(screen.getByTestId('status').textContent).toBe('open');
+ expect(screen.getByTestId('index').textContent).toBe('2');
+ });
+
+ it('opens at the trigger index on Enter and swallows the key press', () => {
+ render(<Gallery />);
+ const notDefaultPrevented = fireEvent.keyDown(
+ screen.getByTestId('thumb-3'),
+ {key: 'Enter'},
+ );
+ expect(notDefaultPrevented).toBe(false);
+ expect(screen.getByTestId('index').textContent).toBe('3');
+ });
+
+ it('opens at the trigger index on Space and swallows the key press', () => {
+ render(<Gallery />);
+ const notDefaultPrevented = fireEvent.keyDown(
+ screen.getByTestId('thumb-1'),
+ {key: ' '},
+ );
+ expect(notDefaultPrevented).toBe(false);
+ expect(screen.getByTestId('index').textContent).toBe('1');
+ });
+
+ it('leaves other keys alone on an indexed trigger', () => {
+ render(<Gallery />);
+ const notDefaultPrevented = fireEvent.keyDown(
+ screen.getByTestId('thumb-1'),
+ {key: 'a'},
+ );
+ expect(notDefaultPrevented).toBe(true);
+ expect(screen.getByTestId('status').textContent).toBe('closed');
+ });
+});
+
+describe('useLightbox — element wiring', () => {
+ it('keeps the lightbox closed until a trigger fires', () => {
+ render(<Gallery />);
+ expect(document.querySelector('dialog')).not.toHaveAttribute('open');
+ });
+
+ it('shows the media for the index the trigger opened', () => {
+ render(<Gallery />);
+ fireEvent.click(screen.getByTestId('thumb-2'));
+
+ const dialog = document.querySelector('dialog')!;
+ expect(dialog).toHaveAttribute('open');
+ expect(screen.getByAltText('Photo 3')).toBeInTheDocument();
+ expect(screen.queryByAltText('Photo 1')).toBeNull();
+ });
+
+ it('closes when the lightbox close button is pressed', () => {
+ render(<Gallery />);
+ fireEvent.click(screen.getByTestId('thumb-2'));
+
+ fireEvent.click(screen.getByRole('button', {name: 'Close'}));
+
+ expect(screen.getByTestId('status').textContent).toBe('closed');
+ expect(document.querySelector('dialog')).not.toHaveAttribute('open');
+ });
+
+ it('follows the index when the lightbox navigates', () => {
+ render(<Gallery />);
+ fireEvent.click(screen.getByTestId('thumb-2'));
+
+ fireEvent.click(screen.getByRole('button', {name: 'Next'}));
+
+ expect(screen.getByTestId('index').textContent).toBe('3');
+ expect(screen.getByAltText('Photo 4')).toBeInTheDocument();
+ });
+
+ it('reopens at a new index after closing', () => {
+ render(<Gallery />);
+ fireEvent.click(screen.getByTestId('thumb-0'));
+ fireEvent.click(screen.getByRole('button', {name: 'Close'}));
+
+ fireEvent.click(screen.getByTestId('thumb-3'));
+
+ expect(screen.getByTestId('index').textContent).toBe('3');
+ expect(screen.getByAltText('Photo 4')).toBeInTheDocument();
+ });
+});
diff --git a/packages/core/src/PowerSearch/PowerSearchFilterEditor.test.tsx b/packages/core/src/PowerSearch/PowerSearchFilterEditor.test.tsx
new file mode 100644
index 0000000000..cec5e2eef5
--- /dev/null
+++ b/packages/core/src/PowerSearch/PowerSearchFilterEditor.test.tsx
@@ -0,0 +1,253 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file PowerSearchFilterEditor.test.tsx
+ * @input Uses vitest, @testing-library/react, PowerSearchFilterEditor
+ * @output Unit tests for the default PowerSearch editor wrapper
+ * @position Testing; validates PowerSearchFilterEditor.tsx config
+ * normalization, the field-keyed remount contract, and prop forwarding
+ *
+ * SYNC: When PowerSearchFilterEditor.tsx changes, update tests to match
+ */
+
+import {describe, it, expect, vi, beforeAll} from 'vitest';
+import {render, screen, fireEvent} from '@testing-library/react';
+import {PowerSearchFilterEditor} from './PowerSearchFilterEditor';
+import type {PowerSearchConfig, PartialFilter} from './types';
+
+// =============================================================================
+// Test infrastructure
+// =============================================================================
+
+class MockResizeObserver {
+ observe() {}
+ unobserve() {}
+ disconnect() {}
+}
+
+beforeAll(() => {
+ globalThis.ResizeObserver = MockResizeObserver;
+});
+
+// =============================================================================
+// Fixtures
+// =============================================================================
+
+const config: PowerSearchConfig = {
+ name: 'TestSearch',
+ fields: [
+ {
+ key: 'status',
+ label: 'Status',
+ operators: [{key: 'is', label: 'is', value: {type: 'string'}}],
+ },
+ {
+ key: 'priority',
+ label: 'Priority',
+ operators: [{key: 'equals', label: 'equals', value: {type: 'string'}}],
+ },
+ ],
+};
+
+const statusFilter: PartialFilter = {
+ field: 'status',
+ operator: 'is',
+ value: {type: 'string', value: 'open'},
+};
+
+const priorityFilter: PartialFilter = {
+ field: 'priority',
+ operator: 'equals',
+ value: {type: 'string', value: 'high'},
+};
+
+function valueInput(): HTMLInputElement {
+ return screen.getByRole('textbox', {name: 'Value'});
+}
+
+/** The popover renders the field selector first, then the operator selector. */
+function selectorTriggers(): HTMLElement[] {
+ return screen.getAllByRole('combobox');
+}
+
+// =============================================================================
+// Tests
+// =============================================================================
+
+describe('PowerSearchFilterEditor', () => {
+ it('renders the editor with labels resolved from the raw config', () => {
+ render(
+ <PowerSearchFilterEditor
+ config={config}
+ filter={statusFilter}
+ mode="edit"
+ onSave={vi.fn()}
+ onCancel={vi.fn()}
+ />,
+ );
+
+ // The config is indexed before it reaches the popover, so the field key
+ // 'status' is displayed as its label 'Status' and 'is' as the operator.
+ const [fieldTrigger, operatorTrigger] = selectorTriggers();
+ expect(fieldTrigger).toHaveTextContent(/^Status$/);
+ expect(operatorTrigger).toHaveTextContent(/^is$/);
+ expect(valueInput()).toHaveValue('open');
+ });
+
+ it('discards in-progress edits when the filter field changes', () => {
+ const {rerender} = render(
+ <PowerSearchFilterEditor
+ config={config}
+ filter={statusFilter}
+ mode="edit"
+ onSave={vi.fn()}
+ onCancel={vi.fn()}
+ />,
+ );
+
+ fireEvent.change(valueInput(), {target: {value: 'edited'}});
+ expect(valueInput()).toHaveValue('edited');
+
+ rerender(
+ <PowerSearchFilterEditor
+ config={config}
+ filter={priorityFilter}
+ mode="edit"
+ onSave={vi.fn()}
+ onCancel={vi.fn()}
+ />,
+ );
+
+ // A new field remounts the popover, so its state restarts from the
+ // incoming filter instead of keeping the edit made against the old one.
+ expect(valueInput()).toHaveValue('high');
+ const [fieldTrigger, operatorTrigger] = selectorTriggers();
+ expect(fieldTrigger).toHaveTextContent(/^Priority$/);
+ expect(operatorTrigger).toHaveTextContent(/^equals$/);
+ });
+
+ it('keeps in-progress edits when only the filter value changes', () => {
+ const {rerender} = render(
+ <PowerSearchFilterEditor
+ config={config}
+ filter={statusFilter}
+ mode="edit"
+ onSave={vi.fn()}
+ onCancel={vi.fn()}
+ />,
+ );
+
+ fireEvent.change(valueInput(), {target: {value: 'edited'}});
+
+ rerender(
+ <PowerSearchFilterEditor
+ config={config}
+ filter={{...statusFilter, value: {type: 'string', value: 'closed'}}}
+ mode="edit"
+ onSave={vi.fn()}
+ onCancel={vi.fn()}
+ />,
+ );
+
+ // Same field — no remount, so the user's edit survives.
+ expect(valueInput()).toHaveValue('edited');
+ });
+
+ it('forwards the save button label to the primary action', () => {
+ render(
+ <PowerSearchFilterEditor
+ config={config}
+ filter={statusFilter}
+ mode="edit"
+ onSave={vi.fn()}
+ onCancel={vi.fn()}
+ saveButtonLabel="Save"
+ />,
+ );
+
+ expect(screen.getByRole('button', {name: 'Save'})).toBeInTheDocument();
+ expect(screen.queryByRole('button', {name: 'Apply'})).toBeNull();
+ });
+
+ it('forwards the edited filter to onSave', () => {
+ const onSave = vi.fn();
+ render(
+ <PowerSearchFilterEditor
+ config={config}
+ filter={statusFilter}
+ mode="edit"
+ onSave={onSave}
+ onCancel={vi.fn()}
+ />,
+ );
+
+ fireEvent.change(valueInput(), {target: {value: 'closed'}});
+ fireEvent.click(screen.getByRole('button', {name: 'Apply'}));
+
+ expect(onSave).toHaveBeenCalledTimes(1);
+ expect(onSave).toHaveBeenCalledWith({
+ field: 'status',
+ operator: 'is',
+ value: {type: 'string', value: 'closed'},
+ });
+ });
+
+ it('forwards onCancel to the cancel action', () => {
+ const onCancel = vi.fn();
+ render(
+ <PowerSearchFilterEditor
+ config={config}
+ filter={statusFilter}
+ mode="edit"
+ onSave={vi.fn()}
+ onCancel={onCancel}
+ />,
+ );
+
+ fireEvent.click(screen.getByRole('button', {name: 'Cancel'}));
+ expect(onCancel).toHaveBeenCalledTimes(1);
+ });
+
+ it('forwards the mode so only an existing filter offers deletion', () => {
+ const {unmount} = render(
+ <PowerSearchFilterEditor
+ config={config}
+ filter={statusFilter}
+ mode="edit"
+ onSave={vi.fn()}
+ onCancel={vi.fn()}
+ />,
+ );
+ expect(screen.getByRole('button', {name: 'Delete'})).toBeInTheDocument();
+ unmount();
+
+ render(
+ <PowerSearchFilterEditor
+ config={config}
+ filter={statusFilter}
+ mode="create"
+ onSave={vi.fn()}
+ onCancel={vi.fn()}
+ />,
+ );
+ expect(screen.queryByRole('button', {name: 'Delete'})).toBeNull();
+ });
+
+ it('forwards isReadOnly so the field and operator cannot be changed', () => {
+ render(
+ <PowerSearchFilterEditor
+ config={config}
+ filter={statusFilter}
+ mode="edit"
+ onSave={vi.fn()}
+ onCancel={vi.fn()}
+ isReadOnly
+ />,
+ );
+
+ expect(screen.queryByRole('button', {name: 'Delete'})).toBeNull();
+ const [fieldTrigger, operatorTrigger] = selectorTriggers();
+ expect(fieldTrigger).toBeDisabled();
+ expect(operatorTrigger).toBeDisabled();
+ });
+});
diff --git a/packages/core/src/PowerSearch/PowerSearchToken.test.tsx b/packages/core/src/PowerSearch/PowerSearchToken.test.tsx
new file mode 100644
index 0000000000..f702649d64
--- /dev/null
+++ b/packages/core/src/PowerSearch/PowerSearchToken.test.tsx
@@ -0,0 +1,228 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file PowerSearchToken.test.tsx
+ * @input Uses vitest, @testing-library/react, PowerSearchToken
+ * @output Unit tests for the default PowerSearch token pill
+ * @position Testing; validates PowerSearchToken.tsx label composition,
+ * value truncation budget, and click/remove/disabled wiring
+ *
+ * SYNC: When PowerSearchToken.tsx changes, update tests to match
+ */
+
+import {describe, it, expect, vi} from 'vitest';
+import {render, screen, fireEvent} from '@testing-library/react';
+import {PowerSearchToken} from './PowerSearchToken';
+import type {
+ FilterValue,
+ PowerSearchConfig,
+ PowerSearchField,
+ PowerSearchOperator,
+} from './types';
+
+// =============================================================================
+// Fixtures
+// =============================================================================
+
+const isOperator: PowerSearchOperator = {
+ key: 'is',
+ label: 'is',
+ value: {type: 'string'},
+};
+
+const statusField: PowerSearchField = {
+ key: 'status',
+ label: 'Status',
+ operators: [isOperator],
+};
+
+const config: PowerSearchConfig = {
+ name: 'TestSearch',
+ fields: [statusField],
+};
+
+/** 26 characters — long enough that every truncation budget below bites. */
+const LONG_VALUE = 'abcdefghijklmnopqrstuvwxyz';
+
+function renderToken(
+ overrides: {
+ field?: PowerSearchField;
+ operator?: PowerSearchOperator;
+ value?: FilterValue;
+ maxLength?: number;
+ onClick?: () => void;
+ onRemove?: () => void;
+ isDisabled?: boolean;
+ } = {},
+) {
+ const field = overrides.field ?? statusField;
+ const operator = overrides.operator ?? isOperator;
+ const value = overrides.value ?? {type: 'string', value: 'open'};
+ return render(
+ <PowerSearchToken
+ config={config}
+ filter={{field: field.key, operator: operator.key, value}}
+ field={field}
+ operator={operator}
+ maxLength={overrides.maxLength ?? 60}
+ onClick={overrides.onClick}
+ onRemove={overrides.onRemove}
+ isDisabled={overrides.isDisabled}
+ />,
+ );
+}
+
+// =============================================================================
+// Tests
+// =============================================================================
+
+describe('PowerSearchToken', () => {
+ it('joins the field label and the operator label with a colon', () => {
+ renderToken();
+ expect(screen.getByText('Status: is')).toBeInTheDocument();
+ });
+
+ it('drops the colon when the operator resolves to an empty label', () => {
+ renderToken({
+ operator: {key: 'any', label: '', value: {type: 'string'}},
+ });
+ expect(screen.getByText('Status')).toBeInTheDocument();
+ expect(screen.queryByText('Status:')).toBeNull();
+ });
+
+ it('resolves an i18nKey operator through the translator', () => {
+ renderToken({
+ operator: {
+ key: 'contains',
+ i18nKey: '@astryx.powersearch.operator.contains',
+ value: {type: 'string'},
+ },
+ });
+ expect(screen.getByText('Status: contains')).toBeInTheDocument();
+ });
+
+ it('renders the formatted value in its own element beside the label', () => {
+ const {container} = renderToken({value: {type: 'string', value: 'open'}});
+ const label = screen.getByText('Status: is');
+ const value = screen.getByText('open');
+ expect(value).not.toBe(label);
+ expect(container.firstElementChild?.childElementCount).toBe(2);
+ });
+
+ it('renders no value element when the value formats to an empty string', () => {
+ const {container} = renderToken({value: {type: 'empty'}});
+ // Only the label element remains — the value span is dropped entirely.
+ expect(container.firstElementChild?.childElementCount).toBe(1);
+ expect(container.firstElementChild).toHaveTextContent(/^Status: is$/);
+ });
+
+ it('formats the value with the operator value definition, not the raw value', () => {
+ const enumOperator: PowerSearchOperator = {
+ key: 'is',
+ label: 'is',
+ value: {
+ type: 'enum',
+ values: [
+ {value: 'open', label: 'Open'},
+ {value: 'closed', label: 'Closed'},
+ ],
+ },
+ };
+ renderToken({
+ operator: enumOperator,
+ value: {type: 'enum', value: 'open'},
+ });
+ expect(screen.getByText('Open')).toBeInTheDocument();
+ expect(screen.queryByText('open')).toBeNull();
+ });
+
+ it('renders the value in full when the label leaves enough budget', () => {
+ // 60 - len('Status') - len('is') = 52 >= 26
+ renderToken({maxLength: 60, value: {type: 'string', value: LONG_VALUE}});
+ expect(screen.getByText(LONG_VALUE)).toBeInTheDocument();
+ });
+
+ it('shrinks the value budget by the field and operator label lengths', () => {
+ // 30 - len('Status') - len('contains') = 16 -> 15 chars + ellipsis
+ renderToken({
+ operator: {key: 'contains', label: 'contains', value: {type: 'string'}},
+ maxLength: 30,
+ value: {type: 'string', value: LONG_VALUE},
+ });
+ expect(screen.getByText('abcdefghijklmno…')).toBeInTheDocument();
+ });
+
+ it('never shrinks the value budget below ten characters', () => {
+ // 20 - 38 - 8 is negative, so the floor of 10 applies: 9 chars + ellipsis
+ renderToken({
+ field: {
+ key: 'status',
+ label: 'Extremely Long Field Label For Testing',
+ operators: [isOperator],
+ },
+ operator: {key: 'contains', label: 'contains', value: {type: 'string'}},
+ maxLength: 20,
+ value: {type: 'string', value: LONG_VALUE},
+ });
+ expect(screen.getByText('abcdefghi…')).toBeInTheDocument();
+ });
+
+ it('calls onClick when the token is activated', () => {
+ const onClick = vi.fn();
+ renderToken({onClick});
+ fireEvent.click(screen.getByRole('button', {name: 'Status: is'}));
+ expect(onClick).toHaveBeenCalledTimes(1);
+ });
+
+ it('stops the activation click from reaching an enclosing handler', () => {
+ const onClick = vi.fn();
+ const onOuterClick = vi.fn();
+ render(
+ <div onClick={onOuterClick}>
+ <PowerSearchToken
+ config={config}
+ filter={{
+ field: 'status',
+ operator: 'is',
+ value: {type: 'string', value: 'open'},
+ }}
+ field={statusField}
+ operator={isOperator}
+ maxLength={60}
+ onClick={onClick}
+ />
+ <button type="button">outside</button>
+ </div>,
+ );
+
+ fireEvent.click(screen.getByRole('button', {name: 'Status: is'}));
+ expect(onClick).toHaveBeenCalledTimes(1);
+ expect(onOuterClick).not.toHaveBeenCalled();
+
+ // Control: a click that is not stopped does reach the enclosing handler.
+ fireEvent.click(screen.getByRole('button', {name: 'outside'}));
+ expect(onOuterClick).toHaveBeenCalledTimes(1);
+ });
+
+ it('renders no remove button when onRemove is omitted', () => {
+ renderToken();
+ expect(
+ screen.queryByRole('button', {name: 'Remove Status: is'}),
+ ).toBeNull();
+ });
+
+ it('calls onRemove when the remove button is clicked', () => {
+ const onRemove = vi.fn();
+ renderToken({onRemove});
+ fireEvent.click(screen.getByRole('button', {name: 'Remove Status: is'}));
+ expect(onRemove).toHaveBeenCalledTimes(1);
+ });
+
+ it('disables both the activation and remove buttons when isDisabled is set', () => {
+ renderToken({onClick: vi.fn(), onRemove: vi.fn(), isDisabled: true});
+ expect(screen.getByRole('button', {name: 'Status: is'})).toBeDisabled();
+ expect(
+ screen.getByRole('button', {name: 'Remove Status: is'}),
+ ).toBeDisabled();
+ });
+});
diff --git a/packages/core/src/Table/TableHeaderCell.test.tsx b/packages/core/src/Table/TableHeaderCell.test.tsx
new file mode 100644
index 0000000000..baa3f34006
--- /dev/null
+++ b/packages/core/src/Table/TableHeaderCell.test.tsx
@@ -0,0 +1,291 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file TableHeaderCell.test.tsx
+ * @input Uses vitest, @testing-library/react, StyleX, Table, TableHeaderCell
+ * @output Unit tests for TableHeaderCell
+ * @position Testing; validates the `<th>` contract, the standalone (no
+ * TableContext) plain render, and the context-driven density/divider styling
+ *
+ * SYNC: When TableHeaderCell.tsx changes, update tests to match
+ */
+
+import {describe, it, expect, vi} from 'vitest';
+import {render, screen} from '@testing-library/react';
+import * as stylex from '@stylexjs/stylex';
+import {Table} from './Table';
+import {TableHeaderCell} from './TableHeaderCell';
+import type {TableColumn} from './types';
+
+// =============================================================================
+// Test Data
+// =============================================================================
+
+interface User extends Record<string, unknown> {
+ name: string;
+ age: number;
+}
+
+const users: User[] = [{name: 'Alice', age: 30}];
+
+const columns: TableColumn<User>[] = [
+ {key: 'name', header: 'Name'},
+ {key: 'age', header: 'Age'},
+];
+
+// =============================================================================
+// Helpers
+// =============================================================================
+
+/**
+ * Read back the CSS declarations that actually apply to an element's classes.
+ * StyleX runs with `runtimeInjection` under vitest, so the real rules live in
+ * `document.styleSheets` — this keeps the assertions on declarations instead
+ * of on hashed class names.
+ *
+ * Conditional rules keep their pseudo-class prefix, e.g.
+ * `:last-child border-inline-end-width: 0`.
+ */
+function cssDeclarationsOf(el: Element): string[] {
+ const classes = new Set(
+ (el as HTMLElement).className.split(/\s+/).filter(Boolean),
+ );
+ const declarations: string[] = [];
+
+ for (const sheet of Array.from(document.styleSheets)) {
+ for (const rule of Array.from(sheet.cssRules)) {
+ const text = rule.cssText;
+ const brace = text.indexOf('{');
+ if (brace === -1) {
+ continue;
+ }
+ // Strip StyleX's `:not(#\#)` specificity padding from the selector.
+ const selector = text.slice(0, brace).replaceAll(':not(#\\#)', '').trim();
+ const match = /^\.([\w-]+)(.*)$/.exec(selector);
+ if (!match || !classes.has(match[1])) {
+ continue;
+ }
+ const body = text
+ .slice(brace + 1, text.lastIndexOf('}'))
+ .trim()
+ .replace(/;$/, '');
+ const condition = match[2].trim();
+ declarations.push(condition ? `${condition} ${body}` : body);
+ }
+ }
+
+ return declarations;
+}
+
+/** Render a lone header cell with no Table around it. */
+function renderStandalone(cell: React.ReactNode) {
+ return render(
+ <table>
+ <thead>
+ <tr>{cell}</tr>
+ </thead>
+ </table>,
+ );
+}
+
+/** Declarations applying to the first header cell of a rendered Table. */
+function headerCellDeclarations(container: HTMLElement): string[] {
+ const th = container.querySelector('thead th');
+ expect(th).not.toBeNull();
+ return cssDeclarationsOf(th as Element);
+}
+
+// =============================================================================
+// Tests
+// =============================================================================
+
+describe('TableHeaderCell', () => {
+ it('renders a th element around its children', () => {
+ const {container} = renderStandalone(
+ <TableHeaderCell>Name</TableHeaderCell>,
+ );
+ const th = container.querySelector('th');
+ expect(th).not.toBeNull();
+ expect(th).toHaveTextContent('Name');
+ expect(screen.getByRole('columnheader')).toBe(th);
+ });
+
+ it('sets no scope attribute unless one is given', () => {
+ const {container} = renderStandalone(
+ <TableHeaderCell>Name</TableHeaderCell>,
+ );
+ expect(container.querySelector('th')).not.toHaveAttribute('scope');
+ });
+
+ it('reflects the scope prop on the th', () => {
+ const {container} = renderStandalone(
+ <TableHeaderCell scope="rowgroup">Name</TableHeaderCell>,
+ );
+ expect(container.querySelector('th')).toHaveAttribute('scope', 'rowgroup');
+ });
+
+ it('renders unstyled when used outside a Table', () => {
+ const {container} = renderStandalone(
+ <TableHeaderCell>Name</TableHeaderCell>,
+ );
+ const th = container.querySelector('th') as HTMLElement;
+ // No table context — no density, divider or overflow styling at all.
+ expect(cssDeclarationsOf(th)).toEqual([]);
+ expect(th).toHaveClass('astryx-table-header-cell');
+ });
+
+ it('takes the balanced density padding from the table by default', () => {
+ const {container} = render(<Table data={users} columns={columns} />);
+ const declarations = headerCellDeclarations(container);
+ expect(declarations).toContain('padding-block: var(--spacing-2)');
+ expect(declarations).toContain('padding-inline: var(--spacing-3)');
+ });
+
+ it('takes the compact density padding from the table', () => {
+ const {container} = render(
+ <Table data={users} columns={columns} density="compact" />,
+ );
+ const declarations = headerCellDeclarations(container);
+ expect(declarations).toContain('padding-block: var(--spacing-1)');
+ expect(declarations).toContain('padding-inline: var(--spacing-2)');
+ });
+
+ it('takes the spacious density padding from the table', () => {
+ const {container} = render(
+ <Table data={users} columns={columns} density="spacious" />,
+ );
+ const declarations = headerCellDeclarations(container);
+ expect(declarations).toContain('padding-block: var(--spacing-3)');
+ expect(declarations).toContain('padding-inline: var(--spacing-4)');
+ });
+
+ it('applies the header font weight and color inside a table', () => {
+ const {container} = render(<Table data={users} columns={columns} />);
+ const declarations = headerCellDeclarations(container);
+ expect(declarations).toContain('font-weight: var(--font-weight-semibold)');
+ expect(declarations).toContain('color: var(--color-text-secondary)');
+ });
+
+ it('draws the bottom divider even when the table has dividers off', () => {
+ const {container} = render(
+ <Table data={users} columns={columns} dividers="none" />,
+ );
+ const declarations = headerCellDeclarations(container);
+ // The header/body separator is unconditional inside a table.
+ expect(declarations).toContain('border-bottom-width: var(--border-width)');
+ expect(declarations).toContain('border-bottom-style: solid');
+ expect(declarations).toContain('border-bottom-color: var(--color-border)');
+ // …but the column divider is not.
+ expect(declarations.filter(d => d.includes('border-inline-end'))).toEqual(
+ [],
+ );
+ });
+
+ it('draws no column divider when the table divides rows only', () => {
+ const {container} = render(
+ <Table data={users} columns={columns} dividers="rows" />,
+ );
+ expect(
+ headerCellDeclarations(container).filter(d =>
+ d.includes('border-inline-end'),
+ ),
+ ).toEqual([]);
+ });
+
+ // StyleX packs the default and the `:last-child` override into one atomic
+ // class, so this reads the rules the header cells carry rather than
+ // comparing two cells — both carry byte-identical classes. The divider sits
+ // on the logical inline-end edge so it mirrors under RTL.
+ it('draws a column divider that the last header cell zeroes out', () => {
+ const {container} = render(
+ <Table data={users} columns={columns} dividers="columns" />,
+ );
+ const declarations = headerCellDeclarations(container);
+ expect(declarations).toContain(
+ 'border-inline-end-width: var(--border-width)',
+ );
+ expect(declarations).toContain('border-inline-end-style: solid');
+ expect(declarations).toContain(
+ 'border-inline-end-color: var(--color-border)',
+ );
+ expect(declarations).toContain(':last-child border-inline-end-width: 0');
+ });
+
+ it('draws a column divider when the table divides on a grid', () => {
+ const {container} = render(
+ <Table data={users} columns={columns} dividers="grid" />,
+ );
+ expect(headerCellDeclarations(container)).toContain(
+ 'border-inline-end-width: var(--border-width)',
+ );
+ });
+
+ it('lets consumer xstyle win over the context header styling', () => {
+ const custom = stylex.create({trailing: {textAlign: 'end'}});
+ const {container} = render(
+ <Table>
+ <thead>
+ <tr>
+ <TableHeaderCell xstyle={custom.trailing}>Name</TableHeaderCell>
+ </tr>
+ </thead>
+ </Table>,
+ );
+ const declarations = headerCellDeclarations(container);
+ // The context sets `text-align: start`; xstyle merges on top of it.
+ expect(declarations).toContain('text-align: end');
+ expect(declarations).not.toContain('text-align: start');
+ // The rest of the context styling survives the override.
+ expect(declarations).toContain('padding-inline: var(--spacing-3)');
+ });
+
+ it('accepts an array of xstyle values', () => {
+ const custom = stylex.create({
+ caps: {textTransform: 'uppercase'},
+ spaced: {letterSpacing: '2px'},
+ });
+ const {container} = renderStandalone(
+ <TableHeaderCell xstyle={[custom.caps, custom.spaced]}>
+ Name
+ </TableHeaderCell>,
+ );
+ const th = container.querySelector('th') as HTMLElement;
+ expect(cssDeclarationsOf(th).sort()).toEqual([
+ 'letter-spacing: 2px',
+ 'text-transform: uppercase',
+ ]);
+ });
+
+ it('forwards the ref to the th element', () => {
+ const ref = vi.fn();
+ renderStandalone(<TableHeaderCell ref={ref}>Name</TableHeaderCell>);
+ expect(ref).toHaveBeenCalledWith(expect.any(HTMLTableCellElement));
+ });
+
+ it('spreads html attributes onto the th', () => {
+ const {container} = renderStandalone(
+ <TableHeaderCell
+ id="name-header"
+ aria-sort="ascending"
+ data-column-key="name">
+ Name
+ </TableHeaderCell>,
+ );
+ const th = container.querySelector('th') as HTMLElement;
+ expect(th.id).toBe('name-header');
+ expect(th).toHaveAttribute('aria-sort', 'ascending');
+ expect(th).toHaveAttribute('data-column-key', 'name');
+ });
+
+ it('keeps a consumer className and style alongside the astryx class', () => {
+ const {container} = renderStandalone(
+ <TableHeaderCell className="custom-header" style={{width: '10px'}}>
+ Name
+ </TableHeaderCell>,
+ );
+ const th = container.querySelector('th') as HTMLElement;
+ expect(th).toHaveClass('astryx-table-header-cell');
+ expect(th).toHaveClass('custom-header');
+ expect(th.style.width).toBe('10px');
+ });
+});
diff --git a/packages/core/src/Table/plugins/filtering/useTableFilterState.test.tsx b/packages/core/src/Table/plugins/filtering/useTableFilterState.test.tsx
new file mode 100644
index 0000000000..450ae2bbf7
--- /dev/null
+++ b/packages/core/src/Table/plugins/filtering/useTableFilterState.test.tsx
@@ -0,0 +1,143 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file useTableFilterState.test.tsx
+ * @input Uses vitest, @testing-library/react
+ * @output Unit tests for the useTableFilterState hook
+ * @position Testing; validates the filter state helper (set/overwrite,
+ * null-deletes, clearAll, callback stability)
+ */
+
+import {describe, it, expect} from 'vitest';
+import {act, renderHook} from '@testing-library/react';
+import {useTableFilterState} from './useTableFilterState';
+
+// =============================================================================
+// Initial state
+// =============================================================================
+
+describe('useTableFilterState — initial state', () => {
+ it('starts with an empty filter map', () => {
+ const {result} = renderHook(() => useTableFilterState());
+
+ expect(result.current.filters).toEqual({});
+ });
+
+ it('adopts the provided initial state', () => {
+ const {result} = renderHook(() =>
+ useTableFilterState({status: 'active', tags: ['a', 'b']}),
+ );
+
+ expect(result.current.filters).toEqual({
+ status: 'active',
+ tags: ['a', 'b'],
+ });
+ });
+});
+
+// =============================================================================
+// onFilterChange
+// =============================================================================
+
+describe('useTableFilterState — onFilterChange', () => {
+ it('sets a filter value for a key', () => {
+ const {result} = renderHook(() => useTableFilterState());
+
+ act(() => {
+ result.current.onFilterChange('status', 'active');
+ });
+
+ expect(result.current.filters).toEqual({status: 'active'});
+ });
+
+ it('overwrites an existing key with the new value', () => {
+ const {result} = renderHook(() => useTableFilterState({status: 'active'}));
+
+ act(() => {
+ result.current.onFilterChange('status', 'archived');
+ });
+
+ expect(result.current.filters).toEqual({status: 'archived'});
+ });
+
+ it('keeps other keys intact when setting a new one', () => {
+ const {result} = renderHook(() => useTableFilterState({status: 'active'}));
+
+ act(() => {
+ result.current.onFilterChange('owner', 'alice');
+ });
+
+ expect(result.current.filters).toEqual({
+ status: 'active',
+ owner: 'alice',
+ });
+ });
+
+ it('deletes the key entirely when the value is null', () => {
+ const {result} = renderHook(() =>
+ useTableFilterState({status: 'active', owner: 'alice'}),
+ );
+
+ act(() => {
+ result.current.onFilterChange('status', null);
+ });
+
+ // The key must be absent — not present with a null value.
+ expect('status' in result.current.filters).toBe(false);
+ expect(result.current.filters).toEqual({owner: 'alice'});
+ });
+
+ it('deleting a key that is not set leaves the state unchanged', () => {
+ const {result} = renderHook(() => useTableFilterState({owner: 'alice'}));
+
+ act(() => {
+ result.current.onFilterChange('ghost', null);
+ });
+
+ expect(result.current.filters).toEqual({owner: 'alice'});
+ });
+});
+
+// =============================================================================
+// clearAll
+// =============================================================================
+
+describe('useTableFilterState — clearAll', () => {
+ it('resets both initial and added filters to an empty map', () => {
+ const {result} = renderHook(() => useTableFilterState({status: 'active'}));
+
+ act(() => {
+ result.current.onFilterChange('owner', 'alice');
+ });
+ expect(result.current.filters).toEqual({
+ status: 'active',
+ owner: 'alice',
+ });
+
+ act(() => {
+ result.current.clearAll();
+ });
+
+ expect(result.current.filters).toEqual({});
+ });
+});
+
+// =============================================================================
+// Callback stability
+// =============================================================================
+
+describe('useTableFilterState — callback stability', () => {
+ it('keeps onFilterChange and clearAll referentially stable across updates and rerenders', () => {
+ const {result, rerender} = renderHook(() => useTableFilterState());
+ const initialOnFilterChange = result.current.onFilterChange;
+ const initialClearAll = result.current.clearAll;
+
+ act(() => {
+ result.current.onFilterChange('status', 'active');
+ });
+ rerender();
+
+ expect(result.current.onFilterChange).toBe(initialOnFilterChange);
+ expect(result.current.clearAll).toBe(initialClearAll);
+ });
+});
diff --git a/packages/core/src/Tooltip/useTooltip.test.tsx b/packages/core/src/Tooltip/useTooltip.test.tsx
new file mode 100644
index 0000000000..ac8c17b7d0
--- /dev/null
+++ b/packages/core/src/Tooltip/useTooltip.test.tsx
@@ -0,0 +1,318 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file useTooltip.test.tsx
+ * @input Uses vitest, @testing-library/react, useTooltip hook
+ * @output Unit tests for the tooltip show/hide timers and controlled state
+ * @position Testing; validates useTooltip.tsx timing contract. Component-level
+ * behavior lives in Tooltip.test.tsx — this file pins the delays, the
+ * hover-bridge constant, and timer teardown, which are invisible from there.
+ *
+ * SYNC: When useTooltip.tsx changes, update tests to match new behavior
+ */
+
+import {
+ describe,
+ it,
+ expect,
+ vi,
+ beforeAll,
+ afterAll,
+ beforeEach,
+ afterEach,
+} from 'vitest';
+import {render, screen, fireEvent, act} from '@testing-library/react';
+import {useTooltip, type TooltipOptions} from './useTooltip';
+
+// jsdom implements neither the Popover API nor `:popover-open`; mirror
+// Tooltip.test.tsx's shims so the layer can open.
+const originalMatches = HTMLElement.prototype.matches;
+const popoverOpenState = new WeakMap<HTMLElement, boolean>();
+
+beforeAll(() => {
+ HTMLElement.prototype.showPopover = vi.fn(function (this: HTMLElement) {
+ popoverOpenState.set(this, true);
+ });
+ HTMLElement.prototype.hidePopover = vi.fn(function (this: HTMLElement) {
+ popoverOpenState.set(this, false);
+ });
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ (HTMLElement.prototype as any).matches = function (selector: string) {
+ if (selector === ':popover-open') {
+ return popoverOpenState.get(this) ?? false;
+ }
+ return originalMatches.call(this, selector);
+ };
+});
+
+afterAll(() => {
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ (HTMLElement.prototype as any).matches = originalMatches;
+});
+
+beforeEach(() => {
+ vi.useFakeTimers();
+});
+
+afterEach(() => {
+ vi.useRealTimers();
+});
+
+function Harness(options: TooltipOptions) {
+ const tooltip = useTooltip(options);
+ return (
+ <div>
+ <button
+ type="button"
+ ref={tooltip.ref}
+ aria-describedby={tooltip.describedBy}>
+ Trigger
+ </button>
+ {tooltip.renderTooltip('Helpful text')}
+ </div>
+ );
+}
+
+function trigger() {
+ return screen.getByRole('button', {name: 'Trigger'});
+}
+
+/** The popover element the trigger's aria-describedby points at. */
+function tooltipElement(): HTMLElement {
+ const id = trigger().getAttribute('aria-describedby');
+ const element = id == null ? null : document.getElementById(id);
+ expect(element).not.toBeNull();
+ return element as HTMLElement;
+}
+
+/** Advance timers inside act so the layer's state updates flush. */
+function tick(ms: number) {
+ act(() => {
+ vi.advanceTimersByTime(ms);
+ });
+}
+
+describe('useTooltip — show delay', () => {
+ it('does not show before the default 200ms delay elapses', () => {
+ const onShow = vi.fn();
+ render(<Harness onShow={onShow} />);
+
+ fireEvent.mouseEnter(trigger());
+ tick(199);
+
+ expect(onShow).not.toHaveBeenCalled();
+ });
+
+ it('shows once the default 200ms delay elapses', () => {
+ const onShow = vi.fn();
+ render(<Harness onShow={onShow} />);
+
+ fireEvent.mouseEnter(trigger());
+ tick(200);
+
+ expect(onShow).toHaveBeenCalledTimes(1);
+ });
+
+ it('honors a custom delay on both sides of the boundary', () => {
+ const onShow = vi.fn();
+ render(<Harness delay={50} onShow={onShow} />);
+
+ fireEvent.mouseEnter(trigger());
+ tick(49);
+ expect(onShow).not.toHaveBeenCalled();
+
+ tick(1);
+ expect(onShow).toHaveBeenCalledTimes(1);
+ });
+
+ it('cancels a pending show when the pointer leaves before the delay elapses', () => {
+ const onShow = vi.fn();
+ render(<Harness onShow={onShow} />);
+
+ fireEvent.mouseEnter(trigger());
+ tick(100);
+ fireEvent.mouseLeave(trigger());
+ tick(1000);
+
+ expect(onShow).not.toHaveBeenCalled();
+ });
+
+ it('does not show on hover while isEnabled is false', () => {
+ const onShow = vi.fn();
+ render(<Harness isEnabled={false} onShow={onShow} />);
+
+ fireEvent.mouseEnter(trigger());
+ tick(1000);
+
+ expect(onShow).not.toHaveBeenCalled();
+ });
+});
+
+describe('useTooltip — touch suppression', () => {
+ it('never shows on the hover a finger synthesizes, but still on a mouse', () => {
+ // Touch is decided per interaction from the pointer type — a finger's
+ // arrival fires `pointerenter` ahead of the `mouseenter` a tap synthesizes
+ // — not once per device from a `(hover: none)` media query, so a hybrid
+ // device keeps hover under a mouse.
+ const onShow = vi.fn();
+ render(<Harness onShow={onShow} />);
+
+ fireEvent.pointerEnter(trigger(), {pointerType: 'touch'});
+ fireEvent.mouseEnter(trigger());
+ tick(1000);
+ expect(onShow).not.toHaveBeenCalled();
+
+ fireEvent.pointerEnter(trigger(), {pointerType: 'mouse'});
+ fireEvent.mouseEnter(trigger());
+ tick(200);
+ expect(onShow).toHaveBeenCalledTimes(1);
+ });
+});
+
+describe('useTooltip — hide delay', () => {
+ function showTooltip(onHide: () => void, options: TooltipOptions = {}) {
+ render(<Harness delay={0} onHide={onHide} {...options} />);
+ fireEvent.mouseEnter(trigger());
+ tick(0);
+ }
+
+ it('holds the tooltip open for a 100ms hover bridge when hideDelay is 0', () => {
+ const onHide = vi.fn();
+ showTooltip(onHide, {hideDelay: 0});
+
+ fireEvent.mouseLeave(trigger());
+ tick(99);
+ expect(onHide).not.toHaveBeenCalled();
+
+ tick(1);
+ expect(onHide).toHaveBeenCalledTimes(1);
+ });
+
+ it('applies the same hover bridge when hideDelay is left unset', () => {
+ const onHide = vi.fn();
+ showTooltip(onHide);
+
+ fireEvent.mouseLeave(trigger());
+ tick(99);
+ expect(onHide).not.toHaveBeenCalled();
+
+ tick(1);
+ expect(onHide).toHaveBeenCalledTimes(1);
+ });
+
+ it('uses an explicit hideDelay instead of the hover bridge', () => {
+ const onHide = vi.fn();
+ showTooltip(onHide, {hideDelay: 500});
+
+ fireEvent.mouseLeave(trigger());
+ tick(100);
+ expect(onHide).not.toHaveBeenCalled();
+
+ tick(400);
+ expect(onHide).toHaveBeenCalledTimes(1);
+ });
+});
+
+describe('useTooltip — controlled isOpen', () => {
+ it('shows on mount when isOpen is true', () => {
+ const onShow = vi.fn();
+ render(<Harness isOpen onShow={onShow} />);
+ expect(onShow).toHaveBeenCalledTimes(1);
+ });
+
+ it('ignores pointer-leave while isOpen is true', () => {
+ const onHide = vi.fn();
+ render(<Harness isOpen onHide={onHide} />);
+
+ fireEvent.mouseLeave(trigger());
+ tick(1000);
+
+ expect(onHide).not.toHaveBeenCalled();
+ });
+
+ it('never schedules a show while isOpen is false', () => {
+ const onShow = vi.fn();
+ render(<Harness isOpen={false} onShow={onShow} />);
+
+ fireEvent.mouseEnter(trigger());
+ expect(vi.getTimerCount()).toBe(0);
+
+ tick(1000);
+ expect(onShow).not.toHaveBeenCalled();
+ });
+});
+
+describe('useTooltip — Escape dismissal', () => {
+ it('hides an uncontrolled tooltip when Escape is pressed', () => {
+ const onHide = vi.fn();
+ render(<Harness delay={0} onHide={onHide} />);
+ fireEvent.mouseEnter(trigger());
+ tick(0);
+ expect(tooltipElement().matches(':popover-open')).toBe(true);
+
+ fireEvent.keyDown(document, {key: 'Escape'});
+
+ expect(onHide).toHaveBeenCalledTimes(1);
+ expect(tooltipElement().matches(':popover-open')).toBe(false);
+ });
+
+ it('ignores an Escape that carries the IME keyCode 229', () => {
+ const onHide = vi.fn();
+ render(<Harness delay={0} onHide={onHide} />);
+ fireEvent.mouseEnter(trigger());
+ tick(0);
+
+ fireEvent.keyDown(document, {key: 'Escape', keyCode: 229});
+
+ expect(onHide).not.toHaveBeenCalled();
+ });
+
+ it('ignores keys other than Escape', () => {
+ const onHide = vi.fn();
+ render(<Harness delay={0} onHide={onHide} />);
+ fireEvent.mouseEnter(trigger());
+ tick(0);
+
+ fireEvent.keyDown(document, {key: 'Enter'});
+
+ expect(onHide).not.toHaveBeenCalled();
+ });
+
+ it('reports Escape on a controlled tooltip through onHide without hiding it', () => {
+ const onHide = vi.fn();
+ render(<Harness isOpen onHide={onHide} />);
+ expect(tooltipElement().matches(':popover-open')).toBe(true);
+
+ fireEvent.keyDown(document, {key: 'Escape'});
+
+ // `isOpen` is the consumer's value: the hook asks, the consumer decides.
+ expect(onHide).toHaveBeenCalledTimes(1);
+ expect(tooltipElement().matches(':popover-open')).toBe(true);
+ });
+});
+
+describe('useTooltip — teardown', () => {
+ it('clears a pending show timer on unmount', () => {
+ const {unmount} = render(<Harness />);
+
+ fireEvent.mouseEnter(trigger());
+ expect(vi.getTimerCount()).toBe(1);
+
+ unmount();
+
+ expect(vi.getTimerCount()).toBe(0);
+ });
+
+ it('clears a pending hide timer on unmount', () => {
+ const {unmount} = render(<Harness delay={0} />);
+ fireEvent.mouseEnter(trigger());
+ tick(0);
+
+ fireEvent.mouseLeave(trigger());
+ expect(vi.getTimerCount()).toBe(1);
+
+ unmount();
+
+ expect(vi.getTimerCount()).toBe(0);
+ });
+});
diff --git a/packages/core/src/Typeahead/TypeaheadItem.test.tsx b/packages/core/src/Typeahead/TypeaheadItem.test.tsx
index 7dc592847b..3bfa9139c4 100644
--- a/packages/core/src/Typeahead/TypeaheadItem.test.tsx
+++ b/packages/core/src/Typeahead/TypeaheadItem.test.tsx
@@ -2,14 +2,28 @@
/**
* @file TypeaheadItem.test.tsx
- * @input Uses vitest, @testing-library/react, TypeaheadItem
+ * @input Uses vitest, @testing-library/react, TypeaheadItem, the shared
+ * declaredValue StyleX read-back helper
* @output Unit tests for TypeaheadItem
- * @position Testing; validates TypeaheadItem.tsx implementation
+ * @position Testing; validates TypeaheadItem.tsx implementation — pass-through
+ * props, the label/icon/description layout, disabled dimming, ref forwarding,
+ * and the pre-rendered `item.element` short-circuit
*/
import {describe, it, expect} from 'vitest';
+import {createRef, type ReactElement} from 'react';
import {render, screen} from '@testing-library/react';
import {TypeaheadItem} from './TypeaheadItem';
+import type {SearchableItem} from './types';
+import {declaredValue} from '../__tests__/stylexDeclarations';
+
+const item: SearchableItem = {id: '1', label: 'Alice'};
+
+/** Renders the item and returns its root row element. */
+function renderItem(ui: ReactElement): HTMLElement {
+ const {container} = render(ui);
+ return container.firstElementChild as HTMLElement;
+}
describe('TypeaheadItem', () => {
it('forwards pass-through props to the item element', () => {
@@ -40,4 +54,81 @@ describe('TypeaheadItem', () => {
expect(item.className).toContain('caller-class');
expect(item.className).toContain('astryx-typeahead-item');
});
+
+ it('renders the item label', () => {
+ render(<TypeaheadItem item={item} />);
+ expect(screen.getByText('Alice')).toBeInTheDocument();
+ });
+
+ it('renders the description below the label when provided', () => {
+ const root = renderItem(
+ <TypeaheadItem item={item} description="Engineer" />,
+ );
+ const content = root.lastElementChild!;
+ expect(Array.from(content.children).map(c => c.textContent)).toEqual([
+ 'Alice',
+ 'Engineer',
+ ]);
+ });
+
+ it('renders no description element when none is provided', () => {
+ const root = renderItem(<TypeaheadItem item={item} />);
+ const content = root.lastElementChild!;
+ expect(content.children.length).toBe(1);
+ expect(content.textContent).toBe('Alice');
+ });
+
+ it('renders the icon before the label content', () => {
+ const root = renderItem(
+ <TypeaheadItem item={item} icon={<svg data-testid="avatar" />} />,
+ );
+ expect(root.children.length).toBe(2);
+ expect(root.firstElementChild).toBe(screen.getByTestId('avatar'));
+ });
+
+ it('dims the row when isDisabled is set', () => {
+ const root = renderItem(<TypeaheadItem item={item} isDisabled />);
+ expect(declaredValue(root, 'opacity')).toBe('0.5');
+ });
+
+ it('does not dim the row by default', () => {
+ const root = renderItem(<TypeaheadItem item={item} />);
+ expect(declaredValue(root, 'opacity')).toBeNull();
+ });
+
+ it('forwards ref to the row element', () => {
+ const ref = createRef<HTMLDivElement>();
+ const root = renderItem(<TypeaheadItem item={item} ref={ref} />);
+ expect(ref.current).toBe(root);
+ });
+});
+
+describe('TypeaheadItem with a pre-rendered item.element', () => {
+ it('renders item.element raw in place of the label layout', () => {
+ // The caller's element is the whole output — not wrapped in the styled
+ // row — so the label, icon, description and isDisabled dimming have
+ // nowhere to land.
+ const {container} = render(
+ <TypeaheadItem
+ item={{
+ id: '1',
+ label: 'Never shown',
+ element: <div data-testid="prerendered">Pre-rendered row</div>,
+ }}
+ icon={<svg data-testid="avatar" />}
+ description="Engineer"
+ isDisabled
+ />,
+ );
+ const root = container.firstElementChild!;
+ expect(root).toBe(screen.getByTestId('prerendered'));
+ expect(container.children.length).toBe(1);
+ expect(root.className).toBe('');
+ expect(
+ container.querySelector('.astryx-typeahead-item'),
+ ).not.toBeInTheDocument();
+ expect(screen.queryByText('Never shown')).not.toBeInTheDocument();
+ expect(screen.queryByTestId('avatar')).not.toBeInTheDocument();
+ expect(screen.queryByText('Engineer')).not.toBeInTheDocument();
+ });
});
diff --git a/packages/core/src/__tests__/stylexDeclarations.ts b/packages/core/src/__tests__/stylexDeclarations.ts
new file mode 100644
index 0000000000..4bcbc7464b
--- /dev/null
+++ b/packages/core/src/__tests__/stylexDeclarations.ts
@@ -0,0 +1,51 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file stylexDeclarations.ts
+ * @input Uses document.styleSheets (populated by StyleX runtime injection)
+ * @output declaredValue — the CSS value a rendered element's StyleX classes
+ * actually declare for a property
+ * @position Shared test helper; imported by component tests that need to prove
+ * a style prop reached the element
+ *
+ * Vitest compiles StyleX with `runtimeInjection: true` (see vitest.config.ts),
+ * so the generated atomic rules are live in `document.styleSheets` during a
+ * test. Asserting on the declaration a class carries — rather than on the
+ * hashed class name itself — keeps these assertions stable across StyleX hash
+ * changes and across the atomic-class merging that makes literal class-name
+ * comparisons meaningless.
+ *
+ * Later rules win, matching the cascade for the equal-specificity atomic
+ * classes StyleX emits.
+ *
+ * SYNC: When modified, update this header.
+ */
+
+/**
+ * Read back the value the element's StyleX classes declare for `property`.
+ *
+ * @param el Rendered element to inspect.
+ * @param property CSS property name, e.g. `'opacity'` or `'width'`.
+ * @returns The declared value, or `null` when no class on the element declares
+ * the property.
+ */
+export function declaredValue(el: Element, property: string): string | null {
+ const classes = new Set(el.className.split(' '));
+ let value: string | null = null;
+ for (const sheet of Array.from(document.styleSheets)) {
+ for (const rule of Array.from(sheet.cssRules)) {
+ if (!(rule instanceof CSSStyleRule)) {
+ continue;
+ }
+ const owner = /^\.([\w-]+)/.exec(rule.selectorText)?.[1];
+ if (owner == null || !classes.has(owner)) {
+ continue;
+ }
+ const declared = rule.style.getPropertyValue(property);
+ if (declared !== '') {
+ value = declared;
+ }
+ }
+ }
+ return value;
+}
diff --git a/packages/core/src/hooks/useScrollLock.test.ts b/packages/core/src/hooks/useScrollLock.test.ts
index c305b82d55..0616fd9548 100644
--- a/packages/core/src/hooks/useScrollLock.test.ts
+++ b/packages/core/src/hooks/useScrollLock.test.ts
@@ -43,6 +43,109 @@ describe('useScrollLock', () => {
expect(window.scrollTo).toHaveBeenCalledWith(120, 480);
});
+ it('leaves the body alone and never scrolls when it is not locked', () => {
+ document.body.style.overflow = 'auto';
+ document.body.style.position = 'relative';
+ vi.spyOn(window, 'scrollTo').mockImplementation(() => {});
+
+ const lock = renderHook(() => useScrollLock(false));
+
+ expect(document.body.style.overflow).toBe('auto');
+ expect(document.body.style.position).toBe('relative');
+ expect(document.body.style.top).toBe('');
+ expect(document.body.style.left).toBe('');
+ expect(document.body.style.right).toBe('');
+
+ lock.unmount();
+
+ expect(window.scrollTo).not.toHaveBeenCalled();
+ });
+
+ it('pins the body edge to edge, offset upward by the current scroll position', () => {
+ vi.spyOn(window, 'scrollY', 'get').mockReturnValue(250);
+ vi.spyOn(window, 'scrollTo').mockImplementation(() => {});
+
+ renderHook(() => useScrollLock(true));
+
+ expect(document.body.style.top).toBe('-250px');
+ expect(document.body.style.left).toBe('0px');
+ expect(document.body.style.right).toBe('0px');
+ });
+
+ it('puts back pre-existing top/left/right inline styles instead of blanking them', () => {
+ document.body.style.top = '10px';
+ document.body.style.left = '5px';
+ document.body.style.right = '3px';
+ vi.spyOn(window, 'scrollTo').mockImplementation(() => {});
+
+ const lock = renderHook(({locked}) => useScrollLock(locked), {
+ initialProps: {locked: true},
+ });
+ expect(document.body.style.position).toBe('fixed');
+
+ lock.rerender({locked: false});
+
+ expect(document.body.style.top).toBe('10px');
+ expect(document.body.style.left).toBe('5px');
+ expect(document.body.style.right).toBe('3px');
+ });
+
+ it('scrolls back to the offset captured at lock time, not the offset at release', () => {
+ const scrollX = vi.spyOn(window, 'scrollX', 'get').mockReturnValue(30);
+ const scrollY = vi.spyOn(window, 'scrollY', 'get').mockReturnValue(250);
+ vi.spyOn(window, 'scrollTo').mockImplementation(() => {});
+
+ const lock = renderHook(({locked}) => useScrollLock(locked), {
+ initialProps: {locked: true},
+ });
+
+ // Pinning the body drops the document to the top in a real browser; the
+ // hook must restore from the value it saved, not from the current one.
+ scrollX.mockReturnValue(0);
+ scrollY.mockReturnValue(0);
+ lock.rerender({locked: false});
+
+ expect(window.scrollTo).toHaveBeenCalledTimes(1);
+ expect(window.scrollTo).toHaveBeenCalledWith(30, 250);
+ });
+
+ it('keeps one lock in place across rerenders with the same value', () => {
+ vi.spyOn(window, 'scrollY', 'get').mockReturnValue(250);
+ vi.spyOn(window, 'scrollTo').mockImplementation(() => {});
+
+ const lock = renderHook(({locked}) => useScrollLock(locked), {
+ initialProps: {locked: true},
+ });
+
+ lock.rerender({locked: true});
+ lock.rerender({locked: true});
+
+ // Re-running the effect would tear the lock down and back up, restoring
+ // scroll each time.
+ expect(window.scrollTo).not.toHaveBeenCalled();
+ expect(document.body.style.position).toBe('fixed');
+ expect(document.body.style.top).toBe('-250px');
+ });
+
+ it('takes a fresh scroll snapshot when locked a second time', () => {
+ const scrollY = vi.spyOn(window, 'scrollY', 'get').mockReturnValue(100);
+ vi.spyOn(window, 'scrollTo').mockImplementation(() => {});
+
+ const lock = renderHook(({locked}) => useScrollLock(locked), {
+ initialProps: {locked: true},
+ });
+ expect(document.body.style.top).toBe('-100px');
+
+ lock.rerender({locked: false});
+ scrollY.mockReturnValue(300);
+ lock.rerender({locked: true});
+
+ expect(document.body.style.top).toBe('-300px');
+
+ lock.rerender({locked: false});
+ expect(window.scrollTo).toHaveBeenLastCalledWith(0, 300);
+ });
+
it('stays locked while a second overlay is still open, even if the first closes out of order', () => {
vi.spyOn(window, 'scrollTo').mockImplementation(() => {});
diff --git a/packages/core/src/i18n/useTranslator.test.tsx b/packages/core/src/i18n/useTranslator.test.tsx
new file mode 100644
index 0000000000..d70082b39e
--- /dev/null
+++ b/packages/core/src/i18n/useTranslator.test.tsx
@@ -0,0 +1,197 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file useTranslator.test.tsx
+ * @input Uses vitest, @testing-library/react, useTranslator hook, i18n provider
+ * @output Unit tests for the client translator bound to the provider locale
+ * @position Testing; validates useTranslator.ts. Lookup/format rules
+ * themselves live in __tests__/resolve.test.ts — this file pins the
+ * context wiring and the identity of the returned function.
+ *
+ * SYNC: When useTranslator.ts changes, update tests to match new behavior
+ */
+
+import {describe, it, expect, vi, beforeEach} from 'vitest';
+import {useState} from 'react';
+import {render, screen, fireEvent, renderHook} from '@testing-library/react';
+import {useTranslator, type TranslatorFn} from './useTranslator';
+import {InternationalizationProvider} from './InternationalizationProvider';
+import {__resetForTests} from './resolve';
+import type {MessagesByLocale, Overrides} from './types';
+
+// Module scope: the provider memoizes on prop identity, so inline object
+// literals would hand back a fresh context value on every render.
+const FR_MESSAGES: MessagesByLocale = {
+ fr: {'@astryx.pagination.next': {defaultMessage: 'Page suivante'}},
+};
+const FR_OVERRIDES: Overrides = {
+ fr: {'@astryx.pagination.next': 'Suivant'},
+};
+
+// resolve() warns once per locale+key for good; reset between tests.
+beforeEach(() => {
+ __resetForTests();
+});
+
+describe('useTranslator — resolution', () => {
+ it('resolves a shipped key to English when no provider is mounted', () => {
+ const {result} = renderHook(() => useTranslator());
+ expect(result.current('@astryx.pagination.next')).toBe('Go to next page');
+ });
+
+ it('interpolates values into the message', () => {
+ const {result} = renderHook(() => useTranslator());
+ expect(result.current('@astryx.pagination.goToPage', {page: 5})).toBe(
+ 'Go to page 5',
+ );
+ });
+
+ it('returns the key itself for a key that exists nowhere', () => {
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ const {result} = renderHook(() => useTranslator());
+
+ expect(result.current('@astryx.not.a.real.key')).toBe(
+ '@astryx.not.a.real.key',
+ );
+ expect(warn).toHaveBeenCalledWith(expect.stringContaining('missing key'));
+ warn.mockRestore();
+ });
+
+ it('uses the catalog the provider supplies for its locale', () => {
+ const {result} = renderHook(() => useTranslator(), {
+ wrapper: ({children}) => (
+ <InternationalizationProvider locale="fr" messages={FR_MESSAGES}>
+ {children}
+ </InternationalizationProvider>
+ ),
+ });
+ expect(result.current('@astryx.pagination.next')).toBe('Page suivante');
+ });
+
+ it('lets a provider override beat the provider catalog', () => {
+ const {result} = renderHook(() => useTranslator(), {
+ wrapper: ({children}) => (
+ <InternationalizationProvider
+ locale="fr"
+ messages={FR_MESSAGES}
+ overrides={FR_OVERRIDES}>
+ {children}
+ </InternationalizationProvider>
+ ),
+ });
+ expect(result.current('@astryx.pagination.next')).toBe('Suivant');
+ });
+
+ it('falls back to English for keys the provider catalog is missing', () => {
+ const {result} = renderHook(() => useTranslator(), {
+ wrapper: ({children}) => (
+ <InternationalizationProvider locale="fr" messages={FR_MESSAGES}>
+ {children}
+ </InternationalizationProvider>
+ ),
+ });
+ expect(result.current('@astryx.pagination.previous')).toBe(
+ 'Go to previous page',
+ );
+ });
+
+ it('formats numbers with the provider locale', () => {
+ const {result} = renderHook(() => useTranslator(), {
+ wrapper: ({children}) => (
+ <InternationalizationProvider locale="de-DE">
+ {children}
+ </InternationalizationProvider>
+ ),
+ });
+ expect(
+ result.current('@astryx.pagination.count', {
+ from: 1,
+ to: 10,
+ total: 1000,
+ }),
+ ).toBe('1–10 of 1.000');
+ });
+});
+
+describe('useTranslator — identity', () => {
+ function Probe({onRender}: {onRender: (t: TranslatorFn) => void}) {
+ const translate = useTranslator();
+ onRender(translate);
+ return (
+ <span data-testid="out">{translate('@astryx.pagination.next')}</span>
+ );
+ }
+
+ it('hands back the same translator across rerenders of an unchanged provider', () => {
+ const seen: TranslatorFn[] = [];
+ // Built fresh each time — passing the identical element back to rerender()
+ // makes React bail out of the subtree entirely.
+ const tree = () => (
+ <InternationalizationProvider locale="fr" overrides={FR_OVERRIDES}>
+ <Probe onRender={t => seen.push(t)} />
+ </InternationalizationProvider>
+ );
+
+ const {rerender} = render(tree());
+ rerender(tree());
+
+ expect(seen).toHaveLength(2);
+ expect(seen[1]).toBe(seen[0]);
+ });
+
+ it('hands back a new translator when the locale changes', () => {
+ const seen: TranslatorFn[] = [];
+
+ const {rerender} = render(
+ <InternationalizationProvider locale="fr" overrides={FR_OVERRIDES}>
+ <Probe onRender={t => seen.push(t)} />
+ </InternationalizationProvider>,
+ );
+ expect(screen.getByTestId('out').textContent).toBe('Suivant');
+
+ rerender(
+ <InternationalizationProvider locale="es" overrides={FR_OVERRIDES}>
+ <Probe onRender={t => seen.push(t)} />
+ </InternationalizationProvider>,
+ );
+
+ expect(seen[1]).not.toBe(seen[0]);
+ // The fr override no longer applies, so es falls through to English.
+ expect(screen.getByTestId('out').textContent).toBe('Go to next page');
+ });
+});
+
+describe('useTranslator — deferred calls', () => {
+ it('resolves against the provider locale when called from an event handler', () => {
+ function Deferred() {
+ const translate = useTranslator();
+ const [text, setText] = useState('');
+ return (
+ <div>
+ <button
+ type="button"
+ onClick={() =>
+ setText(translate('@astryx.pagination.goToPage', {page: 3}))
+ }>
+ announce
+ </button>
+ <span data-testid="out">{text}</span>
+ </div>
+ );
+ }
+
+ render(
+ <InternationalizationProvider
+ locale="fr"
+ overrides={{
+ fr: {'@astryx.pagination.goToPage': 'Aller à la page {page, number}'},
+ }}>
+ <Deferred />
+ </InternationalizationProvider>,
+ );
+
+ expect(screen.getByTestId('out').textContent).toBe('');
+ fireEvent.click(screen.getByText('announce'));
+ expect(screen.getByTestId('out').textContent).toBe('Aller à la page 3');
+ });
+});
diff --git a/packages/lab/src/Chart/Chart.test.tsx b/packages/lab/src/Chart/Chart.test.tsx
index 7a6df5d88d..53ae728e43 100644
--- a/packages/lab/src/Chart/Chart.test.tsx
+++ b/packages/lab/src/Chart/Chart.test.tsx
@@ -2,14 +2,18 @@
/**
* @file Chart.test.tsx
- * @input Uses vitest, @testing-library/react, Chart component
- * @output Unit tests for Chart accessibility (WCAG 1.1.1)
+ * @input Uses vitest, @testing-library/react, Chart component, useChart
+ * @output Unit tests for Chart accessibility (WCAG 1.1.1) plus the root's
+ * measurement gate, margin convention, and the useChart context guard
+ * (issue #4295 viz coverage)
* @position Testing; validates Chart.tsx accessible name + data-table fallback
+ * and ChartContext.ts's outside-provider error
*/
import {describe, it, expect, beforeEach, afterEach, vi} from 'vitest';
-import {render, screen, act} from '@testing-library/react';
+import {render, renderHook, screen, act} from '@testing-library/react';
import {Chart} from './Chart';
+import {useChart} from './ChartContext';
const data = [
{month: 'Jan', revenue: 100, profit: 20},
@@ -124,3 +128,60 @@ describe('Chart data table fallback', () => {
expect(screen.queryByRole('table')).not.toBeInTheDocument();
});
});
+
+describe('Chart measurement gate', () => {
+ it('renders no svg until the container reports a width', () => {
+ const {container} = render(
+ <Chart data={data} xKey="month" yKeys={['revenue']}>
+ <circle data-testid="mark" />
+ </Chart>,
+ );
+
+ expect(container.querySelector('svg')).toBeNull();
+ expect(screen.queryByTestId('mark')).toBeNull();
+ });
+
+ it('renders the svg at the reported width and the default height once measured', () => {
+ const {container} = render(
+ <Chart data={data} xKey="month" yKeys={['revenue']}>
+ <circle data-testid="mark" />
+ </Chart>,
+ );
+
+ reportWidth(464);
+
+ const svg = container.querySelector('svg');
+ expect(svg).not.toBeNull();
+ expect(svg).toHaveAttribute('width', '464');
+ expect(svg).toHaveAttribute('height', '300');
+ });
+
+ it('renders children inside the margin-translated group', () => {
+ render(
+ <Chart data={data} xKey="month" yKeys={['revenue']}>
+ <circle data-testid="mark" />
+ </Chart>,
+ );
+
+ reportWidth(464);
+
+ // Default margins: left 48, top 16 (d3 margin convention)
+ const mark = screen.getByTestId('mark');
+ expect(mark.closest('g')).toHaveAttribute('transform', 'translate(48,16)');
+ });
+});
+
+describe('useChart', () => {
+ it('throws a clear error when used outside <Chart>', () => {
+ // React reports the uncaught render error via console.error; keep the
+ // test output quiet.
+ const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
+ try {
+ expect(() => renderHook(() => useChart())).toThrow(
+ 'Chart components must be used inside <Chart>',
+ );
+ } finally {
+ errorSpy.mockRestore();
+ }
+ });
+});
diff --git a/packages/lab/src/Chart/ChartArea.test.tsx b/packages/lab/src/Chart/ChartArea.test.tsx
new file mode 100644
index 0000000000..af2df98329
--- /dev/null
+++ b/packages/lab/src/Chart/ChartArea.test.tsx
@@ -0,0 +1,108 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file ChartArea.test.tsx
+ * @input Renders ChartArea inside Chart with a stubbed ResizeObserver
+ * @output Render-smoke coverage for area bands: fill path, edge stroke, baseline fallback, empty guard (#4295)
+ * @position Colocated test for ChartArea.tsx
+ */
+
+import {describe, it, expect, beforeEach, afterEach, vi} from 'vitest';
+import {render, act} from '@testing-library/react';
+import {Chart} from './Chart';
+import {ChartArea} from './ChartArea';
+
+const data = [
+ {month: 'Jan', upper: 30, lower: 10, mean: 20},
+ {month: 'Feb', upper: 40, lower: 20, mean: 30},
+ {month: 'Mar', upper: 50, lower: 30, mean: 40},
+];
+
+// Capture the ResizeObserver callback so tests can drive the reported width.
+let resizeCallback: ResizeObserverCallback | undefined;
+
+beforeEach(() => {
+ resizeCallback = undefined;
+ vi.stubGlobal(
+ 'ResizeObserver',
+ class {
+ constructor(cb: ResizeObserverCallback) {
+ resizeCallback = cb;
+ }
+ observe() {}
+ unobserve() {}
+ disconnect() {}
+ },
+ );
+});
+
+afterEach(() => {
+ vi.unstubAllGlobals();
+});
+
+function reportWidth(width: number) {
+ act(() => {
+ resizeCallback?.(
+ [{contentRect: {width}} as unknown as ResizeObserverEntry],
+ {} as ResizeObserver,
+ );
+ });
+}
+
+describe('ChartArea', () => {
+ it('renders a single filled band between yUpper and yLower', () => {
+ const {container} = render(
+ <Chart data={data} xKey="month" yKeys={['upper', 'lower']}>
+ <ChartArea yUpper="upper" yLower="lower" color="#0064E0" />
+ </Chart>,
+ );
+
+ reportWidth(464);
+
+ const paths = container.querySelectorAll('path');
+ expect(paths).toHaveLength(1);
+ expect(paths[0].getAttribute('d')).toMatch(/^M/);
+ expect(paths[0]).toHaveAttribute('fill', '#0064E0');
+ // Default opacity
+ expect(paths[0]).toHaveAttribute('fill-opacity', '0.2');
+ });
+
+ it('adds an edge stroke path when stroke is set', () => {
+ const {container} = render(
+ <Chart data={data} xKey="month" yKeys={['upper', 'lower']}>
+ <ChartArea yUpper="upper" yLower="lower" color="#0064E0" stroke />
+ </Chart>,
+ );
+
+ reportWidth(464);
+
+ const paths = container.querySelectorAll('path');
+ expect(paths).toHaveLength(2);
+ expect(paths[1]).toHaveAttribute('fill', 'none');
+ expect(paths[1]).toHaveAttribute('stroke', '#0064E0');
+ });
+
+ it('falls back to the baseline key for the missing bound', () => {
+ const {container} = render(
+ <Chart data={data} xKey="month" yKeys={['upper', 'mean']}>
+ <ChartArea yUpper="upper" baseline="mean" color="#0064E0" />
+ </Chart>,
+ );
+
+ reportWidth(464);
+
+ expect(container.querySelectorAll('path')).toHaveLength(1);
+ });
+
+ it('renders nothing when no bound keys are given', () => {
+ const {container} = render(
+ <Chart data={data} xKey="month" yKeys={['upper']}>
+ <ChartArea color="#0064E0" />
+ </Chart>,
+ );
+
+ reportWidth(464);
+
+ expect(container.querySelectorAll('path')).toHaveLength(0);
+ });
+});
diff --git a/packages/lab/src/Chart/ChartAxis.test.tsx b/packages/lab/src/Chart/ChartAxis.test.tsx
new file mode 100644
index 0000000000..f7bca84dde
--- /dev/null
+++ b/packages/lab/src/Chart/ChartAxis.test.tsx
@@ -0,0 +1,115 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file ChartAxis.test.tsx
+ * @input Renders ChartAxis inside Chart with a stubbed ResizeObserver
+ * @output Render-smoke coverage for axes: band ticks, numeric ticks, maxTicks skip, truncation (#4295)
+ * @position Colocated test for ChartAxis.tsx
+ */
+
+import {describe, it, expect, beforeEach, afterEach, vi} from 'vitest';
+import {render, act} from '@testing-library/react';
+import {Chart} from './Chart';
+import {ChartAxis} from './ChartAxis';
+
+const data = [
+ {month: 'Jan', revenue: 10},
+ {month: 'Feb', revenue: 20},
+ {month: 'Mar', revenue: 30},
+];
+
+// Capture the ResizeObserver callback so tests can drive the reported width.
+let resizeCallback: ResizeObserverCallback | undefined;
+
+beforeEach(() => {
+ resizeCallback = undefined;
+ vi.stubGlobal(
+ 'ResizeObserver',
+ class {
+ constructor(cb: ResizeObserverCallback) {
+ resizeCallback = cb;
+ }
+ observe() {}
+ unobserve() {}
+ disconnect() {}
+ },
+ );
+});
+
+afterEach(() => {
+ vi.unstubAllGlobals();
+});
+
+function reportWidth(width: number) {
+ act(() => {
+ resizeCallback?.(
+ [{contentRect: {width}} as unknown as ResizeObserverEntry],
+ {} as ResizeObserver,
+ );
+ });
+}
+
+function labelsOf(container: HTMLElement): string[] {
+ return Array.from(container.querySelectorAll('text')).map(
+ t => t.textContent ?? '',
+ );
+}
+
+describe('ChartAxis', () => {
+ it('renders one tick label per category on the bottom band axis', () => {
+ const {container} = render(
+ <Chart data={data} xKey="month" yKeys={['revenue']}>
+ <ChartAxis position="bottom" />
+ </Chart>,
+ );
+
+ reportWidth(464);
+
+ expect(labelsOf(container)).toEqual(['Jan', 'Feb', 'Mar']);
+ // One axis line plus one tick line per category.
+ expect(container.querySelectorAll('line')).toHaveLength(4);
+ });
+
+ it('renders numeric tick labels on the left axis', () => {
+ const {container} = render(
+ <Chart data={data} xKey="month" yKeys={['revenue']} yDomain={[0, 4]}>
+ <ChartAxis position="left" />
+ </Chart>,
+ );
+
+ reportWidth(464);
+
+ // d3 ticks(5) on an explicit [0, 4] domain
+ expect(labelsOf(container)).toEqual(['0', '1', '2', '3', '4']);
+ expect(container.querySelectorAll('line')).toHaveLength(6);
+ });
+
+ it('skips labels evenly when maxTicks is exceeded', () => {
+ const wide = ['A', 'B', 'C', 'D', 'E'].map(cat => ({cat, value: 1}));
+
+ const {container} = render(
+ <Chart data={wide} xKey="cat" yKeys={['value']}>
+ <ChartAxis position="bottom" maxTicks={3} />
+ </Chart>,
+ );
+
+ reportWidth(464);
+
+ // ceil(5 / 3) = 2 → every second category
+ expect(labelsOf(container)).toEqual(['A', 'C', 'E']);
+ });
+
+ it('truncates long labels with an ellipsis', () => {
+ const long = [{month: 'January', revenue: 10}];
+
+ const {container} = render(
+ <Chart data={long} xKey="month" yKeys={['revenue']}>
+ <ChartAxis position="bottom" truncate={3} />
+ </Chart>,
+ );
+
+ reportWidth(464);
+
+ expect(labelsOf(container)).toEqual(['Jan…']);
+ });
+});
diff --git a/packages/lab/src/Chart/ChartBar.test.tsx b/packages/lab/src/Chart/ChartBar.test.tsx
new file mode 100644
index 0000000000..b02102a70e
--- /dev/null
+++ b/packages/lab/src/Chart/ChartBar.test.tsx
@@ -0,0 +1,129 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file ChartBar.test.tsx
+ * @input Renders ChartBar inside Chart with a stubbed ResizeObserver
+ * @output Render-smoke coverage for bar marks: rect-per-datum, zero-line growth, band-scale guard (#4295)
+ * @position Colocated test for ChartBar.tsx
+ */
+
+import {describe, it, expect, beforeEach, afterEach, vi} from 'vitest';
+import {render, act} from '@testing-library/react';
+import {Chart} from './Chart';
+import {ChartBar} from './ChartBar';
+
+const data = [
+ {month: 'Jan', revenue: 10},
+ {month: 'Feb', revenue: 20},
+ {month: 'Mar', revenue: 30},
+];
+
+// Capture the ResizeObserver callback so tests can drive the reported width.
+let resizeCallback: ResizeObserverCallback | undefined;
+
+beforeEach(() => {
+ resizeCallback = undefined;
+ vi.stubGlobal(
+ 'ResizeObserver',
+ class {
+ constructor(cb: ResizeObserverCallback) {
+ resizeCallback = cb;
+ }
+ observe() {}
+ unobserve() {}
+ disconnect() {}
+ },
+ );
+});
+
+afterEach(() => {
+ vi.unstubAllGlobals();
+});
+
+function reportWidth(width: number) {
+ act(() => {
+ resizeCallback?.(
+ [{contentRect: {width}} as unknown as ResizeObserverEntry],
+ {} as ResizeObserver,
+ );
+ });
+}
+
+// Scope rect queries to the margin-translated plot group — the chart root
+// also renders a clipPath rect inside <defs>.
+const PLOT_RECTS = 'svg > g rect';
+
+describe('ChartBar', () => {
+ it('renders one bar rect per datum', () => {
+ const {container} = render(
+ <Chart data={data} xKey="month" yKeys={['revenue']}>
+ <ChartBar dataKey="revenue" color="#0064E0" />
+ </Chart>,
+ );
+
+ reportWidth(464);
+
+ const bars = container.querySelectorAll(PLOT_RECTS);
+ expect(bars).toHaveLength(3);
+ for (const bar of bars) {
+ expect(bar).toHaveAttribute('fill', '#0064E0');
+ }
+ });
+
+ it('grows bars from the zero line for positive and negative values', () => {
+ const posNeg = [
+ {month: 'Jan', delta: 10},
+ {month: 'Feb', delta: -10},
+ ];
+
+ // innerHeight = 300 - 16 (top) - 32 (bottom) = 252. With yDomain
+ // [-20, 20] the zero line sits at 126 and ±10 maps to a 63px column.
+ const {container} = render(
+ <Chart data={posNeg} xKey="month" yKeys={['delta']} yDomain={[-20, 20]}>
+ <ChartBar dataKey="delta" color="#0064E0" />
+ </Chart>,
+ );
+
+ reportWidth(464);
+
+ const [up, down] = Array.from(container.querySelectorAll(PLOT_RECTS));
+ // Positive bar: top at the value, extends down to the zero line.
+ expect(up).toHaveAttribute('y', '63');
+ expect(up).toHaveAttribute('height', '63');
+ // Negative bar: top at the zero line, extends down to the value.
+ expect(down).toHaveAttribute('y', '126');
+ expect(down).toHaveAttribute('height', '63');
+ });
+
+ it('rounds bar corners with the radius prop', () => {
+ const {container} = render(
+ <Chart data={data} xKey="month" yKeys={['revenue']}>
+ <ChartBar dataKey="revenue" color="#0064E0" radius={8} />
+ </Chart>,
+ );
+
+ reportWidth(464);
+
+ const bar = container.querySelector(PLOT_RECTS);
+ expect(bar).toHaveAttribute('rx', '8');
+ expect(bar).toHaveAttribute('ry', '8');
+ });
+
+ it('renders nothing when the x scale is not categorical', () => {
+ const numeric = [
+ {x: 0, y: 1},
+ {x: 1, y: 2},
+ {x: 2, y: 3},
+ ];
+
+ const {container} = render(
+ <Chart data={numeric} xKey="x" yKeys={['y']}>
+ <ChartBar dataKey="y" color="#0064E0" />
+ </Chart>,
+ );
+
+ reportWidth(464);
+
+ expect(container.querySelectorAll(PLOT_RECTS)).toHaveLength(0);
+ });
+});
diff --git a/packages/lab/src/Chart/ChartBrush.test.tsx b/packages/lab/src/Chart/ChartBrush.test.tsx
new file mode 100644
index 0000000000..1af5fd1029
--- /dev/null
+++ b/packages/lab/src/Chart/ChartBrush.test.tsx
@@ -0,0 +1,83 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file ChartBrush.test.tsx
+ * @input Renders ChartBrush inside Chart with a stubbed ResizeObserver
+ * @output Render-smoke coverage for the brush's idle state. Drag gestures need
+ * createSVGPoint/getScreenCTM, which do not exist in jsdom, so they are
+ * intentionally out of scope here. (#4295)
+ * @position Colocated test for ChartBrush.tsx
+ */
+
+import {describe, it, expect, beforeEach, afterEach, vi} from 'vitest';
+import {render, act} from '@testing-library/react';
+import {Chart} from './Chart';
+import {ChartBrush} from './ChartBrush';
+
+const data = [
+ {x: 0, y: 1},
+ {x: 1, y: 2},
+ {x: 2, y: 3},
+];
+
+// Capture the ResizeObserver callback so tests can drive the reported width.
+let resizeCallback: ResizeObserverCallback | undefined;
+
+beforeEach(() => {
+ resizeCallback = undefined;
+ vi.stubGlobal(
+ 'ResizeObserver',
+ class {
+ constructor(cb: ResizeObserverCallback) {
+ resizeCallback = cb;
+ }
+ observe() {}
+ unobserve() {}
+ disconnect() {}
+ },
+ );
+});
+
+afterEach(() => {
+ vi.unstubAllGlobals();
+});
+
+function reportWidth(width: number) {
+ act(() => {
+ resizeCallback?.(
+ [{contentRect: {width}} as unknown as ResizeObserverEntry],
+ {} as ResizeObserver,
+ );
+ });
+}
+
+describe('ChartBrush', () => {
+ it('renders a full-plot drag capture surface', () => {
+ const {container} = render(
+ <Chart data={data} xKey="x" yKeys={['y']}>
+ <ChartBrush />
+ </Chart>,
+ );
+
+ reportWidth(464);
+
+ const surface = container.querySelector('svg > g rect');
+ expect(surface).not.toBeNull();
+ expect(surface).toHaveAttribute('width', '400');
+ expect(surface).toHaveAttribute('height', '252');
+ expect(surface).toHaveAttribute('fill', 'transparent');
+ });
+
+ it('shows no selection rectangle before any drag', () => {
+ const {container} = render(
+ <Chart data={data} xKey="x" yKeys={['y']}>
+ <ChartBrush mode="xy" />
+ </Chart>,
+ );
+
+ reportWidth(464);
+
+ // Only the capture surface — no highlight overlay.
+ expect(container.querySelectorAll('svg > g rect')).toHaveLength(1);
+ });
+});
diff --git a/packages/lab/src/Chart/ChartCandlestick.test.tsx b/packages/lab/src/Chart/ChartCandlestick.test.tsx
new file mode 100644
index 0000000000..2f414d5fa8
--- /dev/null
+++ b/packages/lab/src/Chart/ChartCandlestick.test.tsx
@@ -0,0 +1,127 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file ChartCandlestick.test.tsx
+ * @input Renders ChartCandlestick inside Chart with a stubbed ResizeObserver
+ * @output Render-smoke coverage for candlesticks: default and bar variants, up/down colors, band guard (#4295)
+ * @position Colocated test for ChartCandlestick.tsx
+ */
+
+import {describe, it, expect, beforeEach, afterEach, vi} from 'vitest';
+import {render, act} from '@testing-library/react';
+import {Chart} from './Chart';
+import {ChartCandlestick} from './ChartCandlestick';
+
+const ohlc = [
+ {day: 'Mon', high: 90, low: 10, open: 30, close: 70}, // up
+ {day: 'Tue', high: 80, low: 20, open: 60, close: 40}, // down
+ {day: 'Wed', high: 95, low: 5, open: 50, close: 50}, // flat counts as up
+];
+
+// Capture the ResizeObserver callback so tests can drive the reported width.
+let resizeCallback: ResizeObserverCallback | undefined;
+
+beforeEach(() => {
+ resizeCallback = undefined;
+ vi.stubGlobal(
+ 'ResizeObserver',
+ class {
+ constructor(cb: ResizeObserverCallback) {
+ resizeCallback = cb;
+ }
+ observe() {}
+ unobserve() {}
+ disconnect() {}
+ },
+ );
+});
+
+afterEach(() => {
+ vi.unstubAllGlobals();
+});
+
+function reportWidth(width: number) {
+ act(() => {
+ resizeCallback?.(
+ [{contentRect: {width}} as unknown as ResizeObserverEntry],
+ {} as ResizeObserver,
+ );
+ });
+}
+
+// Scope rect queries to the margin-translated plot group — the chart root
+// also renders a clipPath rect inside <defs>.
+const PLOT_RECTS = 'svg > g rect';
+
+describe('ChartCandlestick', () => {
+ it('renders two whiskers and a body rect per datum in the default variant', () => {
+ const {container} = render(
+ <Chart data={ohlc} xKey="day" yKeys={['high', 'low']}>
+ <ChartCandlestick high="high" low="low" open="open" close="close" />
+ </Chart>,
+ );
+
+ reportWidth(464);
+
+ expect(container.querySelectorAll('line')).toHaveLength(6);
+ expect(container.querySelectorAll(PLOT_RECTS)).toHaveLength(3);
+ });
+
+ it('renders a range line and open/close ticks per datum in the bar variant', () => {
+ const {container} = render(
+ <Chart data={ohlc} xKey="day" yKeys={['high', 'low']}>
+ <ChartCandlestick
+ variant="bar"
+ high="high"
+ low="low"
+ open="open"
+ close="close"
+ />
+ </Chart>,
+ );
+
+ reportWidth(464);
+
+ expect(container.querySelectorAll('line')).toHaveLength(9);
+ expect(container.querySelectorAll(PLOT_RECTS)).toHaveLength(0);
+ });
+
+ it('colors rising and falling candles with upColor and downColor', () => {
+ const {container} = render(
+ <Chart data={ohlc} xKey="day" yKeys={['high', 'low']}>
+ <ChartCandlestick
+ high="high"
+ low="low"
+ open="open"
+ close="close"
+ upColor="#00aa00"
+ downColor="#cc0000"
+ />
+ </Chart>,
+ );
+
+ reportWidth(464);
+
+ const bodies = Array.from(container.querySelectorAll(PLOT_RECTS));
+ expect(bodies.map(b => b.getAttribute('fill'))).toEqual([
+ '#00aa00', // close > open
+ '#cc0000', // close < open
+ '#00aa00', // close === open counts as up
+ ]);
+ });
+
+ it('renders nothing when the x scale is not categorical', () => {
+ const numeric = [{t: 0, high: 90, low: 10, open: 30, close: 70}];
+
+ const {container} = render(
+ <Chart data={numeric} xKey="t" yKeys={['high', 'low']}>
+ <ChartCandlestick high="high" low="low" open="open" close="close" />
+ </Chart>,
+ );
+
+ reportWidth(464);
+
+ expect(container.querySelectorAll('line')).toHaveLength(0);
+ expect(container.querySelectorAll(PLOT_RECTS)).toHaveLength(0);
+ });
+});
diff --git a/packages/lab/src/Chart/ChartDot.test.tsx b/packages/lab/src/Chart/ChartDot.test.tsx
new file mode 100644
index 0000000000..a6306c6010
--- /dev/null
+++ b/packages/lab/src/Chart/ChartDot.test.tsx
@@ -0,0 +1,96 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file ChartDot.test.tsx
+ * @input Renders ChartDot inside Chart with a stubbed ResizeObserver
+ * @output Render-smoke coverage for scatter dots: circle-per-datum, linear-scale positions (#4295)
+ * @position Colocated test for ChartDot.tsx
+ */
+
+import {describe, it, expect, beforeEach, afterEach, vi} from 'vitest';
+import {render, act} from '@testing-library/react';
+import {Chart} from './Chart';
+import {ChartDot} from './ChartDot';
+
+const data = [
+ {month: 'Jan', revenue: 10},
+ {month: 'Feb', revenue: 20},
+ {month: 'Mar', revenue: 30},
+];
+
+// Capture the ResizeObserver callback so tests can drive the reported width.
+let resizeCallback: ResizeObserverCallback | undefined;
+
+beforeEach(() => {
+ resizeCallback = undefined;
+ vi.stubGlobal(
+ 'ResizeObserver',
+ class {
+ constructor(cb: ResizeObserverCallback) {
+ resizeCallback = cb;
+ }
+ observe() {}
+ unobserve() {}
+ disconnect() {}
+ },
+ );
+});
+
+afterEach(() => {
+ vi.unstubAllGlobals();
+});
+
+function reportWidth(width: number) {
+ act(() => {
+ resizeCallback?.(
+ [{contentRect: {width}} as unknown as ResizeObserverEntry],
+ {} as ResizeObserver,
+ );
+ });
+}
+
+describe('ChartDot', () => {
+ it('renders one circle per datum with the default radius', () => {
+ const {container} = render(
+ <Chart data={data} xKey="month" yKeys={['revenue']}>
+ <ChartDot dataKey="revenue" color="#0064E0" />
+ </Chart>,
+ );
+
+ reportWidth(464);
+
+ const circles = container.querySelectorAll('circle');
+ expect(circles).toHaveLength(3);
+ for (const circle of circles) {
+ expect(circle).toHaveAttribute('r', '4');
+ expect(circle).toHaveAttribute('fill', '#0064E0');
+ }
+ });
+
+ it('positions dots through the linear scales for numeric data', () => {
+ const numeric = [
+ {x: 0, y: 0},
+ {x: 1, y: 5},
+ {x: 2, y: 10},
+ ];
+
+ // Width 464 - margins (48 + 16) = 400 inner width; height 300 - (16 + 32)
+ // = 252 inner height. Explicit domains make the mapping exact.
+ const {container} = render(
+ <Chart
+ data={numeric}
+ xKey="x"
+ yKeys={['y']}
+ xDomain={[0, 2]}
+ yDomain={[0, 10]}>
+ <ChartDot dataKey="y" color="#0064E0" />
+ </Chart>,
+ );
+
+ reportWidth(464);
+
+ const circles = Array.from(container.querySelectorAll('circle'));
+ expect(circles.map(c => c.getAttribute('cx'))).toEqual(['0', '200', '400']);
+ expect(circles.map(c => c.getAttribute('cy'))).toEqual(['252', '126', '0']);
+ });
+});
diff --git a/packages/lab/src/Chart/ChartDotGL.test.tsx b/packages/lab/src/Chart/ChartDotGL.test.tsx
new file mode 100644
index 0000000000..dd21f9cc32
--- /dev/null
+++ b/packages/lab/src/Chart/ChartDotGL.test.tsx
@@ -0,0 +1,122 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file ChartDotGL.test.tsx
+ * @input Renders ChartDotGL inside Chart with stubbed ResizeObserver, WebGL-less
+ * canvas (getContext → null), and a getScreenCTM polyfill returning null (the
+ * spec value for unrendered elements — jsdom lacks the method entirely)
+ * @output Render-smoke coverage for the GL scatter: marker group, overlay canvas
+ * mount and unmount, no crash without WebGL (#4295)
+ * @position Colocated test for ChartDotGL.tsx
+ */
+
+import {describe, it, expect, beforeEach, afterEach, vi} from 'vitest';
+import {render, act} from '@testing-library/react';
+import {Chart} from './Chart';
+import {ChartDotGL} from './ChartDotGL';
+
+const data = [
+ {x: 0, y: 1},
+ {x: 1, y: 2},
+ {x: 2, y: 3},
+];
+
+// Capture the ResizeObserver callback so tests can drive the reported width.
+let resizeCallback: ResizeObserverCallback | undefined;
+
+let originalGetContext: typeof HTMLCanvasElement.prototype.getContext;
+let hadGetScreenCTM = false;
+
+beforeEach(() => {
+ resizeCallback = undefined;
+ vi.stubGlobal(
+ 'ResizeObserver',
+ class {
+ constructor(cb: ResizeObserverCallback) {
+ resizeCallback = cb;
+ }
+ observe() {}
+ unobserve() {}
+ disconnect() {}
+ },
+ );
+
+ // Behave like a browser without WebGL — the GL marks null-guard this.
+ originalGetContext = HTMLCanvasElement.prototype.getContext;
+ HTMLCanvasElement.prototype.getContext = (() =>
+ null) as typeof HTMLCanvasElement.prototype.getContext;
+
+ // jsdom has no getScreenCTM at all; a real browser returns null for
+ // undisplayed elements and mountCanvasOverSVG handles that branch.
+ const svgProto = SVGElement.prototype as unknown as {
+ getScreenCTM?: () => unknown;
+ };
+ hadGetScreenCTM = typeof svgProto.getScreenCTM === 'function';
+ if (!hadGetScreenCTM) {
+ svgProto.getScreenCTM = () => null;
+ }
+});
+
+afterEach(() => {
+ HTMLCanvasElement.prototype.getContext = originalGetContext;
+ if (!hadGetScreenCTM) {
+ delete (SVGElement.prototype as unknown as {getScreenCTM?: unknown})
+ .getScreenCTM;
+ }
+ vi.unstubAllGlobals();
+});
+
+function reportWidth(width: number) {
+ act(() => {
+ resizeCallback?.(
+ [{contentRect: {width}} as unknown as ResizeObserverEntry],
+ {} as ResizeObserver,
+ );
+ });
+}
+
+describe('ChartDotGL', () => {
+ it('mounts a positioning marker group without a WebGL context', () => {
+ const {container} = render(
+ <Chart data={data} xKey="x" yKeys={['y']}>
+ <ChartDotGL dataKey="y" color="#0064E0" />
+ </Chart>,
+ );
+
+ reportWidth(464);
+
+ expect(container.querySelector('svg > g > g')).not.toBeNull();
+ });
+
+ it('mounts the overlay canvas as a sibling of the svg', () => {
+ const {container} = render(
+ <Chart data={data} xKey="x" yKeys={['y']}>
+ <ChartDotGL dataKey="y" color="#0064E0" />
+ </Chart>,
+ );
+
+ reportWidth(464);
+
+ const canvas = container.querySelector('canvas');
+ const svg = container.querySelector('svg');
+ expect(canvas).not.toBeNull();
+ expect(canvas?.parentElement).toBe(svg?.parentElement);
+ expect(canvas?.style.position).toBe('absolute');
+ expect(canvas?.style.pointerEvents).toBe('none');
+ });
+
+ it('removes the overlay canvas on unmount', () => {
+ const {container, unmount} = render(
+ <Chart data={data} xKey="x" yKeys={['y']}>
+ <ChartDotGL dataKey="y" color="#0064E0" />
+ </Chart>,
+ );
+
+ reportWidth(464);
+ expect(container.querySelector('canvas')).not.toBeNull();
+
+ unmount();
+
+ expect(document.querySelector('canvas')).toBeNull();
+ });
+});
diff --git a/packages/lab/src/Chart/ChartErrorBar.test.tsx b/packages/lab/src/Chart/ChartErrorBar.test.tsx
new file mode 100644
index 0000000000..2f73deaa74
--- /dev/null
+++ b/packages/lab/src/Chart/ChartErrorBar.test.tsx
@@ -0,0 +1,91 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file ChartErrorBar.test.tsx
+ * @input Renders ChartErrorBar inside Chart with a stubbed ResizeObserver
+ * @output Render-smoke coverage for error bars: stem and caps per datum, bound-to-bound span (#4295)
+ * @position Colocated test for ChartErrorBar.tsx
+ */
+
+import {describe, it, expect, beforeEach, afterEach, vi} from 'vitest';
+import {render, act} from '@testing-library/react';
+import {Chart} from './Chart';
+import {ChartErrorBar} from './ChartErrorBar';
+
+const data = [
+ {month: 'Jan', upper: 30, lower: 10},
+ {month: 'Feb', upper: 40, lower: 20},
+ {month: 'Mar', upper: 50, lower: 30},
+];
+
+// Capture the ResizeObserver callback so tests can drive the reported width.
+let resizeCallback: ResizeObserverCallback | undefined;
+
+beforeEach(() => {
+ resizeCallback = undefined;
+ vi.stubGlobal(
+ 'ResizeObserver',
+ class {
+ constructor(cb: ResizeObserverCallback) {
+ resizeCallback = cb;
+ }
+ observe() {}
+ unobserve() {}
+ disconnect() {}
+ },
+ );
+});
+
+afterEach(() => {
+ vi.unstubAllGlobals();
+});
+
+function reportWidth(width: number) {
+ act(() => {
+ resizeCallback?.(
+ [{contentRect: {width}} as unknown as ResizeObserverEntry],
+ {} as ResizeObserver,
+ );
+ });
+}
+
+describe('ChartErrorBar', () => {
+ it('renders a stem and two whisker caps per datum', () => {
+ const {container} = render(
+ <Chart data={data} xKey="month" yKeys={['upper', 'lower']}>
+ <ChartErrorBar yUpper="upper" yLower="lower" />
+ </Chart>,
+ );
+
+ reportWidth(464);
+
+ expect(container.querySelectorAll('line')).toHaveLength(9);
+ });
+
+ it('spans the stem from the lower to the upper bound', () => {
+ const single = [{month: 'Jan', upper: 75, lower: 25}];
+
+ const {container} = render(
+ <Chart
+ data={single}
+ xKey="month"
+ yKeys={['upper', 'lower']}
+ yDomain={[0, 100]}>
+ <ChartErrorBar yUpper="upper" yLower="lower" />
+ </Chart>,
+ );
+
+ reportWidth(464);
+
+ // On [0, 100] over the 252px inner height: 75 → 63, 25 → 189.
+ const [stem, capTop, capBottom] = Array.from(
+ container.querySelectorAll('line'),
+ );
+ expect(stem).toHaveAttribute('y1', '63');
+ expect(stem).toHaveAttribute('y2', '189');
+ expect(capTop).toHaveAttribute('y1', '63');
+ expect(capTop).toHaveAttribute('y2', '63');
+ expect(capBottom).toHaveAttribute('y1', '189');
+ expect(capBottom).toHaveAttribute('y2', '189');
+ });
+});
diff --git a/packages/lab/src/Chart/ChartGrid.test.tsx b/packages/lab/src/Chart/ChartGrid.test.tsx
new file mode 100644
index 0000000000..94298b77cd
--- /dev/null
+++ b/packages/lab/src/Chart/ChartGrid.test.tsx
@@ -0,0 +1,100 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file ChartGrid.test.tsx
+ * @input Renders ChartGrid inside Chart with a stubbed ResizeObserver
+ * @output Render-smoke coverage for grid lines: horizontal ticks, vertical band centers, off state (#4295)
+ * @position Colocated test for ChartGrid.tsx
+ */
+
+import {describe, it, expect, beforeEach, afterEach, vi} from 'vitest';
+import {render, act} from '@testing-library/react';
+import {Chart} from './Chart';
+import {ChartGrid} from './ChartGrid';
+
+const data = [
+ {month: 'Jan', revenue: 1},
+ {month: 'Feb', revenue: 2},
+ {month: 'Mar', revenue: 4},
+];
+
+// Capture the ResizeObserver callback so tests can drive the reported width.
+let resizeCallback: ResizeObserverCallback | undefined;
+
+beforeEach(() => {
+ resizeCallback = undefined;
+ vi.stubGlobal(
+ 'ResizeObserver',
+ class {
+ constructor(cb: ResizeObserverCallback) {
+ resizeCallback = cb;
+ }
+ observe() {}
+ unobserve() {}
+ disconnect() {}
+ },
+ );
+});
+
+afterEach(() => {
+ vi.unstubAllGlobals();
+});
+
+function reportWidth(width: number) {
+ act(() => {
+ resizeCallback?.(
+ [{contentRect: {width}} as unknown as ResizeObserverEntry],
+ {} as ResizeObserver,
+ );
+ });
+}
+
+describe('ChartGrid', () => {
+ it('renders a horizontal line per y tick by default', () => {
+ const {container} = render(
+ <Chart data={data} xKey="month" yKeys={['revenue']} yDomain={[0, 4]}>
+ <ChartGrid />
+ </Chart>,
+ );
+
+ reportWidth(464);
+
+ // d3 ticks(5) on [0, 4] → 0..4; lines span the 400px inner width.
+ const lines = container.querySelectorAll('line');
+ expect(lines).toHaveLength(5);
+ for (const line of lines) {
+ expect(line).toHaveAttribute('x1', '0');
+ expect(line).toHaveAttribute('x2', '400');
+ }
+ });
+
+ it('renders a vertical line per band center when vertical is on', () => {
+ const {container} = render(
+ <Chart data={data} xKey="month" yKeys={['revenue']}>
+ <ChartGrid horizontal={false} vertical />
+ </Chart>,
+ );
+
+ reportWidth(464);
+
+ // One line per category, spanning the 252px inner height.
+ const lines = container.querySelectorAll('line');
+ expect(lines).toHaveLength(3);
+ for (const line of lines) {
+ expect(line).toHaveAttribute('y1', '0');
+ expect(line).toHaveAttribute('y2', '252');
+ }
+ });
+
+ it('renders no lines when both orientations are off', () => {
+ const {container} = render(
+ <Chart data={data} xKey="month" yKeys={['revenue']}>
+ <ChartGrid horizontal={false} />
+ </Chart>,
+ );
+
+ reportWidth(464);
+
+ expect(container.querySelectorAll('line')).toHaveLength(0);
+ });
+});
diff --git a/packages/lab/src/Chart/ChartHeatmapGL.test.tsx b/packages/lab/src/Chart/ChartHeatmapGL.test.tsx
new file mode 100644
index 0000000000..7f3c0720da
--- /dev/null
+++ b/packages/lab/src/Chart/ChartHeatmapGL.test.tsx
@@ -0,0 +1,117 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file ChartHeatmapGL.test.tsx
+ * @input Renders ChartHeatmapGL inside Chart with stubbed ResizeObserver, WebGL-less
+ * canvas (getContext → null), and a getScreenCTM polyfill returning null (the
+ * spec value for unrendered elements — jsdom lacks the method entirely)
+ * @output Render-smoke coverage for the GL heatmap: marker group and overlay canvas
+ * mount without a WebGL context (#4295)
+ * @position Colocated test for ChartHeatmapGL.tsx
+ */
+
+import {describe, it, expect, beforeEach, afterEach, vi} from 'vitest';
+import {render, act} from '@testing-library/react';
+import {Chart} from './Chart';
+import {ChartHeatmapGL} from './ChartHeatmapGL';
+
+const data = [
+ {month: 'Jan', row: 'A', value: 1},
+ {month: 'Jan', row: 'B', value: 2},
+ {month: 'Feb', row: 'A', value: 3},
+ {month: 'Feb', row: 'B', value: 4},
+];
+
+// Capture the ResizeObserver callback so tests can drive the reported width.
+let resizeCallback: ResizeObserverCallback | undefined;
+
+let originalGetContext: typeof HTMLCanvasElement.prototype.getContext;
+let hadGetScreenCTM = false;
+
+beforeEach(() => {
+ resizeCallback = undefined;
+ vi.stubGlobal(
+ 'ResizeObserver',
+ class {
+ constructor(cb: ResizeObserverCallback) {
+ resizeCallback = cb;
+ }
+ observe() {}
+ unobserve() {}
+ disconnect() {}
+ },
+ );
+
+ // Behave like a browser without WebGL — the GL marks null-guard this.
+ originalGetContext = HTMLCanvasElement.prototype.getContext;
+ HTMLCanvasElement.prototype.getContext = (() =>
+ null) as typeof HTMLCanvasElement.prototype.getContext;
+
+ // jsdom has no getScreenCTM at all; a real browser returns null for
+ // undisplayed elements and mountCanvasOverSVG handles that branch.
+ const svgProto = SVGElement.prototype as unknown as {
+ getScreenCTM?: () => unknown;
+ };
+ hadGetScreenCTM = typeof svgProto.getScreenCTM === 'function';
+ if (!hadGetScreenCTM) {
+ svgProto.getScreenCTM = () => null;
+ }
+});
+
+afterEach(() => {
+ HTMLCanvasElement.prototype.getContext = originalGetContext;
+ if (!hadGetScreenCTM) {
+ delete (SVGElement.prototype as unknown as {getScreenCTM?: unknown})
+ .getScreenCTM;
+ }
+ vi.unstubAllGlobals();
+});
+
+function reportWidth(width: number) {
+ act(() => {
+ resizeCallback?.(
+ [{contentRect: {width}} as unknown as ResizeObserverEntry],
+ {} as ResizeObserver,
+ );
+ });
+}
+
+describe('ChartHeatmapGL', () => {
+ it('mounts a positioning marker group without a WebGL context', () => {
+ const {container} = render(
+ <Chart data={data} xKey="month" yKeys={['value']}>
+ <ChartHeatmapGL
+ xKey="month"
+ yKey="row"
+ valueKey="value"
+ colorRange={['#000000', '#ffffff']}
+ />
+ </Chart>,
+ );
+
+ reportWidth(464);
+
+ expect(container.querySelector('svg > g > g')).not.toBeNull();
+ });
+
+ it('mounts the overlay canvas as a sibling of the svg', () => {
+ const {container} = render(
+ <Chart data={data} xKey="month" yKeys={['value']}>
+ <ChartHeatmapGL
+ xKey="month"
+ yKey="row"
+ valueKey="value"
+ colorRange={['#000000', '#ffffff']}
+ />
+ </Chart>,
+ );
+
+ reportWidth(464);
+
+ const canvas = container.querySelector('canvas');
+ const svg = container.querySelector('svg');
+ expect(canvas).not.toBeNull();
+ expect(canvas?.parentElement).toBe(svg?.parentElement);
+ expect(canvas?.style.pointerEvents).toBe('none');
+ });
+});
diff --git a/packages/lab/src/Chart/ChartLegend.test.tsx b/packages/lab/src/Chart/ChartLegend.test.tsx
new file mode 100644
index 0000000000..39bb3e1ca3
--- /dev/null
+++ b/packages/lab/src/Chart/ChartLegend.test.tsx
@@ -0,0 +1,103 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file ChartLegend.test.tsx
+ * @input Renders ChartLegend inside Chart with a stubbed ResizeObserver
+ * @output Render-smoke coverage for legends: discrete swatches, gradient bar with ticks, empty guard (#4295)
+ * @position Colocated test for ChartLegend.tsx
+ */
+
+import {describe, it, expect, beforeEach, afterEach, vi} from 'vitest';
+import {render, screen, act} from '@testing-library/react';
+import {Chart} from './Chart';
+import {ChartLegend} from './ChartLegend';
+
+const data = [
+ {month: 'Jan', revenue: 10},
+ {month: 'Feb', revenue: 20},
+ {month: 'Mar', revenue: 30},
+];
+
+// Capture the ResizeObserver callback so tests can drive the reported width.
+let resizeCallback: ResizeObserverCallback | undefined;
+
+beforeEach(() => {
+ resizeCallback = undefined;
+ vi.stubGlobal(
+ 'ResizeObserver',
+ class {
+ constructor(cb: ResizeObserverCallback) {
+ resizeCallback = cb;
+ }
+ observe() {}
+ unobserve() {}
+ disconnect() {}
+ },
+ );
+});
+
+afterEach(() => {
+ vi.unstubAllGlobals();
+});
+
+function reportWidth(width: number) {
+ act(() => {
+ resizeCallback?.(
+ [{contentRect: {width}} as unknown as ResizeObserverEntry],
+ {} as ResizeObserver,
+ );
+ });
+}
+
+describe('ChartLegend', () => {
+ it('renders a label per discrete item', () => {
+ const {container} = render(
+ <Chart data={data} xKey="month" yKeys={['revenue']}>
+ <ChartLegend
+ items={[
+ {label: 'Revenue', color: '#0064E0'},
+ {label: 'Expenses', color: '#E00064'},
+ ]}
+ />
+ </Chart>,
+ );
+
+ reportWidth(464);
+
+ expect(container.querySelectorAll('foreignObject')).toHaveLength(1);
+ expect(screen.getByText('Revenue')).toBeInTheDocument();
+ expect(screen.getByText('Expenses')).toBeInTheDocument();
+ });
+
+ it('renders a gradient bar with evenly spaced domain tick labels', () => {
+ render(
+ <Chart data={data} xKey="month" yKeys={['revenue']}>
+ <ChartLegend
+ gradient={['#000000', '#ffffff']}
+ domain={[0, 100]}
+ label="Temperature"
+ />
+ </Chart>,
+ );
+
+ reportWidth(464);
+
+ expect(screen.getByText('Temperature')).toBeInTheDocument();
+ // Default 3 ticks across [0, 100]
+ expect(screen.getByText('0')).toBeInTheDocument();
+ expect(screen.getByText('50')).toBeInTheDocument();
+ expect(screen.getByText('100')).toBeInTheDocument();
+ });
+
+ it('renders nothing without items or a gradient', () => {
+ const {container} = render(
+ <Chart data={data} xKey="month" yKeys={['revenue']}>
+ <ChartLegend />
+ </Chart>,
+ );
+
+ reportWidth(464);
+
+ expect(container.querySelector('foreignObject')).toBeNull();
+ });
+});
diff --git a/packages/lab/src/Chart/ChartLine.test.tsx b/packages/lab/src/Chart/ChartLine.test.tsx
new file mode 100644
index 0000000000..56b5e8b7ce
--- /dev/null
+++ b/packages/lab/src/Chart/ChartLine.test.tsx
@@ -0,0 +1,102 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file ChartLine.test.tsx
+ * @input Renders ChartLine inside Chart with a stubbed ResizeObserver
+ * @output Render-smoke coverage for line marks: single path, optional dots, stroke props (#4295)
+ * @position Colocated test for ChartLine.tsx
+ */
+
+import {describe, it, expect, beforeEach, afterEach, vi} from 'vitest';
+import {render, act} from '@testing-library/react';
+import {Chart} from './Chart';
+import {ChartLine} from './ChartLine';
+
+const data = [
+ {month: 'Jan', revenue: 10},
+ {month: 'Feb', revenue: 20},
+ {month: 'Mar', revenue: 30},
+];
+
+// Capture the ResizeObserver callback so tests can drive the reported width.
+let resizeCallback: ResizeObserverCallback | undefined;
+
+beforeEach(() => {
+ resizeCallback = undefined;
+ vi.stubGlobal(
+ 'ResizeObserver',
+ class {
+ constructor(cb: ResizeObserverCallback) {
+ resizeCallback = cb;
+ }
+ observe() {}
+ unobserve() {}
+ disconnect() {}
+ },
+ );
+});
+
+afterEach(() => {
+ vi.unstubAllGlobals();
+});
+
+function reportWidth(width: number) {
+ act(() => {
+ resizeCallback?.(
+ [{contentRect: {width}} as unknown as ResizeObserverEntry],
+ {} as ResizeObserver,
+ );
+ });
+}
+
+describe('ChartLine', () => {
+ it('renders a single stroked path through the data and no dots by default', () => {
+ const {container} = render(
+ <Chart data={data} xKey="month" yKeys={['revenue']}>
+ <ChartLine dataKey="revenue" color="#0064E0" />
+ </Chart>,
+ );
+
+ reportWidth(464);
+
+ const paths = container.querySelectorAll('path');
+ expect(paths).toHaveLength(1);
+ expect(paths[0].getAttribute('d')).toMatch(/^M/);
+ expect(paths[0]).toHaveAttribute('fill', 'none');
+ expect(paths[0]).toHaveAttribute('stroke', '#0064E0');
+ expect(container.querySelectorAll('circle')).toHaveLength(0);
+ });
+
+ it('marks each datum with a dot when dots is set', () => {
+ const {container} = render(
+ <Chart data={data} xKey="month" yKeys={['revenue']}>
+ <ChartLine dataKey="revenue" color="#0064E0" dots />
+ </Chart>,
+ );
+
+ reportWidth(464);
+
+ const circles = container.querySelectorAll('circle');
+ expect(circles).toHaveLength(3);
+ for (const circle of circles) {
+ // Default dotRadius
+ expect(circle).toHaveAttribute('r', '3');
+ expect(circle).toHaveAttribute('fill', '#0064E0');
+ }
+ });
+
+ it('applies the strokeWidth prop to the line', () => {
+ const {container} = render(
+ <Chart data={data} xKey="month" yKeys={['revenue']}>
+ <ChartLine dataKey="revenue" color="#0064E0" strokeWidth={5} />
+ </Chart>,
+ );
+
+ reportWidth(464);
+
+ expect(container.querySelector('path')).toHaveAttribute(
+ 'stroke-width',
+ '5',
+ );
+ });
+});
diff --git a/packages/lab/src/Chart/ChartReferenceLine.test.tsx b/packages/lab/src/Chart/ChartReferenceLine.test.tsx
new file mode 100644
index 0000000000..0c9f5fa40e
--- /dev/null
+++ b/packages/lab/src/Chart/ChartReferenceLine.test.tsx
@@ -0,0 +1,120 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file ChartReferenceLine.test.tsx
+ * @input Renders ChartReferenceLine inside Chart with a stubbed ResizeObserver
+ * @output Render-smoke coverage for reference lines: y line, badge label, x line, band-scale guard (#4295)
+ * @position Colocated test for ChartReferenceLine.tsx
+ */
+
+import {describe, it, expect, beforeEach, afterEach, vi} from 'vitest';
+import {render, screen, act} from '@testing-library/react';
+import {Chart} from './Chart';
+import {ChartReferenceLine} from './ChartReferenceLine';
+
+const data = [
+ {month: 'Jan', revenue: 10},
+ {month: 'Feb', revenue: 20},
+ {month: 'Mar', revenue: 30},
+];
+
+// Capture the ResizeObserver callback so tests can drive the reported width.
+let resizeCallback: ResizeObserverCallback | undefined;
+
+beforeEach(() => {
+ resizeCallback = undefined;
+ vi.stubGlobal(
+ 'ResizeObserver',
+ class {
+ constructor(cb: ResizeObserverCallback) {
+ resizeCallback = cb;
+ }
+ observe() {}
+ unobserve() {}
+ disconnect() {}
+ },
+ );
+});
+
+afterEach(() => {
+ vi.unstubAllGlobals();
+});
+
+function reportWidth(width: number) {
+ act(() => {
+ resizeCallback?.(
+ [{contentRect: {width}} as unknown as ResizeObserverEntry],
+ {} as ResizeObserver,
+ );
+ });
+}
+
+describe('ChartReferenceLine', () => {
+ it('renders a horizontal line across the plot at the y value', () => {
+ const {container} = render(
+ <Chart data={data} xKey="month" yKeys={['revenue']} yDomain={[0, 100]}>
+ <ChartReferenceLine y={50} />
+ </Chart>,
+ );
+
+ reportWidth(464);
+
+ // y=50 on [0, 100] over the 252px inner height → 126
+ const lines = container.querySelectorAll('line');
+ expect(lines).toHaveLength(1);
+ expect(lines[0]).toHaveAttribute('x1', '0');
+ expect(lines[0]).toHaveAttribute('x2', '400');
+ expect(lines[0]).toHaveAttribute('y1', '126');
+ expect(lines[0]).toHaveAttribute('y2', '126');
+ });
+
+ it('renders a badge with the label text when label is set', () => {
+ const {container} = render(
+ <Chart data={data} xKey="month" yKeys={['revenue']} yDomain={[0, 100]}>
+ <ChartReferenceLine y={50} label="Target" />
+ </Chart>,
+ );
+
+ reportWidth(464);
+
+ expect(screen.getByText('Target')).toBeInTheDocument();
+ // Badge background behind the label (defs clip rect is outside the plot g)
+ expect(container.querySelectorAll('svg > g rect')).toHaveLength(1);
+ });
+
+ it('renders a vertical line at the x value on a linear scale', () => {
+ const numeric = [
+ {x: 0, y: 1},
+ {x: 1, y: 2},
+ {x: 2, y: 3},
+ ];
+
+ const {container} = render(
+ <Chart data={numeric} xKey="x" yKeys={['y']} xDomain={[0, 2]}>
+ <ChartReferenceLine x={1} />
+ </Chart>,
+ );
+
+ reportWidth(464);
+
+ // x=1 on [0, 2] over the 400px inner width → 200
+ const lines = container.querySelectorAll('line');
+ expect(lines).toHaveLength(1);
+ expect(lines[0]).toHaveAttribute('x1', '200');
+ expect(lines[0]).toHaveAttribute('x2', '200');
+ expect(lines[0]).toHaveAttribute('y1', '0');
+ expect(lines[0]).toHaveAttribute('y2', '252');
+ });
+
+ it('renders nothing for an x value on a categorical scale', () => {
+ const {container} = render(
+ <Chart data={data} xKey="month" yKeys={['revenue']}>
+ <ChartReferenceLine x={1} />
+ </Chart>,
+ );
+
+ reportWidth(464);
+
+ expect(container.querySelectorAll('line')).toHaveLength(0);
+ });
+});
diff --git a/packages/lab/src/Chart/ChartSelect.test.tsx b/packages/lab/src/Chart/ChartSelect.test.tsx
new file mode 100644
index 0000000000..08f206c006
--- /dev/null
+++ b/packages/lab/src/Chart/ChartSelect.test.tsx
@@ -0,0 +1,101 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file ChartSelect.test.tsx
+ * @input Renders ChartSelect inside Chart with a stubbed ResizeObserver
+ * @output Render-smoke coverage for selection: capture surface, controlled selection rings,
+ * out-of-range guard. Tap gestures need createSVGPoint/getScreenCTM, which do not
+ * exist in jsdom, so they are intentionally out of scope here. (#4295)
+ * @position Colocated test for ChartSelect.tsx
+ */
+
+import {describe, it, expect, beforeEach, afterEach, vi} from 'vitest';
+import {render, act} from '@testing-library/react';
+import {Chart} from './Chart';
+import {ChartSelect} from './ChartSelect';
+
+const data = [
+ {month: 'Jan', revenue: 10},
+ {month: 'Feb', revenue: 20},
+ {month: 'Mar', revenue: 30},
+];
+
+// Capture the ResizeObserver callback so tests can drive the reported width.
+let resizeCallback: ResizeObserverCallback | undefined;
+
+beforeEach(() => {
+ resizeCallback = undefined;
+ vi.stubGlobal(
+ 'ResizeObserver',
+ class {
+ constructor(cb: ResizeObserverCallback) {
+ resizeCallback = cb;
+ }
+ observe() {}
+ unobserve() {}
+ disconnect() {}
+ },
+ );
+});
+
+afterEach(() => {
+ vi.unstubAllGlobals();
+});
+
+function reportWidth(width: number) {
+ act(() => {
+ resizeCallback?.(
+ [{contentRect: {width}} as unknown as ResizeObserverEntry],
+ {} as ResizeObserver,
+ );
+ });
+}
+
+describe('ChartSelect', () => {
+ it('renders a full-plot tap capture surface and no rings by default', () => {
+ const {container} = render(
+ <Chart data={data} xKey="month" yKeys={['revenue']}>
+ <ChartSelect />
+ </Chart>,
+ );
+
+ reportWidth(464);
+
+ const surface = container.querySelector('svg > g rect');
+ expect(surface).not.toBeNull();
+ expect(surface).toHaveAttribute('width', '400');
+ expect(surface).toHaveAttribute('height', '252');
+ expect(container.querySelectorAll('circle')).toHaveLength(0);
+ });
+
+ it('rings each controlled selected data point', () => {
+ const {container} = render(
+ <Chart data={data} xKey="month" yKeys={['revenue']}>
+ <ChartSelect selected={[0, 2]} color="#0064E0" />
+ </Chart>,
+ );
+
+ reportWidth(464);
+
+ const rings = container.querySelectorAll('circle');
+ expect(rings).toHaveLength(2);
+ for (const ring of rings) {
+ expect(ring).toHaveAttribute('fill', 'none');
+ expect(ring).toHaveAttribute('stroke', '#0064E0');
+ // Default radius
+ expect(ring).toHaveAttribute('r', '6');
+ }
+ });
+
+ it('ignores out-of-range selection indices', () => {
+ const {container} = render(
+ <Chart data={data} xKey="month" yKeys={['revenue']}>
+ <ChartSelect selected={[-1, 5]} />
+ </Chart>,
+ );
+
+ reportWidth(464);
+
+ expect(container.querySelectorAll('circle')).toHaveLength(0);
+ });
+});
diff --git a/packages/lab/src/Chart/ChartStreamGL.test.tsx b/packages/lab/src/Chart/ChartStreamGL.test.tsx
new file mode 100644
index 0000000000..1c1b02b353
--- /dev/null
+++ b/packages/lab/src/Chart/ChartStreamGL.test.tsx
@@ -0,0 +1,135 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file ChartStreamGL.test.tsx
+ * @input Renders ChartStreamGL inside Chart with stubbed ResizeObserver, WebGL-less
+ * canvas (getContext → null), and a getScreenCTM polyfill returning null (the
+ * spec value for unrendered elements — jsdom lacks the method entirely)
+ * @output Render-smoke coverage for the GL stream: marker group, overlay canvas,
+ * and safe imperative pushes without a WebGL context (#4295)
+ * @position Colocated test for ChartStreamGL.tsx
+ */
+
+import {describe, it, expect, beforeEach, afterEach, vi} from 'vitest';
+import {render, act} from '@testing-library/react';
+import {Chart} from './Chart';
+import {ChartStreamGL, type ChartStreamGLHandle} from './ChartStreamGL';
+
+// Streaming charts start empty and take their window from explicit domains.
+const streamProps = {
+ data: [] as Record<string, unknown>[],
+ xKey: 't',
+ yKeys: ['v'],
+ xDomain: [0, 10] as [number, number],
+ yDomain: [0, 1] as [number, number],
+};
+
+// Capture the ResizeObserver callback so tests can drive the reported width.
+let resizeCallback: ResizeObserverCallback | undefined;
+
+let originalGetContext: typeof HTMLCanvasElement.prototype.getContext;
+let hadGetScreenCTM = false;
+
+beforeEach(() => {
+ resizeCallback = undefined;
+ vi.stubGlobal(
+ 'ResizeObserver',
+ class {
+ constructor(cb: ResizeObserverCallback) {
+ resizeCallback = cb;
+ }
+ observe() {}
+ unobserve() {}
+ disconnect() {}
+ },
+ );
+
+ // Behave like a browser without WebGL — the GL marks null-guard this.
+ originalGetContext = HTMLCanvasElement.prototype.getContext;
+ HTMLCanvasElement.prototype.getContext = (() =>
+ null) as typeof HTMLCanvasElement.prototype.getContext;
+
+ // jsdom has no getScreenCTM at all; a real browser returns null for
+ // undisplayed elements and mountCanvasOverSVG handles that branch.
+ const svgProto = SVGElement.prototype as unknown as {
+ getScreenCTM?: () => unknown;
+ };
+ hadGetScreenCTM = typeof svgProto.getScreenCTM === 'function';
+ if (!hadGetScreenCTM) {
+ svgProto.getScreenCTM = () => null;
+ }
+});
+
+afterEach(() => {
+ HTMLCanvasElement.prototype.getContext = originalGetContext;
+ if (!hadGetScreenCTM) {
+ delete (SVGElement.prototype as unknown as {getScreenCTM?: unknown})
+ .getScreenCTM;
+ }
+ vi.unstubAllGlobals();
+});
+
+function reportWidth(width: number) {
+ act(() => {
+ resizeCallback?.(
+ [{contentRect: {width}} as unknown as ResizeObserverEntry],
+ {} as ResizeObserver,
+ );
+ });
+}
+
+describe('ChartStreamGL', () => {
+ it('mounts a positioning marker group without a WebGL context', () => {
+ const {container} = render(
+ <Chart {...streamProps}>
+ <ChartStreamGL color="#0064E0" />
+ </Chart>,
+ );
+
+ reportWidth(464);
+
+ expect(container.querySelector('svg > g > g')).not.toBeNull();
+ });
+
+ it('mounts the overlay canvas as a sibling of the svg', () => {
+ const {container} = render(
+ <Chart {...streamProps}>
+ <ChartStreamGL color="#0064E0" />
+ </Chart>,
+ );
+
+ reportWidth(464);
+
+ const canvas = container.querySelector('canvas');
+ const svg = container.querySelector('svg');
+ expect(canvas).not.toBeNull();
+ expect(canvas?.parentElement).toBe(svg?.parentElement);
+ });
+
+ it('accepts streamed points and clear without a WebGL context', () => {
+ let handle: ChartStreamGLHandle | null = null;
+
+ render(
+ <Chart {...streamProps}>
+ <ChartStreamGL
+ color="#0064E0"
+ handleRef={h => {
+ handle = h;
+ }}
+ />
+ </Chart>,
+ );
+
+ reportWidth(464);
+
+ expect(handle).not.toBeNull();
+ expect(() =>
+ act(() => {
+ handle?.push(1, 0.5);
+ handle?.push(2, 0.7);
+ handle?.push(3, 0.4);
+ handle?.clear();
+ }),
+ ).not.toThrow();
+ });
+});
diff --git a/packages/lab/src/Chart/ChartTooltip.test.tsx b/packages/lab/src/Chart/ChartTooltip.test.tsx
new file mode 100644
index 0000000000..3dec1a17cd
--- /dev/null
+++ b/packages/lab/src/Chart/ChartTooltip.test.tsx
@@ -0,0 +1,107 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file ChartTooltip.test.tsx
+ * @input Renders ChartTooltip inside Chart with a stubbed ResizeObserver
+ * @output Render-smoke coverage for the tooltip's idle state: capture surface, no crosshair, no card.
+ * The pointer pipeline (createSVGPoint/getScreenCTM) does not exist in jsdom, so hover
+ * states are intentionally out of scope here. (#4295)
+ * @position Colocated test for ChartTooltip.tsx
+ */
+
+import {describe, it, expect, beforeEach, afterEach, vi} from 'vitest';
+import {render, screen, act} from '@testing-library/react';
+import {Chart} from './Chart';
+import {ChartTooltip} from './ChartTooltip';
+
+const data = [
+ {month: 'Jan', revenue: 10},
+ {month: 'Feb', revenue: 20},
+ {month: 'Mar', revenue: 30},
+];
+
+// Capture the ResizeObserver callback so tests can drive the reported width.
+let resizeCallback: ResizeObserverCallback | undefined;
+
+beforeEach(() => {
+ resizeCallback = undefined;
+ vi.stubGlobal(
+ 'ResizeObserver',
+ class {
+ constructor(cb: ResizeObserverCallback) {
+ resizeCallback = cb;
+ }
+ observe() {}
+ unobserve() {}
+ disconnect() {}
+ },
+ );
+});
+
+afterEach(() => {
+ vi.unstubAllGlobals();
+});
+
+function reportWidth(width: number) {
+ act(() => {
+ resizeCallback?.(
+ [{contentRect: {width}} as unknown as ResizeObserverEntry],
+ {} as ResizeObserver,
+ );
+ });
+}
+
+describe('ChartTooltip', () => {
+ it('renders a full-plot pointer capture surface', () => {
+ const {container} = render(
+ <Chart data={data} xKey="month" yKeys={['revenue']}>
+ <ChartTooltip />
+ </Chart>,
+ );
+
+ reportWidth(464);
+
+ // Inner plot area: 464 - (48 + 16) wide, 300 - (16 + 32) tall.
+ const surface = container.querySelector('svg > g rect');
+ expect(surface).not.toBeNull();
+ expect(surface).toHaveAttribute('width', '400');
+ expect(surface).toHaveAttribute('height', '252');
+ expect(surface).toHaveAttribute('fill', 'transparent');
+ });
+
+ it('shows no crosshair or point indicator before pointer interaction', () => {
+ const {container} = render(
+ <Chart data={data} xKey="month" yKeys={['revenue']}>
+ <ChartTooltip crosshair="xy" crosshairLabels />
+ </Chart>,
+ );
+
+ reportWidth(464);
+
+ expect(container.querySelectorAll('line')).toHaveLength(0);
+ expect(container.querySelectorAll('circle')).toHaveLength(0);
+ });
+
+ it('shows no tooltip content before pointer interaction', () => {
+ render(
+ <Chart data={data} xKey="month" yKeys={['revenue']}>
+ <ChartTooltip />
+ </Chart>,
+ );
+
+ reportWidth(464);
+ // A second measurement re-renders with the svg ref resolved, giving the
+ // portal every chance to mount — content must still be absent.
+ reportWidth(465);
+
+ // The default renderer would print "month: Jan" lines for the datum.
+ // Chart also renders a visually hidden data table (#4382) whose row and
+ // column headers legitimately read "Jan" and "revenue", so only text
+ // outside that table counts as tooltip content.
+ const outsideTable = (el: HTMLElement) => el.closest('table') == null;
+ expect(screen.queryAllByText(/Jan/).filter(outsideTable)).toHaveLength(0);
+ expect(screen.queryAllByText(/revenue/).filter(outsideTable)).toHaveLength(
+ 0,
+ );
+ });
+});
diff --git a/packages/lab/src/Chart/ChartZoom.test.tsx b/packages/lab/src/Chart/ChartZoom.test.tsx
new file mode 100644
index 0000000000..92580ad938
--- /dev/null
+++ b/packages/lab/src/Chart/ChartZoom.test.tsx
@@ -0,0 +1,102 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file ChartZoom.test.tsx
+ * @input Renders ChartZoom inside Chart with a stubbed ResizeObserver
+ * @output Render-smoke coverage for zoom: capture surface, portaled toolbar, toolbar opt-out.
+ * Wheel/pinch gestures need createSVGPoint/getScreenCTM, which do not exist in
+ * jsdom, so they are intentionally out of scope here. (#4295)
+ * @position Colocated test for ChartZoom.tsx
+ */
+
+import {describe, it, expect, beforeEach, afterEach, vi} from 'vitest';
+import {render, screen, act} from '@testing-library/react';
+import {Chart} from './Chart';
+import {ChartZoom} from './ChartZoom';
+
+const data = [
+ {x: 0, y: 1},
+ {x: 1, y: 2},
+ {x: 2, y: 3},
+];
+
+// Capture the ResizeObserver callback so tests can drive the reported width.
+let resizeCallback: ResizeObserverCallback | undefined;
+
+beforeEach(() => {
+ resizeCallback = undefined;
+ vi.stubGlobal(
+ 'ResizeObserver',
+ class {
+ constructor(cb: ResizeObserverCallback) {
+ resizeCallback = cb;
+ }
+ observe() {}
+ unobserve() {}
+ disconnect() {}
+ },
+ );
+});
+
+afterEach(() => {
+ vi.unstubAllGlobals();
+});
+
+function reportWidth(width: number) {
+ act(() => {
+ resizeCallback?.(
+ [{contentRect: {width}} as unknown as ResizeObserverEntry],
+ {} as ResizeObserver,
+ );
+ });
+}
+
+describe('ChartZoom', () => {
+ it('renders a full-plot wheel and drag capture surface', () => {
+ const {container} = render(
+ <Chart data={data} xKey="x" yKeys={['y']} interactive>
+ <ChartZoom />
+ </Chart>,
+ );
+
+ reportWidth(464);
+
+ const surface = container.querySelector('svg > g rect');
+ expect(surface).not.toBeNull();
+ expect(surface).toHaveAttribute('width', '400');
+ expect(surface).toHaveAttribute('height', '252');
+ expect(surface).toHaveAttribute('fill', 'transparent');
+ });
+
+ it('portals the zoom toolbar into the chart container once the svg is measured', () => {
+ render(
+ <Chart data={data} xKey="x" yKeys={['y']} interactive>
+ <ChartZoom />
+ </Chart>,
+ );
+
+ // The toolbar portal target is the svg's parent, which only resolves on a
+ // render after the svg has been committed — report a second measurement.
+ reportWidth(464);
+ reportWidth(465);
+
+ expect(screen.getByRole('button', {name: 'Zoom in'})).toBeInTheDocument();
+ expect(screen.getByRole('button', {name: 'Zoom out'})).toBeInTheDocument();
+ expect(
+ screen.getByRole('button', {name: 'Reset zoom'}),
+ ).toBeInTheDocument();
+ });
+
+ it('renders no toolbar when toolbar is false', () => {
+ render(
+ <Chart data={data} xKey="x" yKeys={['y']} interactive>
+ <ChartZoom toolbar={false} />
+ </Chart>,
+ );
+
+ reportWidth(464);
+ reportWidth(465);
+
+ expect(screen.queryByRole('button')).toBeNull();
+ });
+});
diff --git a/packages/lab/src/Radial/RadialArea.test.tsx b/packages/lab/src/Radial/RadialArea.test.tsx
new file mode 100644
index 0000000000..92ddfea1f8
--- /dev/null
+++ b/packages/lab/src/Radial/RadialArea.test.tsx
@@ -0,0 +1,158 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file RadialArea.test.tsx
+ * @input RadialArea inside a spider-mode RadialChart (600x400 → cx=300,
+ * cy=200, outerRadius=160); axis domains are floored at 0
+ * @output Render-smoke coverage: polygon per selected row, value-to-radius
+ * mapping, row selection by dataKey, first-row fallback, vertex dots,
+ * pie-mode guard
+ * @position Colocated test for RadialArea.tsx
+ */
+
+import {describe, it, expect, beforeEach, afterEach, vi} from 'vitest';
+import {render, act} from '@testing-library/react';
+import {RadialChart} from './RadialChart';
+import {RadialArea} from './RadialArea';
+
+const spiderData = [
+ {model: 'A', speed: 10, handling: 5, comfort: 8},
+ {model: 'B', speed: 5, handling: 10, comfort: 4},
+];
+
+// Capture the ResizeObserver callback so tests can drive the reported width.
+let resizeCallback: ResizeObserverCallback | undefined;
+
+beforeEach(() => {
+ resizeCallback = undefined;
+ vi.stubGlobal(
+ 'ResizeObserver',
+ class {
+ constructor(cb: ResizeObserverCallback) {
+ resizeCallback = cb;
+ }
+ observe() {}
+ unobserve() {}
+ disconnect() {}
+ },
+ );
+});
+
+afterEach(() => {
+ vi.unstubAllGlobals();
+});
+
+function reportWidth(width: number) {
+ act(() => {
+ resizeCallback?.(
+ [{contentRect: {width}} as unknown as ResizeObserverEntry],
+ {} as ResizeObserver,
+ );
+ });
+}
+
+function renderSpider(children: React.ReactNode) {
+ const result = render(
+ <RadialChart data={spiderData} axes={['speed', 'handling', 'comfort']}>
+ {children}
+ </RadialChart>,
+ );
+ reportWidth(600);
+ return result;
+}
+
+/** Parse a polygon's points attribute into [x, y] pairs. */
+function parsePoints(polygon: Element): number[][] {
+ return (polygon.getAttribute('points') ?? '')
+ .split(' ')
+ .map(pair => pair.split(',').map(parseFloat));
+}
+
+describe('RadialArea', () => {
+ it('renders a single polygon with one vertex per axis', () => {
+ const {container} = renderSpider(
+ <RadialArea dataKey="A" color="#ff0000" />,
+ );
+
+ const polygons = container.querySelectorAll('polygon');
+ expect(polygons).toHaveLength(1);
+ expect(parsePoints(polygons[0])).toHaveLength(3);
+ expect(polygons[0]).toHaveAttribute('fill', '#ff0000');
+ });
+
+ it('maps the axis maximum to the outer radius', () => {
+ const {container} = renderSpider(
+ <RadialArea dataKey="A" color="#ff0000" />,
+ );
+
+ // Row A has the speed max (10); domain [0, 10] → t=1 → r=160.
+ // Top axis vertex: (300, 200 - 160) = (300, 40).
+ const [first] = parsePoints(container.querySelector('polygon')!);
+ expect(first[0]).toBeCloseTo(300, 6);
+ expect(first[1]).toBeCloseTo(40, 6);
+ });
+
+ it('selects the row whose fields contain the dataKey value', () => {
+ const {container} = renderSpider(
+ <RadialArea dataKey="B" color="#ff0000" />,
+ );
+
+ // Row B: speed 5 in domain [0, 10] → t=0.5 → r=80 → (300, 120).
+ const [first] = parsePoints(container.querySelector('polygon')!);
+ expect(first[0]).toBeCloseTo(300, 6);
+ expect(first[1]).toBeCloseTo(120, 6);
+ });
+
+ it('falls back to the first row when no field matches the dataKey', () => {
+ const {container} = renderSpider(
+ <RadialArea dataKey="does-not-exist" color="#ff0000" />,
+ );
+
+ // Falls back to row A → top vertex at the outer radius.
+ const [first] = parsePoints(container.querySelector('polygon')!);
+ expect(first[1]).toBeCloseTo(40, 6);
+ });
+
+ it('renders a dot at each vertex when dots is set', () => {
+ const {container} = renderSpider(
+ <RadialArea dataKey="A" color="#ff0000" dots dotRadius={6} />,
+ );
+
+ const circles = container.querySelectorAll('circle');
+ expect(circles).toHaveLength(3);
+ for (const circle of circles) {
+ expect(circle).toHaveAttribute('r', '6');
+ expect(circle).toHaveAttribute('fill', '#ff0000');
+ }
+ });
+
+ it('renders no dots by default', () => {
+ const {container} = renderSpider(
+ <RadialArea dataKey="A" color="#ff0000" />,
+ );
+
+ expect(container.querySelector('circle')).toBeNull();
+ });
+
+ it('renders nothing when the chart has no data', () => {
+ const {container} = render(
+ <RadialChart data={[]} axes={['speed', 'handling', 'comfort']}>
+ <RadialArea dataKey="A" color="#ff0000" />
+ </RadialChart>,
+ );
+ reportWidth(600);
+
+ expect(container.querySelector('polygon')).toBeNull();
+ });
+
+ it('renders nothing inside a pie-mode chart', () => {
+ const {container} = render(
+ <RadialChart data={spiderData} valueKey="speed" labelKey="model">
+ <RadialArea dataKey="A" color="#ff0000" />
+ </RadialChart>,
+ );
+ reportWidth(600);
+
+ expect(container.querySelector('polygon')).toBeNull();
+ });
+});
diff --git a/packages/lab/src/Radial/RadialAxis.test.tsx b/packages/lab/src/Radial/RadialAxis.test.tsx
new file mode 100644
index 0000000000..e68f357047
--- /dev/null
+++ b/packages/lab/src/Radial/RadialAxis.test.tsx
@@ -0,0 +1,106 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file RadialAxis.test.tsx
+ * @input RadialAxis inside a spider-mode RadialChart (600x400 → cx=300,
+ * cy=200, outerRadius=160); three axes at -90/30/150 degrees
+ * @output Render-smoke coverage: one label per axis, position-derived text
+ * anchors, label offset geometry, pie-mode guard
+ * @position Colocated test for RadialAxis.tsx
+ */
+
+import {describe, it, expect, beforeEach, afterEach, vi} from 'vitest';
+import {render, screen, within, act} from '@testing-library/react';
+import {RadialChart} from './RadialChart';
+import {RadialAxis} from './RadialAxis';
+
+const spiderData = [
+ {model: 'A', speed: 10, handling: 5, comfort: 8},
+ {model: 'B', speed: 5, handling: 10, comfort: 4},
+];
+
+// Capture the ResizeObserver callback so tests can drive the reported width.
+let resizeCallback: ResizeObserverCallback | undefined;
+
+beforeEach(() => {
+ resizeCallback = undefined;
+ vi.stubGlobal(
+ 'ResizeObserver',
+ class {
+ constructor(cb: ResizeObserverCallback) {
+ resizeCallback = cb;
+ }
+ observe() {}
+ unobserve() {}
+ disconnect() {}
+ },
+ );
+});
+
+afterEach(() => {
+ vi.unstubAllGlobals();
+});
+
+function reportWidth(width: number) {
+ act(() => {
+ resizeCallback?.(
+ [{contentRect: {width}} as unknown as ResizeObserverEntry],
+ {} as ResizeObserver,
+ );
+ });
+}
+
+function renderSpider(children: React.ReactNode) {
+ const {container} = render(
+ <RadialChart data={spiderData} axes={['speed', 'handling', 'comfort']}>
+ {children}
+ </RadialChart>,
+ );
+ reportWidth(600);
+ // Scope label queries to the svg: RadialChart also renders a visually
+ // hidden data table whose column headers repeat the axis keys (#4382), so
+ // an unscoped getByText('speed') would match two nodes.
+ const svg = within(screen.getByRole('img'));
+ return {container, svg};
+}
+
+describe('RadialAxis', () => {
+ it('renders one label per axis, named after the axis key', () => {
+ const {container, svg} = renderSpider(<RadialAxis />);
+
+ expect(container.querySelectorAll('text')).toHaveLength(3);
+ expect(svg.getByText('speed')).toBeInTheDocument();
+ expect(svg.getByText('handling')).toBeInTheDocument();
+ expect(svg.getByText('comfort')).toBeInTheDocument();
+ });
+
+ it('anchors labels by their side of the chart: top=middle, right=start, left=end', () => {
+ const {svg} = renderSpider(<RadialAxis />);
+
+ // Axes start at the top (-90 degrees) and step clockwise by 120 degrees:
+ // speed at -90 (top), handling at 30 (right), comfort at 150 (left).
+ expect(svg.getByText('speed')).toHaveAttribute('text-anchor', 'middle');
+ expect(svg.getByText('handling')).toHaveAttribute('text-anchor', 'start');
+ expect(svg.getByText('comfort')).toHaveAttribute('text-anchor', 'end');
+ });
+
+ it('positions labels labelOffset px beyond the outer radius', () => {
+ const {svg} = renderSpider(<RadialAxis labelOffset={16} />);
+
+ // Top axis: y = cy - (radius + 16) = 200 - 176 = 24, x = cx = 300.
+ const top = svg.getByText('speed');
+ expect(parseFloat(top.getAttribute('x') ?? '')).toBeCloseTo(300, 6);
+ expect(parseFloat(top.getAttribute('y') ?? '')).toBeCloseTo(24, 6);
+ });
+
+ it('renders nothing inside a pie-mode chart', () => {
+ const {container} = render(
+ <RadialChart data={spiderData} valueKey="speed" labelKey="model">
+ <RadialAxis />
+ </RadialChart>,
+ );
+ reportWidth(600);
+
+ expect(container.querySelector('text')).toBeNull();
+ });
+});
diff --git a/packages/lab/src/Radial/RadialChart.test.tsx b/packages/lab/src/Radial/RadialChart.test.tsx
index 3ea2f5b059..c00670a368 100644
--- a/packages/lab/src/Radial/RadialChart.test.tsx
+++ b/packages/lab/src/Radial/RadialChart.test.tsx
@@ -2,14 +2,19 @@
/**
* @file RadialChart.test.tsx
- * @input Uses vitest, @testing-library/react, RadialChart component
- * @output Unit tests for RadialChart accessibility (WCAG 1.1.1)
- * @position Testing; validates RadialChart.tsx accessible name + data-table fallback
+ * @input Uses vitest, @testing-library/react, RadialChart + useRadial under a
+ * stubbed ResizeObserver
+ * @output Unit tests for RadialChart accessibility (WCAG 1.1.1), the
+ * containerWidth > 0 render gate + svg sizing, and the useRadial
+ * outside-provider guard
+ * @position Testing; validates RadialChart.tsx accessible name + data-table
+ * fallback + sizing, and RadialContext.ts
*/
import {describe, it, expect, beforeEach, afterEach, vi} from 'vitest';
import {render, screen, act} from '@testing-library/react';
import {RadialChart} from './RadialChart';
+import {useRadial} from './RadialContext';
const spiderData = [
{name: 'modelA', speed: 8, handling: 6, comfort: 7},
@@ -155,3 +160,50 @@ describe('RadialChart data table fallback', () => {
expect(screen.queryByRole('table')).not.toBeInTheDocument();
});
});
+
+describe('RadialChart container sizing', () => {
+ it('renders no svg until the container reports a width', () => {
+ render(
+ <RadialChart data={pieData} valueKey="revenue" labelKey="region">
+ <g />
+ </RadialChart>,
+ );
+ expect(screen.queryByRole('img')).not.toBeInTheDocument();
+
+ reportWidth(600);
+
+ const svg = screen.getByRole('img');
+ expect(svg).toHaveAttribute('width', '600');
+ // Default height is 400.
+ expect(svg).toHaveAttribute('height', '400');
+ });
+
+ it('sizes the svg from the height prop in spider mode', () => {
+ render(
+ <RadialChart
+ data={spiderData}
+ axes={['speed', 'handling', 'comfort']}
+ height={300}>
+ <g />
+ </RadialChart>,
+ );
+ reportWidth(500);
+
+ const svg = screen.getByRole('img');
+ expect(svg).toHaveAttribute('width', '500');
+ expect(svg).toHaveAttribute('height', '300');
+ });
+});
+
+describe('useRadial', () => {
+ it('throws when used outside <RadialChart>', () => {
+ function Probe() {
+ useRadial();
+ return null;
+ }
+
+ expect(() => render(<Probe />)).toThrow(
+ 'Radial components must be used inside <RadialChart>',
+ );
+ });
+});
diff --git a/packages/lab/src/Radial/RadialGrid.test.tsx b/packages/lab/src/Radial/RadialGrid.test.tsx
new file mode 100644
index 0000000000..751c9b8bde
--- /dev/null
+++ b/packages/lab/src/Radial/RadialGrid.test.tsx
@@ -0,0 +1,124 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file RadialGrid.test.tsx
+ * @input RadialGrid inside a spider-mode RadialChart (600x400 → cx=300,
+ * cy=200, outerRadius=160)
+ * @output Render-smoke coverage: ring polygon count, axis line count,
+ * ring/line geometry, pie-mode guard
+ * @position Colocated test for RadialGrid.tsx
+ */
+
+import {describe, it, expect, beforeEach, afterEach, vi} from 'vitest';
+import {render, act} from '@testing-library/react';
+import {RadialChart} from './RadialChart';
+import {RadialGrid} from './RadialGrid';
+
+const spiderData = [
+ {model: 'A', speed: 10, handling: 5, comfort: 8},
+ {model: 'B', speed: 5, handling: 10, comfort: 4},
+];
+
+// Capture the ResizeObserver callback so tests can drive the reported width.
+let resizeCallback: ResizeObserverCallback | undefined;
+
+beforeEach(() => {
+ resizeCallback = undefined;
+ vi.stubGlobal(
+ 'ResizeObserver',
+ class {
+ constructor(cb: ResizeObserverCallback) {
+ resizeCallback = cb;
+ }
+ observe() {}
+ unobserve() {}
+ disconnect() {}
+ },
+ );
+});
+
+afterEach(() => {
+ vi.unstubAllGlobals();
+});
+
+function reportWidth(width: number) {
+ act(() => {
+ resizeCallback?.(
+ [{contentRect: {width}} as unknown as ResizeObserverEntry],
+ {} as ResizeObserver,
+ );
+ });
+}
+
+function renderSpider(children: React.ReactNode) {
+ const result = render(
+ <RadialChart data={spiderData} axes={['speed', 'handling', 'comfort']}>
+ {children}
+ </RadialChart>,
+ );
+ reportWidth(600);
+ return result;
+}
+
+describe('RadialGrid', () => {
+ it('renders one concentric ring polygon per ring', () => {
+ const {container} = renderSpider(<RadialGrid rings={4} />);
+
+ expect(container.querySelectorAll('polygon')).toHaveLength(4);
+ });
+
+ it('defaults to five rings', () => {
+ const {container} = renderSpider(<RadialGrid />);
+
+ expect(container.querySelectorAll('polygon')).toHaveLength(5);
+ });
+
+ it('gives each ring one vertex per axis', () => {
+ const {container} = renderSpider(<RadialGrid />);
+
+ for (const polygon of container.querySelectorAll('polygon')) {
+ const pairs = (polygon.getAttribute('points') ?? '').split(' ');
+ expect(pairs).toHaveLength(3);
+ }
+ });
+
+ it('draws the outermost ring at the outer radius', () => {
+ const {container} = renderSpider(<RadialGrid />);
+
+ const polygons = container.querySelectorAll('polygon');
+ const outer = polygons[polygons.length - 1];
+ // First vertex is the top axis at full radius: (cx, cy - 160) = (300, 40).
+ const [x, y] = (outer.getAttribute('points') ?? '')
+ .split(' ')[0]
+ .split(',')
+ .map(parseFloat);
+ expect(x).toBeCloseTo(300, 6);
+ expect(y).toBeCloseTo(40, 6);
+ });
+
+ it('draws one axis line per axis from the center to the outer radius', () => {
+ const {container} = renderSpider(<RadialGrid />);
+
+ const lines = container.querySelectorAll('line');
+ expect(lines).toHaveLength(3);
+
+ // Top axis line: center (300, 200) to top vertex (300, 40).
+ const top = lines[0];
+ expect(parseFloat(top.getAttribute('x1') ?? '')).toBeCloseTo(300, 6);
+ expect(parseFloat(top.getAttribute('y1') ?? '')).toBeCloseTo(200, 6);
+ expect(parseFloat(top.getAttribute('x2') ?? '')).toBeCloseTo(300, 6);
+ expect(parseFloat(top.getAttribute('y2') ?? '')).toBeCloseTo(40, 6);
+ });
+
+ it('renders nothing inside a pie-mode chart', () => {
+ const {container} = render(
+ <RadialChart data={spiderData} valueKey="speed" labelKey="model">
+ <RadialGrid />
+ </RadialChart>,
+ );
+ reportWidth(600);
+
+ expect(container.querySelector('polygon')).toBeNull();
+ expect(container.querySelector('line')).toBeNull();
+ });
+});
diff --git a/packages/lab/src/Radial/RadialSlice.test.tsx b/packages/lab/src/Radial/RadialSlice.test.tsx
new file mode 100644
index 0000000000..6695a145c7
--- /dev/null
+++ b/packages/lab/src/Radial/RadialSlice.test.tsx
@@ -0,0 +1,206 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file RadialSlice.test.tsx
+ * @input RadialSlice inside a pie-mode RadialChart (600x400 → cx=300, cy=200,
+ * outerRadius=160)
+ * @output Render-smoke coverage: one path per datum, color cycling, pie vs
+ * donut arc paths, percentage labels + threshold, empty/spider guards
+ * @position Colocated test for RadialSlice.tsx
+ */
+
+import {describe, it, expect, beforeEach, afterEach, vi} from 'vitest';
+import {render, screen, act} from '@testing-library/react';
+import {RadialChart} from './RadialChart';
+import {RadialSlice} from './RadialSlice';
+
+const pieData = [
+ {region: 'NA', revenue: 500},
+ {region: 'EU', revenue: 300},
+ {region: 'APAC', revenue: 200},
+];
+
+// Capture the ResizeObserver callback so tests can drive the reported width.
+let resizeCallback: ResizeObserverCallback | undefined;
+
+beforeEach(() => {
+ resizeCallback = undefined;
+ vi.stubGlobal(
+ 'ResizeObserver',
+ class {
+ constructor(cb: ResizeObserverCallback) {
+ resizeCallback = cb;
+ }
+ observe() {}
+ unobserve() {}
+ disconnect() {}
+ },
+ );
+});
+
+afterEach(() => {
+ vi.unstubAllGlobals();
+});
+
+function reportWidth(width: number) {
+ act(() => {
+ resizeCallback?.(
+ [{contentRect: {width}} as unknown as ResizeObserverEntry],
+ {} as ResizeObserver,
+ );
+ });
+}
+
+function renderPie(ui: React.ReactElement) {
+ const result = render(ui);
+ reportWidth(600);
+ return result;
+}
+
+/** Count SVG arc commands in a path's `d` attribute. */
+function arcCommandCount(d: string): number {
+ return d.split('A ').length - 1;
+}
+
+describe('RadialSlice', () => {
+ it('renders one path per datum, filled with the given colors in data order', () => {
+ const {container} = renderPie(
+ <RadialChart data={pieData} valueKey="revenue" labelKey="region">
+ <RadialSlice colors={['#111111', '#222222', '#333333']} />
+ </RadialChart>,
+ );
+
+ const paths = container.querySelectorAll('path');
+ expect(paths).toHaveLength(3);
+ expect(paths[0]).toHaveAttribute('fill', '#111111');
+ expect(paths[1]).toHaveAttribute('fill', '#222222');
+ expect(paths[2]).toHaveAttribute('fill', '#333333');
+ });
+
+ it('cycles colors when there are more slices than colors', () => {
+ const {container} = renderPie(
+ <RadialChart data={pieData} valueKey="revenue" labelKey="region">
+ <RadialSlice colors={['#111111', '#222222']} />
+ </RadialChart>,
+ );
+
+ const paths = container.querySelectorAll('path');
+ expect(paths[2]).toHaveAttribute('fill', '#111111');
+ });
+
+ it('draws pie slices as single arcs anchored at the chart center', () => {
+ const {container} = renderPie(
+ <RadialChart data={pieData} valueKey="revenue" labelKey="region">
+ <RadialSlice colors={['#111111']} />
+ </RadialChart>,
+ );
+
+ for (const path of container.querySelectorAll('path')) {
+ const d = path.getAttribute('d') ?? '';
+ // Pie slices start at the center (cx=300, cy=200) and use one arc.
+ expect(d.startsWith('M 300 200')).toBe(true);
+ expect(arcCommandCount(d)).toBe(1);
+ }
+ });
+
+ it('draws donut slices as annular sectors with an inner and outer arc', () => {
+ const {container} = renderPie(
+ <RadialChart
+ data={pieData}
+ valueKey="revenue"
+ labelKey="region"
+ innerRadius={0.6}>
+ <RadialSlice colors={['#111111']} />
+ </RadialChart>,
+ );
+
+ const paths = container.querySelectorAll('path');
+ expect(paths).toHaveLength(3);
+ for (const path of paths) {
+ const d = path.getAttribute('d') ?? '';
+ expect(d.startsWith('M 300 200')).toBe(false);
+ expect(arcCommandCount(d)).toBe(2);
+ }
+ });
+
+ it('drops the hairline separator stroke when cornerRadius is set', () => {
+ const {container} = renderPie(
+ <RadialChart data={pieData} valueKey="revenue" labelKey="region">
+ <RadialSlice colors={['#111111']} cornerRadius={4} />
+ </RadialChart>,
+ );
+
+ for (const path of container.querySelectorAll('path')) {
+ expect(path).toHaveAttribute('stroke-width', '0');
+ }
+ });
+
+ it('separates slices with a 1px surface-colored stroke by default', () => {
+ const {container} = renderPie(
+ <RadialChart data={pieData} valueKey="revenue" labelKey="region">
+ <RadialSlice colors={['#111111']} />
+ </RadialChart>,
+ );
+
+ for (const path of container.querySelectorAll('path')) {
+ expect(path).toHaveAttribute('stroke-width', '1');
+ }
+ });
+
+ it('labels each slice with its rounded percentage of the total', () => {
+ renderPie(
+ <RadialChart data={pieData} valueKey="revenue" labelKey="region">
+ <RadialSlice colors={['#111111']} />
+ </RadialChart>,
+ );
+
+ // 500/300/200 out of 1000.
+ expect(screen.getByText('50%')).toBeInTheDocument();
+ expect(screen.getByText('30%')).toBeInTheDocument();
+ expect(screen.getByText('20%')).toBeInTheDocument();
+ });
+
+ it('hides labels for slices below the label threshold', () => {
+ renderPie(
+ <RadialChart
+ data={[
+ {region: 'big', revenue: 97},
+ {region: 'tiny', revenue: 3},
+ ]}
+ valueKey="revenue"
+ labelKey="region">
+ <RadialSlice colors={['#111111']} />
+ </RadialChart>,
+ );
+
+ expect(screen.getByText('97%')).toBeInTheDocument();
+ // 3% is below the default 5% threshold.
+ expect(screen.queryByText('3%')).not.toBeInTheDocument();
+ });
+
+ it('renders nothing when every value is zero', () => {
+ const {container} = renderPie(
+ <RadialChart
+ data={[
+ {region: 'a', revenue: 0},
+ {region: 'b', revenue: 0},
+ ]}
+ valueKey="revenue"
+ labelKey="region">
+ <RadialSlice colors={['#111111']} />
+ </RadialChart>,
+ );
+
+ expect(container.querySelector('path')).toBeNull();
+ });
+
+ it('renders nothing inside a spider-mode chart', () => {
+ const {container} = renderPie(
+ <RadialChart data={pieData} axes={['revenue']}>
+ <RadialSlice colors={['#111111']} />
+ </RadialChart>,
+ );
+
+ expect(container.querySelector('path')).toBeNull();
+ });
+});
diff --git a/packages/lab/src/Radial/RadialTooltip.test.tsx b/packages/lab/src/Radial/RadialTooltip.test.tsx
new file mode 100644
index 0000000000..c78a1e4a8f
--- /dev/null
+++ b/packages/lab/src/Radial/RadialTooltip.test.tsx
@@ -0,0 +1,88 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file RadialTooltip.test.tsx
+ * @input RadialTooltip inside pie- and spider-mode RadialCharts (600x400 →
+ * outerRadius=160)
+ * @output Mount smoke coverage only: the pointer pipeline needs
+ * createSVGPoint/getScreenCTM, which jsdom does not implement, so hover
+ * behavior is not exercised here. Asserts the event-capture circle mounts.
+ * @position Colocated test for RadialTooltip.tsx
+ */
+
+import {describe, it, expect, beforeEach, afterEach, vi} from 'vitest';
+import {render, act} from '@testing-library/react';
+import {RadialChart} from './RadialChart';
+import {RadialSlice} from './RadialSlice';
+import {RadialTooltip} from './RadialTooltip';
+
+const pieData = [
+ {region: 'NA', revenue: 500},
+ {region: 'EU', revenue: 300},
+];
+
+// Capture the ResizeObserver callback so tests can drive the reported width.
+let resizeCallback: ResizeObserverCallback | undefined;
+
+beforeEach(() => {
+ resizeCallback = undefined;
+ vi.stubGlobal(
+ 'ResizeObserver',
+ class {
+ constructor(cb: ResizeObserverCallback) {
+ resizeCallback = cb;
+ }
+ observe() {}
+ unobserve() {}
+ disconnect() {}
+ },
+ );
+});
+
+afterEach(() => {
+ vi.unstubAllGlobals();
+});
+
+function reportWidth(width: number) {
+ act(() => {
+ resizeCallback?.(
+ [{contentRect: {width}} as unknown as ResizeObserverEntry],
+ {} as ResizeObserver,
+ );
+ });
+}
+
+describe('RadialTooltip', () => {
+ it('mounts in a pie-mode chart and renders the event-capture circle', () => {
+ const {container} = render(
+ <RadialChart data={pieData} valueKey="revenue" labelKey="region">
+ <RadialSlice colors={['#111111', '#222222']} />
+ <RadialTooltip />
+ </RadialChart>,
+ );
+ reportWidth(600);
+
+ // Capture circle covers the chart: r = radius + 10 = 170.
+ const capture = container.querySelector('circle[fill="transparent"]');
+ expect(capture).not.toBeNull();
+ expect(capture).toHaveAttribute('r', '170');
+ });
+
+ it('mounts in a spider-mode chart without crashing', () => {
+ const {container} = render(
+ <RadialChart
+ data={[
+ {model: 'A', speed: 10, handling: 5},
+ {model: 'B', speed: 5, handling: 10},
+ ]}
+ axes={['speed', 'handling']}>
+ <RadialTooltip />
+ </RadialChart>,
+ );
+ reportWidth(600);
+
+ expect(
+ container.querySelector('circle[fill="transparent"]'),
+ ).not.toBeNull();
+ });
+});
diff --git a/packages/lab/src/SVGIcon/SVGIcon.test.tsx b/packages/lab/src/SVGIcon/SVGIcon.test.tsx
index 0be95605aa..5df9ce2040 100644
--- a/packages/lab/src/SVGIcon/SVGIcon.test.tsx
+++ b/packages/lab/src/SVGIcon/SVGIcon.test.tsx
@@ -2,8 +2,14 @@
import {describe, it, expect} from 'vitest';
import {render, screen} from '@testing-library/react';
-import {SVGIcon} from './SVGIcon';
-import {bellIcon} from './icons';
+import {SVGIcon, type SVGIconDef} from './SVGIcon';
+import {iconVars} from './tokens.stylex';
+import {bellIcon, calendarIcon, homeIcon, xIcon} from './icons';
+
+/** Top-level shape groups, excluding the <defs> mask block. */
+function shapeGroups(svg: SVGSVGElement): Element[] {
+ return Array.from(svg.children).filter(el => el.tagName === 'g');
+}
describe('SVGIcon', () => {
it('defaults to decorative (aria-hidden) when no accessible name is given', () => {
@@ -37,4 +43,130 @@ describe('SVGIcon', () => {
const svg = container.querySelector('svg');
expect(svg).toHaveAttribute('aria-hidden', 'true');
});
+
+ it('renders each shape with its attributes inside the default 24x24 viewBox', () => {
+ const {container} = render(<SVGIcon icon={xIcon} />);
+
+ const svg = container.querySelector('svg');
+ expect(svg).toHaveAttribute('viewBox', '0 0 24 24');
+
+ const lines = svg?.querySelectorAll('line') ?? [];
+ expect(lines).toHaveLength(2);
+ expect(lines[0]).toHaveAttribute('x1', '18');
+ expect(lines[0]).toHaveAttribute('y1', '6');
+ expect(lines[0]).toHaveAttribute('x2', '6');
+ expect(lines[0]).toHaveAttribute('y2', '18');
+ });
+
+ it('reflects variation, size, and color as data attributes with the stable class', () => {
+ const {container, rerender} = render(<SVGIcon icon={xIcon} />);
+
+ const svg = container.querySelector('svg');
+ expect(svg).toHaveClass('astryx-svg-icon');
+ // Defaults.
+ expect(svg).toHaveAttribute('data-variation', 'linear');
+ expect(svg).toHaveAttribute('data-size', 'md');
+ expect(svg).toHaveAttribute('data-color', 'primary');
+
+ rerender(
+ <SVGIcon icon={xIcon} variation="twotone" size="sm" color="accent" />,
+ );
+ expect(svg).toHaveAttribute('data-variation', 'twotone');
+ expect(svg).toHaveAttribute('data-size', 'sm');
+ expect(svg).toHaveAttribute('data-color', 'accent');
+ });
+
+ it('splits fill-role and stroke-role shapes into separate layer groups', () => {
+ const {container} = render(<SVGIcon icon={calendarIcon} />);
+ const svg = container.querySelector('svg') as SVGSVGElement;
+
+ // primary fill (frame rect), primary stroke (2 pegs),
+ // secondary stroke (divider line) — no secondary fill group.
+ const groups = shapeGroups(svg);
+ expect(groups).toHaveLength(3);
+ expect(groups[0].querySelectorAll('rect')).toHaveLength(1);
+ expect(groups[0].querySelector('rect')).toHaveAttribute('width', '18');
+ expect(groups[1].querySelectorAll('line')).toHaveLength(2);
+ expect(groups[2].querySelectorAll('line')).toHaveLength(1);
+ expect(groups[2].querySelector('line')).toHaveAttribute('y1', '10');
+ });
+
+ it('knocks secondary shapes out of the primary layer with a mask in bold mode', () => {
+ const {container} = render(<SVGIcon icon={homeIcon} variation="bold" />);
+ const svg = container.querySelector('svg') as SVGSVGElement;
+
+ const mask = svg.querySelector('defs mask');
+ expect(mask).not.toBeNull();
+
+ // Mask = full white plate + the door as a black knockout.
+ const plate = mask?.querySelector('rect');
+ expect(plate).toHaveAttribute('width', '24');
+ expect(plate).toHaveAttribute('height', '24');
+ expect(plate).toHaveAttribute('fill', 'white');
+ const knockout = mask?.querySelector('path');
+ expect(knockout).toHaveAttribute('fill', 'black');
+ expect(knockout).toHaveAttribute('stroke', 'black');
+ expect(knockout).toHaveAttribute('stroke-linecap', 'round');
+
+ // The primary fill layer references the mask; the secondary layer is
+ // dropped entirely (it only exists as the knockout).
+ const groups = shapeGroups(svg);
+ expect(groups).toHaveLength(1);
+ expect(groups[0]).toHaveAttribute('mask', `url(#${mask?.id})`);
+ });
+
+ it('keeps the secondary layer visible without a mask outside bold mode', () => {
+ const {container} = render(<SVGIcon icon={homeIcon} />);
+ const svg = container.querySelector('svg') as SVGSVGElement;
+
+ expect(svg.querySelector('mask')).toBeNull();
+ const groups = shapeGroups(svg);
+ expect(groups).toHaveLength(2);
+ expect(groups[0]).not.toHaveAttribute('mask');
+ // The door renders as a real secondary shape.
+ expect(groups[1].querySelector('path')).toHaveAttribute(
+ 'd',
+ 'M15 21v-8a1 1 0 0 0-1-1h-4a1 1 0 0 0-1 1v8',
+ );
+ });
+
+ it('skips the mask in bold mode when there is nothing to knock out', () => {
+ // xIcon is stroke-role only — no fill shapes, no secondary layer.
+ const {container} = render(<SVGIcon icon={xIcon} variation="bold" />);
+ const svg = container.querySelector('svg') as SVGSVGElement;
+
+ expect(svg.querySelector('mask')).toBeNull();
+ expect(svg.querySelectorAll('line')).toHaveLength(2);
+ });
+
+ it('pins the stroke-width token inline when strokeWidth is set', () => {
+ const strokeWidthProp = (iconVars['--icon-stroke-width'] as string).replace(
+ /^var\((.+)\)$/,
+ '$1',
+ );
+
+ const {container} = render(<SVGIcon icon={xIcon} strokeWidth={3} />);
+ const svg = container.querySelector('svg') as SVGSVGElement;
+ expect(svg.style.getPropertyValue(strokeWidthProp)).toBe('3');
+
+ // Without the override the token stays with the size preset.
+ const {container: plain} = render(<SVGIcon icon={xIcon} />);
+ const plainSvg = plain.querySelector('svg') as SVGSVGElement;
+ expect(plainSvg.style.getPropertyValue(strokeWidthProp)).toBe('');
+ });
+
+ it('honors a custom viewBox and passes extra svg props through', () => {
+ const dotIcon: SVGIconDef = {
+ name: 'Dot',
+ viewBox: '0 0 32 32',
+ primary: [{type: 'circle', attrs: {cx: '16', cy: '16', r: '8'}}],
+ };
+ const {container} = render(<SVGIcon icon={dotIcon} id="probe-icon" />);
+
+ const svg = container.querySelector('svg');
+ expect(svg).toHaveAttribute('viewBox', '0 0 32 32');
+ expect(svg).toHaveAttribute('id', 'probe-icon');
+ // role defaults to "fill" — the circle lands in the fill-role group.
+ expect(svg?.querySelector('g circle')).toHaveAttribute('r', '8');
+ });
});
diff --git a/packages/lab/src/Sankey/SankeyGrid.test.tsx b/packages/lab/src/Sankey/SankeyGrid.test.tsx
new file mode 100644
index 0000000000..15c4d9a4a0
--- /dev/null
+++ b/packages/lab/src/Sankey/SankeyGrid.test.tsx
@@ -0,0 +1,156 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file SankeyGrid.test.tsx
+ * @input Renders SankeyGrid inside SankeyChart with a stubbed ResizeObserver
+ * @output Render-smoke coverage for grid lines: per-column dashed lines,
+ * column headers from rich defs, header toggle, stroke overrides (#4295)
+ * @position Colocated test for SankeyGrid.tsx
+ */
+
+import {describe, it, expect, beforeEach, afterEach, vi} from 'vitest';
+import {render, act} from '@testing-library/react';
+import {SankeyChart} from './SankeyChart';
+import {SankeyGrid} from './SankeyGrid';
+import type {SankeyColumn, SankeyNodeDatum, SankeyLinkDatum} from './types';
+
+const nodes: SankeyNodeDatum[] = [
+ {id: 'a', label: 'A', value: 8},
+ {id: 'b', label: 'B', value: 8},
+ {id: 'c', label: 'C', value: 8},
+];
+const links: SankeyLinkDatum[] = [
+ {source: 'a', target: 'b', value: 4},
+ {source: 'b', target: 'c', value: 4},
+];
+const richColumns: SankeyColumn[] = [
+ {ids: ['a'], label: 'Source'},
+ {ids: ['b'], label: 'Middle'},
+ {ids: ['c'], label: 'Target'},
+];
+
+// Capture the ResizeObserver callback so tests can drive the reported width.
+let resizeCallback: ResizeObserverCallback | undefined;
+
+beforeEach(() => {
+ resizeCallback = undefined;
+ vi.stubGlobal(
+ 'ResizeObserver',
+ class {
+ constructor(cb: ResizeObserverCallback) {
+ resizeCallback = cb;
+ }
+ observe() {}
+ unobserve() {}
+ disconnect() {}
+ },
+ );
+});
+
+afterEach(() => {
+ vi.unstubAllGlobals();
+});
+
+function reportWidth(width: number) {
+ act(() => {
+ resizeCallback?.(
+ [{contentRect: {width}} as unknown as ResizeObserverEntry],
+ {} as ResizeObserver,
+ );
+ });
+}
+
+describe('SankeyGrid', () => {
+ it('renders one dashed full-height line per column at the bar center', () => {
+ const {container} = render(
+ <SankeyChart nodes={nodes} links={links} columns={richColumns}>
+ <SankeyGrid />
+ </SankeyChart>,
+ );
+ reportWidth(1000);
+
+ // Columns at x = 0 / 490 / 980, bar center = x + nodeWidth/2.
+ const lines = container.querySelectorAll('line');
+ expect(lines).toHaveLength(3);
+ const centers = ['10', '500', '990'];
+ lines.forEach((line, i) => {
+ expect(line).toHaveAttribute('x1', centers[i]);
+ expect(line).toHaveAttribute('x2', centers[i]);
+ expect(line).toHaveAttribute('y1', '0');
+ expect(line).toHaveAttribute('y2', '320');
+ expect(line).toHaveAttribute('stroke', 'var(--color-border, #d0d0d8)');
+ expect(line).toHaveAttribute('stroke-opacity', '0.3');
+ expect(line).toHaveAttribute('stroke-dasharray', '4 4');
+ expect(line).toHaveAttribute('stroke-width', '1');
+ });
+ });
+
+ it('renders header labels from rich column defs at the chart bottom', () => {
+ const {container} = render(
+ <SankeyChart nodes={nodes} links={links} columns={richColumns}>
+ <SankeyGrid />
+ </SankeyChart>,
+ );
+ reportWidth(1000);
+
+ const texts = Array.from(container.querySelectorAll('text'));
+ expect(texts.map(t => t.textContent)).toEqual([
+ 'Source',
+ 'Middle',
+ 'Target',
+ ]);
+ expect(texts[0]).toHaveAttribute('x', '10');
+ expect(texts[1]).toHaveAttribute('x', '500');
+ expect(texts[2]).toHaveAttribute('x', '990');
+ expect(texts[0]).toHaveAttribute('y', '318');
+ expect(texts[0]).toHaveAttribute('text-anchor', 'middle');
+ });
+
+ it('suppresses headers but keeps the lines when showHeaders is off', () => {
+ const {container} = render(
+ <SankeyChart nodes={nodes} links={links} columns={richColumns}>
+ <SankeyGrid showHeaders={false} />
+ </SankeyChart>,
+ );
+ reportWidth(1000);
+
+ expect(container.querySelectorAll('text')).toHaveLength(0);
+ expect(container.querySelectorAll('line')).toHaveLength(3);
+ });
+
+ it('renders no headers for simple string[] columns', () => {
+ const {container} = render(
+ <SankeyChart nodes={nodes} links={links} columns={[['a'], ['b'], ['c']]}>
+ <SankeyGrid />
+ </SankeyChart>,
+ );
+ reportWidth(1000);
+
+ expect(container.querySelectorAll('text')).toHaveLength(0);
+ expect(container.querySelectorAll('line')).toHaveLength(3);
+ });
+
+ it('applies custom color, dash pattern, and opacity to the lines', () => {
+ const {container} = render(
+ <SankeyChart nodes={nodes} links={links} columns={richColumns}>
+ <SankeyGrid color="#123456" dashArray="2 6" opacity={0.5} />
+ </SankeyChart>,
+ );
+ reportWidth(1000);
+
+ const line = container.querySelector('line');
+ expect(line).toHaveAttribute('stroke', '#123456');
+ expect(line).toHaveAttribute('stroke-dasharray', '2 6');
+ expect(line).toHaveAttribute('stroke-opacity', '0.5');
+ });
+
+ it('renders no lines before the container reports a width', () => {
+ const {container} = render(
+ <SankeyChart nodes={nodes} links={links} columns={richColumns}>
+ <SankeyGrid />
+ </SankeyChart>,
+ );
+
+ expect(container.querySelectorAll('line')).toHaveLength(0);
+ });
+});
diff --git a/packages/lab/src/Sankey/SankeyLabel.test.tsx b/packages/lab/src/Sankey/SankeyLabel.test.tsx
new file mode 100644
index 0000000000..36221d87a7
--- /dev/null
+++ b/packages/lab/src/Sankey/SankeyLabel.test.tsx
@@ -0,0 +1,250 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file SankeyLabel.test.tsx
+ * @input Renders SankeyLabel inside SankeyChart with a stubbed ResizeObserver
+ * @output Render-smoke coverage for labels: rotated vs beside placement,
+ * percent rows, formatValue, on-dark/on-light text color (#4295)
+ * @position Colocated test for SankeyLabel.tsx
+ */
+
+import {describe, it, expect, beforeEach, afterEach, vi} from 'vitest';
+import {render, act} from '@testing-library/react';
+import {SankeyChart} from './SankeyChart';
+import {SankeyLabel} from './SankeyLabel';
+import type {SankeyNodeDatum, SankeyLinkDatum} from './types';
+
+// Tall bars: values of 8 with height=300 give valueScale 32, so every bar is
+// 256 tall — far taller than "A = 8" needs (5 chars × 6.5 + 8 = 40.5) —
+// which forces the rotated-label strategy for all three nodes.
+const tallNodes: SankeyNodeDatum[] = [
+ {id: 'a', label: 'A', value: 8, color: [0.5, 0.1, 100]},
+ {id: 'b', label: 'B', value: 8, color: [0.6, 0.2, 200]},
+ {id: 'c', label: 'C', value: 8, color: [0.7, 0.3, 300]},
+];
+const tallLinks: SankeyLinkDatum[] = [
+ {source: 'a', target: 'b', value: 4},
+ {source: 'b', target: 'c', value: 4},
+];
+
+// Short bars: height=100 gives valueScale 7, so bars are 56 tall while
+// "Alpha = 8" needs 9 chars × 6.5 + 8 = 66.5 — forcing beside labels.
+const shortNodes: SankeyNodeDatum[] = [
+ {id: 'a', label: 'Alpha', value: 8, color: [0.5, 0.1, 100]},
+ {id: 'b', label: 'Bravo', value: 8, color: [0.6, 0.2, 200]},
+ {id: 'c', label: 'Gamma', value: 8, color: [0.7, 0.3, 300]},
+];
+
+// Capture the ResizeObserver callback so tests can drive the reported width.
+let resizeCallback: ResizeObserverCallback | undefined;
+
+beforeEach(() => {
+ resizeCallback = undefined;
+ vi.stubGlobal(
+ 'ResizeObserver',
+ class {
+ constructor(cb: ResizeObserverCallback) {
+ resizeCallback = cb;
+ }
+ observe() {}
+ unobserve() {}
+ disconnect() {}
+ },
+ );
+});
+
+afterEach(() => {
+ vi.unstubAllGlobals();
+});
+
+function reportWidth(width: number) {
+ act(() => {
+ resizeCallback?.(
+ [{contentRect: {width}} as unknown as ResizeObserverEntry],
+ {} as ResizeObserver,
+ );
+ });
+}
+
+function textContents(container: HTMLElement): Array<string | null> {
+ return Array.from(container.querySelectorAll('text')).map(t => t.textContent);
+}
+
+describe('SankeyLabel rotated placement (tall bars)', () => {
+ it('rotates labels -90° onto the bar center when the text fits the bar', () => {
+ const {container} = render(
+ <SankeyChart nodes={tallNodes} links={tallLinks} height={300}>
+ <SankeyLabel />
+ </SankeyChart>,
+ );
+ reportWidth(1000);
+
+ expect(textContents(container)).toEqual([
+ 'A = 8',
+ 'B = 8',
+ '100%',
+ 'C = 8',
+ '100%',
+ ]);
+
+ // Bar centers: cx = x + nodeWidth/2, cy = 28 + 256/2 = 156.
+ const labelA = Array.from(container.querySelectorAll('text')).find(
+ t => t.textContent === 'A = 8',
+ );
+ expect(labelA?.closest('g[transform]')).toHaveAttribute(
+ 'transform',
+ 'translate(10, 156) rotate(-90)',
+ );
+ expect(labelA).toHaveAttribute('text-anchor', 'middle');
+ });
+
+ it('shows a percent of maxValue below downstream nodes only', () => {
+ const {container} = render(
+ <SankeyChart nodes={tallNodes} links={tallLinks} height={300}>
+ <SankeyLabel />
+ </SankeyChart>,
+ );
+ reportWidth(1000);
+
+ // Column 0 gets no percent; b and c are 8/8 = 100%.
+ const pcts = Array.from(container.querySelectorAll('text')).filter(
+ t => t.textContent === '100%',
+ );
+ expect(pcts).toHaveLength(2);
+ expect(pcts[0]).toHaveAttribute('x', '500');
+ expect(pcts[1]).toHaveAttribute('x', '990');
+ // y clamps to the chart: min(300 - 2, 28 + 256 + 12) = 296.
+ expect(pcts[0]).toHaveAttribute('y', '296');
+ });
+
+ it('hides the percent row when showPercent is off', () => {
+ const {container} = render(
+ <SankeyChart nodes={tallNodes} links={tallLinks} height={300}>
+ <SankeyLabel showPercent={false} />
+ </SankeyChart>,
+ );
+ reportWidth(1000);
+
+ expect(textContents(container)).toEqual(['A = 8', 'B = 8', 'C = 8']);
+ });
+
+ it('formats values through a custom formatValue function', () => {
+ const {container} = render(
+ <SankeyChart nodes={tallNodes} links={tallLinks} height={300}>
+ <SankeyLabel showPercent={false} formatValue={v => `${v}pts`} />
+ </SankeyChart>,
+ );
+ reportWidth(1000);
+
+ expect(textContents(container)).toEqual([
+ 'A = 8pts',
+ 'B = 8pts',
+ 'C = 8pts',
+ ]);
+ });
+
+ it('picks on-dark text for dark bars and on-light for light bars', () => {
+ const {container} = render(
+ <SankeyChart nodes={tallNodes} links={tallLinks} height={300}>
+ <SankeyLabel showPercent={false} />
+ </SankeyChart>,
+ );
+ reportWidth(1000);
+
+ const texts = Array.from(container.querySelectorAll('text'));
+ // Node a has oklch lightness 0.5 (< 0.6) → on-dark text.
+ expect(texts[0].getAttribute('style')).toMatch(/var\(--color-on-dark/);
+ // Node c has lightness 0.7 → on-light text.
+ expect(texts[2].getAttribute('style')).toMatch(/var\(--color-on-light/);
+ });
+});
+
+describe('SankeyLabel beside placement (short bars)', () => {
+ it('places short-bar labels beside the node on a surface pill', () => {
+ const {container} = render(
+ <SankeyChart nodes={shortNodes} links={tallLinks} height={100}>
+ <SankeyLabel showPercent={false} />
+ </SankeyChart>,
+ );
+ reportWidth(1000);
+
+ const labelAlpha = Array.from(container.querySelectorAll('text')).find(
+ t => t.textContent === 'Alpha = 8',
+ );
+ // First column: label starts 6px right of the bar (0 + 20 + 6).
+ expect(labelAlpha).toHaveAttribute('x', '26');
+ expect(labelAlpha).toHaveAttribute('y', '56');
+ expect(labelAlpha).toHaveAttribute('text-anchor', 'start');
+
+ // The pill sits behind the text: 9 chars × 6 + 10 = 64 wide, 16 tall.
+ const pill = labelAlpha?.previousElementSibling;
+ expect(pill?.tagName).toBe('rect');
+ expect(pill).toHaveAttribute('x', '22');
+ expect(pill).toHaveAttribute('y', '48');
+ expect(pill).toHaveAttribute('width', '64');
+ expect(pill).toHaveAttribute('height', '16');
+ expect(pill).toHaveAttribute('rx', '3');
+ expect(pill).toHaveAttribute(
+ 'fill',
+ 'var(--color-background-surface, #fff)',
+ );
+ expect(pill).toHaveAttribute('fill-opacity', '0.9');
+ });
+
+ it('anchors last-column labels to the left to avoid edge clipping', () => {
+ const {container} = render(
+ <SankeyChart nodes={shortNodes} links={tallLinks} height={100}>
+ <SankeyLabel showPercent={false} />
+ </SankeyChart>,
+ );
+ reportWidth(1000);
+
+ const labelGamma = Array.from(container.querySelectorAll('text')).find(
+ t => t.textContent === 'Gamma = 8',
+ );
+ // Last column: label ends 6px left of the bar (980 - 6).
+ expect(labelGamma).toHaveAttribute('x', '974');
+ expect(labelGamma).toHaveAttribute('text-anchor', 'end');
+ // Pill extends leftward from the label: 974 - 64 + 4 = 914.
+ expect(labelGamma?.previousElementSibling).toHaveAttribute('x', '914');
+ });
+});
+
+describe('SankeyLabel default value format', () => {
+ it('compacts thousands and gives small percents one decimal', () => {
+ // b = 1500/12000 = 12.5% (rounds to 13%), c = 600/12000 = 5.0%.
+ const nodes: SankeyNodeDatum[] = [
+ {id: 'a', label: 'A', value: 12000, color: [0.5, 0.1, 100]},
+ {id: 'b', label: 'B', value: 1500, color: [0.6, 0.2, 200]},
+ {id: 'c', label: 'C', value: 600, color: [0.7, 0.3, 300]},
+ ];
+ const links: SankeyLinkDatum[] = [
+ {source: 'a', target: 'b', value: 1500},
+ {source: 'a', target: 'c', value: 600},
+ ];
+ const {container} = render(
+ <SankeyChart nodes={nodes} links={links} height={300}>
+ <SankeyLabel />
+ </SankeyChart>,
+ );
+ reportWidth(1000);
+
+ expect(textContents(container)).toEqual([
+ 'A = 12k',
+ 'B = 1.5k',
+ '13%',
+ 'C = 600',
+ '5.0%',
+ ]);
+ });
+
+ it('renders no labels before the container reports a width', () => {
+ const {container} = render(
+ <SankeyChart nodes={tallNodes} links={tallLinks} height={300}>
+ <SankeyLabel />
+ </SankeyChart>,
+ );
+
+ expect(container.querySelectorAll('text')).toHaveLength(0);
+ });
+});
diff --git a/packages/lab/src/Sankey/SankeyLink.test.tsx b/packages/lab/src/Sankey/SankeyLink.test.tsx
new file mode 100644
index 0000000000..8124c352e6
--- /dev/null
+++ b/packages/lab/src/Sankey/SankeyLink.test.tsx
@@ -0,0 +1,175 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file SankeyLink.test.tsx
+ * @input Renders SankeyLink inside SankeyChart with a stubbed ResizeObserver
+ * @output Render-smoke coverage for link ribbons: bezier geometry, gradient
+ * defs and bias, source/target/flat color modes, tension (#4295)
+ * @position Colocated test for SankeyLink.tsx
+ */
+
+import {describe, it, expect, beforeEach, afterEach, vi} from 'vitest';
+import {render, act} from '@testing-library/react';
+import {SankeyChart} from './SankeyChart';
+import {SankeyLink} from './SankeyLink';
+import type {SankeyNodeDatum, SankeyLinkDatum} from './types';
+
+// Explicit oklch colors so assertions don't couple to the default palette.
+// values of 8 with height=300 give an exact valueScale of 32
+// (usableHeight = 300 - 28 - 16 = 256; 256 / 8 = 32), so every
+// coordinate below is integer-exact.
+const nodes: SankeyNodeDatum[] = [
+ {id: 'a', label: 'A', value: 8, color: [0.5, 0.1, 100]},
+ {id: 'b', label: 'B', value: 8, color: [0.6, 0.2, 200]},
+ {id: 'c', label: 'C', value: 8, color: [0.7, 0.3, 300]},
+];
+const links: SankeyLinkDatum[] = [
+ {source: 'a', target: 'b', value: 4},
+ {source: 'b', target: 'c', value: 4},
+];
+
+// Capture the ResizeObserver callback so tests can drive the reported width.
+let resizeCallback: ResizeObserverCallback | undefined;
+
+beforeEach(() => {
+ resizeCallback = undefined;
+ vi.stubGlobal(
+ 'ResizeObserver',
+ class {
+ constructor(cb: ResizeObserverCallback) {
+ resizeCallback = cb;
+ }
+ observe() {}
+ unobserve() {}
+ disconnect() {}
+ },
+ );
+});
+
+afterEach(() => {
+ vi.unstubAllGlobals();
+});
+
+function reportWidth(width: number) {
+ act(() => {
+ resizeCallback?.(
+ [{contentRect: {width}} as unknown as ResizeObserverEntry],
+ {} as ResizeObserver,
+ );
+ });
+}
+
+function renderLink(props?: React.ComponentProps<typeof SankeyLink>) {
+ const result = render(
+ <SankeyChart nodes={nodes} links={links} height={300}>
+ <SankeyLink {...props} />
+ </SankeyChart>,
+ );
+ reportWidth(1000);
+ return result;
+}
+
+describe('SankeyLink', () => {
+ it('renders one ribbon path per link with the bezier geometry from layout', () => {
+ const {container} = renderLink();
+
+ // Columns land at x = 0 / 490 / 980; nodes span y = 28..284; each
+ // link is 128 tall; tension 0.5 puts control points midway (dx = 235).
+ const paths = container.querySelectorAll('path');
+ expect(paths).toHaveLength(2);
+ expect(paths[0]).toHaveAttribute(
+ 'd',
+ 'M20,28 C255,28 255,28 490,28 L490,156 C255,156 255,156 20,156 Z',
+ );
+ expect(paths[1]).toHaveAttribute(
+ 'd',
+ 'M510,28 C745,28 745,28 980,28 L980,156 C745,156 745,156 510,156 Z',
+ );
+ });
+
+ it('defaults to per-link gradient defs spanning source to target', () => {
+ const {container} = renderLink();
+
+ const grads = container.querySelectorAll('linearGradient');
+ expect(grads).toHaveLength(2);
+ expect(grads[0]).toHaveAttribute('id', 'astryx-sankey-grad-0');
+ expect(grads[0]).toHaveAttribute('gradientUnits', 'userSpaceOnUse');
+ // Gradient runs from the source bar's right edge to the target bar.
+ expect(grads[0]).toHaveAttribute('x1', '20');
+ expect(grads[0]).toHaveAttribute('x2', '490');
+
+ // Default bias 0.5 → inner stops at 35% / 65%, alpha 0.7 * 0.9 = 0.63.
+ const stops = grads[0].querySelectorAll('stop');
+ expect(stops).toHaveLength(4);
+ expect(stops[0]).toHaveAttribute('offset', '0%');
+ expect(stops[0]).toHaveAttribute('stop-color', 'oklch(0.5 0.1 100 / 0.7)');
+ expect(stops[1]).toHaveAttribute('offset', '35%');
+ expect(stops[1]).toHaveAttribute('stop-color', 'oklch(0.5 0.1 100 / 0.63)');
+ expect(stops[2]).toHaveAttribute('offset', '65%');
+ expect(stops[2]).toHaveAttribute('stop-color', 'oklch(0.6 0.2 200 / 0.63)');
+ expect(stops[3]).toHaveAttribute('offset', '100%');
+ expect(stops[3]).toHaveAttribute('stop-color', 'oklch(0.6 0.2 200 / 0.7)');
+
+ const paths = container.querySelectorAll('path');
+ expect(paths[0]).toHaveAttribute('fill', 'url(#astryx-sankey-grad-0)');
+ expect(paths[1]).toHaveAttribute('fill', 'url(#astryx-sankey-grad-1)');
+ });
+
+ it('leans the gradient stops toward the target for a biased gradient', () => {
+ const {container} = renderLink({color: {gradient: 0.75}});
+
+ const stops = container
+ .querySelectorAll('linearGradient')[0]
+ .querySelectorAll('stop');
+ expect(stops[1]).toHaveAttribute('offset', '60%');
+ expect(stops[2]).toHaveAttribute('offset', '90%');
+ });
+
+ it('fills each ribbon with its source node color in source mode', () => {
+ const {container} = renderLink({color: 'source'});
+
+ expect(container.querySelector('linearGradient')).toBeNull();
+ const paths = container.querySelectorAll('path');
+ expect(paths[0]).toHaveAttribute('fill', 'oklch(0.5 0.1 100 / 0.7)');
+ expect(paths[1]).toHaveAttribute('fill', 'oklch(0.6 0.2 200 / 0.7)');
+ // Alpha is baked into the oklch fill — no separate opacity attribute.
+ expect(paths[0]).not.toHaveAttribute('opacity');
+ });
+
+ it('fills each ribbon with its target node color in target mode', () => {
+ const {container} = renderLink({color: 'target'});
+
+ const paths = container.querySelectorAll('path');
+ expect(paths[0]).toHaveAttribute('fill', 'oklch(0.6 0.2 200 / 0.7)');
+ expect(paths[1]).toHaveAttribute('fill', 'oklch(0.7 0.3 300 / 0.7)');
+ });
+
+ it('applies a flat CSS color via fill plus a path opacity attribute', () => {
+ const {container} = renderLink({color: '#ff8800', opacity: 0.5});
+
+ expect(container.querySelector('defs')).toBeNull();
+ const paths = container.querySelectorAll('path');
+ expect(paths[0]).toHaveAttribute('fill', '#ff8800');
+ expect(paths[0]).toHaveAttribute('opacity', '0.5');
+ });
+
+ it('draws straight ribbons when tension is 0', () => {
+ const {container} = renderLink({tension: 0});
+
+ // dx = 0 → control points sit on the endpoints.
+ expect(container.querySelectorAll('path')[0]).toHaveAttribute(
+ 'd',
+ 'M20,28 C20,28 490,28 490,28 L490,156 C490,156 20,156 20,156 Z',
+ );
+ });
+
+ it('renders no ribbons before the container reports a width', () => {
+ const {container} = render(
+ <SankeyChart nodes={nodes} links={links} height={300}>
+ <SankeyLink />
+ </SankeyChart>,
+ );
+
+ expect(container.querySelectorAll('path')).toHaveLength(0);
+ });
+});
diff --git a/packages/lab/src/Sankey/SankeyNode.test.tsx b/packages/lab/src/Sankey/SankeyNode.test.tsx
new file mode 100644
index 0000000000..c6ca7bf81a
--- /dev/null
+++ b/packages/lab/src/Sankey/SankeyNode.test.tsx
@@ -0,0 +1,137 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file SankeyNode.test.tsx
+ * @input Renders SankeyNode inside SankeyChart with a stubbed ResizeObserver
+ * @output Render-smoke coverage for node bars: glow + bar geometry, per-node
+ * oklch colors, the glow toggle, and the nodeColor override (#4295)
+ * @position Colocated test for SankeyNode.tsx
+ */
+
+import {describe, it, expect, beforeEach, afterEach, vi} from 'vitest';
+import {render, act} from '@testing-library/react';
+import {SankeyChart} from './SankeyChart';
+import {SankeyNode} from './SankeyNode';
+import type {SankeyNodeDatum, SankeyLinkDatum} from './types';
+
+// Explicit oklch colors so assertions don't couple to the default palette.
+// values of 8 with height=300 give an exact valueScale of 32, so bars sit
+// at y=28 with height 256 and columns at x = 0 / 490 / 980.
+const nodes: SankeyNodeDatum[] = [
+ {id: 'a', label: 'A', value: 8, color: [0.5, 0.1, 100]},
+ {id: 'b', label: 'B', value: 8, color: [0.6, 0.2, 200]},
+ {id: 'c', label: 'C', value: 8, color: [0.7, 0.3, 300]},
+];
+const links: SankeyLinkDatum[] = [
+ {source: 'a', target: 'b', value: 4},
+ {source: 'b', target: 'c', value: 4},
+];
+
+// Capture the ResizeObserver callback so tests can drive the reported width.
+let resizeCallback: ResizeObserverCallback | undefined;
+
+beforeEach(() => {
+ resizeCallback = undefined;
+ vi.stubGlobal(
+ 'ResizeObserver',
+ class {
+ constructor(cb: ResizeObserverCallback) {
+ resizeCallback = cb;
+ }
+ observe() {}
+ unobserve() {}
+ disconnect() {}
+ },
+ );
+});
+
+afterEach(() => {
+ vi.unstubAllGlobals();
+});
+
+function reportWidth(width: number) {
+ act(() => {
+ resizeCallback?.(
+ [{contentRect: {width}} as unknown as ResizeObserverEntry],
+ {} as ResizeObserver,
+ );
+ });
+}
+
+describe('SankeyNode', () => {
+ it('renders a glow rect and a bar rect per node with layout geometry', () => {
+ const {container} = render(
+ <SankeyChart nodes={nodes} links={links} height={300}>
+ <SankeyNode />
+ </SankeyChart>,
+ );
+ reportWidth(1000);
+
+ const rects = container.querySelectorAll('rect');
+ expect(rects).toHaveLength(6);
+
+ // Glow halo: bar inflated by 3px inline / 1px block, faint node color.
+ expect(rects[0]).toHaveAttribute('x', '-3');
+ expect(rects[0]).toHaveAttribute('y', '27');
+ expect(rects[0]).toHaveAttribute('width', '26');
+ expect(rects[0]).toHaveAttribute('height', '258');
+ expect(rects[0]).toHaveAttribute('rx', '4');
+ expect(rects[0]).toHaveAttribute('fill', 'oklch(0.5 0.1 100 / 0.12)');
+ expect(rects[0]).toHaveAttribute('opacity', '1');
+
+ // Bar: exact layout position, near-opaque node color.
+ expect(rects[1]).toHaveAttribute('x', '0');
+ expect(rects[1]).toHaveAttribute('y', '28');
+ expect(rects[1]).toHaveAttribute('width', '20');
+ expect(rects[1]).toHaveAttribute('height', '256');
+ expect(rects[1]).toHaveAttribute('rx', '1.5');
+ expect(rects[1]).toHaveAttribute('fill', 'oklch(0.5 0.1 100 / 0.9)');
+
+ // Remaining bars land on their column x positions with their own colors.
+ expect(rects[3]).toHaveAttribute('x', '490');
+ expect(rects[3]).toHaveAttribute('fill', 'oklch(0.6 0.2 200 / 0.9)');
+ expect(rects[5]).toHaveAttribute('x', '980');
+ expect(rects[5]).toHaveAttribute('fill', 'oklch(0.7 0.3 300 / 0.9)');
+ });
+
+ it('renders only the bar rects when glow is off', () => {
+ const {container} = render(
+ <SankeyChart nodes={nodes} links={links} height={300}>
+ <SankeyNode glow={false} />
+ </SankeyChart>,
+ );
+ reportWidth(1000);
+
+ const rects = container.querySelectorAll('rect');
+ expect(rects).toHaveLength(3);
+ expect(rects[0]).toHaveAttribute('x', '0');
+ expect(rects[0]).toHaveAttribute('rx', '1.5');
+ });
+
+ it('paints every node with the chart-level nodeColor override', () => {
+ const {container} = render(
+ <SankeyChart nodes={nodes} links={links} height={300} nodeColor="#334455">
+ <SankeyNode />
+ </SankeyChart>,
+ );
+ reportWidth(1000);
+
+ const rects = container.querySelectorAll('rect');
+ expect(rects).toHaveLength(6);
+ for (const rect of rects) {
+ expect(rect).toHaveAttribute('fill', '#334455');
+ }
+ // The glow drops to 0.12 opacity so the flat override still reads as a halo.
+ expect(rects[0]).toHaveAttribute('opacity', '0.12');
+ });
+
+ it('renders no rects before the container reports a width', () => {
+ const {container} = render(
+ <SankeyChart nodes={nodes} links={links} height={300}>
+ <SankeyNode />
+ </SankeyChart>,
+ );
+
+ expect(container.querySelectorAll('rect')).toHaveLength(0);
+ });
+});
diff --git a/packages/lab/src/Sankey/useSankey.test.tsx b/packages/lab/src/Sankey/useSankey.test.tsx
new file mode 100644
index 0000000000..b607423081
--- /dev/null
+++ b/packages/lab/src/Sankey/useSankey.test.tsx
@@ -0,0 +1,25 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file useSankey.test.tsx
+ * @input A component calling useSankey with no surrounding SankeyChart
+ * @output Pins the outside-provider guard and its message (#4295)
+ * @position Colocated test for SankeyContext.ts
+ */
+
+import {describe, it, expect} from 'vitest';
+import {render} from '@testing-library/react';
+import {useSankey} from './SankeyContext';
+
+describe('useSankey', () => {
+ it('throws when used outside <SankeyChart>', () => {
+ function Probe() {
+ useSankey();
+ return null;
+ }
+
+ expect(() => render(<Probe />)).toThrow(
+ 'Sankey components must be used inside <SankeyChart>',
+ );
+ });
+});
diff --git a/packages/lab/src/ThreeD/ThreeDAxis.test.tsx b/packages/lab/src/ThreeD/ThreeDAxis.test.tsx
new file mode 100644
index 0000000000..d1c43eb690
--- /dev/null
+++ b/packages/lab/src/ThreeD/ThreeDAxis.test.tsx
@@ -0,0 +1,97 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file ThreeDAxis.test.tsx
+ * @input ThreeDAxis inside a ThreeDChart at 600x400 with the default camera;
+ * domains computed from data as [0, 2] on every key
+ * @output Render-smoke coverage: three axis lines from a shared origin,
+ * key + domain labels, and the labels={false} switch
+ * @position Colocated test for ThreeDAxis.tsx
+ */
+
+import {describe, it, expect, beforeEach, afterEach, vi} from 'vitest';
+import {render, act} from '@testing-library/react';
+import {ThreeDChart} from './ThreeDChart';
+import {ThreeDAxis} from './ThreeDAxis';
+
+const data = [
+ {x: 0, y: 0, z: 0},
+ {x: 2, y: 2, z: 2},
+];
+
+// Capture the ResizeObserver callback so tests can drive the reported width.
+let resizeCallback: ResizeObserverCallback | undefined;
+
+beforeEach(() => {
+ resizeCallback = undefined;
+ vi.stubGlobal(
+ 'ResizeObserver',
+ class {
+ constructor(cb: ResizeObserverCallback) {
+ resizeCallback = cb;
+ }
+ observe() {}
+ unobserve() {}
+ disconnect() {}
+ },
+ );
+});
+
+afterEach(() => {
+ vi.unstubAllGlobals();
+});
+
+function reportWidth(width: number) {
+ act(() => {
+ resizeCallback?.(
+ [{contentRect: {width}} as unknown as ResizeObserverEntry],
+ {} as ResizeObserver,
+ );
+ });
+}
+
+function renderAxis(children: React.ReactNode) {
+ const result = render(
+ <ThreeDChart data={data} xKey="x" yKey="y" zKey="z">
+ {children}
+ </ThreeDChart>,
+ );
+ reportWidth(600);
+ return result;
+}
+
+describe('ThreeDAxis', () => {
+ it('renders the three axis lines radiating from a shared origin', () => {
+ const {container} = renderAxis(<ThreeDAxis />);
+
+ const lines = container.querySelectorAll('line');
+ expect(lines).toHaveLength(3);
+
+ // All three lines start at project(0, 0, 0).
+ const origins = Array.from(lines, l => [
+ parseFloat(l.getAttribute('x1') ?? ''),
+ parseFloat(l.getAttribute('y1') ?? ''),
+ ]);
+ expect(origins[1]).toEqual(origins[0]);
+ expect(origins[2]).toEqual(origins[0]);
+ expect(origins[0][0]).not.toBeNaN();
+ expect(origins[0][1]).not.toBeNaN();
+ });
+
+ it('labels each axis with its data key and domain', () => {
+ const {container} = renderAxis(<ThreeDAxis />);
+
+ const labels = Array.from(
+ container.querySelectorAll('text'),
+ t => t.textContent,
+ );
+ expect(labels).toEqual(['x [0-2]', 'y [0-2]', 'z [0-2]']);
+ });
+
+ it('renders no labels when labels is false', () => {
+ const {container} = renderAxis(<ThreeDAxis labels={false} />);
+
+ expect(container.querySelectorAll('line')).toHaveLength(3);
+ expect(container.querySelector('text')).toBeNull();
+ });
+});
diff --git a/packages/lab/src/ThreeD/ThreeDBar.test.tsx b/packages/lab/src/ThreeD/ThreeDBar.test.tsx
new file mode 100644
index 0000000000..863c47661d
--- /dev/null
+++ b/packages/lab/src/ThreeD/ThreeDBar.test.tsx
@@ -0,0 +1,96 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file ThreeDBar.test.tsx
+ * @input ThreeDBar inside a ThreeDChart at 600x400 with the default camera
+ * @output Render-smoke coverage: three shaded faces per bar (front 0.9,
+ * right 0.7, top 1), four corners per face
+ * @position Colocated test for ThreeDBar.tsx
+ */
+
+import {describe, it, expect, beforeEach, afterEach, vi} from 'vitest';
+import {render, act} from '@testing-library/react';
+import {ThreeDChart} from './ThreeDChart';
+import {ThreeDBar} from './ThreeDBar';
+
+const data = [
+ {x: 0, y: 1, z: 0},
+ {x: 2, y: 2, z: 2},
+];
+
+// Capture the ResizeObserver callback so tests can drive the reported width.
+let resizeCallback: ResizeObserverCallback | undefined;
+
+beforeEach(() => {
+ resizeCallback = undefined;
+ vi.stubGlobal(
+ 'ResizeObserver',
+ class {
+ constructor(cb: ResizeObserverCallback) {
+ resizeCallback = cb;
+ }
+ observe() {}
+ unobserve() {}
+ disconnect() {}
+ },
+ );
+});
+
+afterEach(() => {
+ vi.unstubAllGlobals();
+});
+
+function reportWidth(width: number) {
+ act(() => {
+ resizeCallback?.(
+ [{contentRect: {width}} as unknown as ResizeObserverEntry],
+ {} as ResizeObserver,
+ );
+ });
+}
+
+function renderBars(children: React.ReactNode) {
+ const result = render(
+ <ThreeDChart data={data} xKey="x" yKey="y" zKey="z">
+ {children}
+ </ThreeDChart>,
+ );
+ reportWidth(600);
+ return result;
+}
+
+describe('ThreeDBar', () => {
+ it('renders three face polygons per datum', () => {
+ const {container} = renderBars(<ThreeDBar color="#00ff00" />);
+
+ const barGroups = container.querySelectorAll('svg g g');
+ expect(barGroups).toHaveLength(2);
+ expect(container.querySelectorAll('polygon')).toHaveLength(6);
+ });
+
+ it('shades each bar face: front 0.9, right 0.7, top 1', () => {
+ const {container} = renderBars(<ThreeDBar color="#00ff00" />);
+
+ for (const bar of container.querySelectorAll('svg g g')) {
+ const opacities = Array.from(bar.querySelectorAll('polygon'), p =>
+ p.getAttribute('fill-opacity'),
+ );
+ expect(opacities).toEqual(['0.9', '0.7', '1']);
+ }
+ });
+
+ it('gives every face four projected corners and the bar color', () => {
+ const {container} = renderBars(<ThreeDBar color="#00ff00" />);
+
+ for (const polygon of container.querySelectorAll('polygon')) {
+ const pairs = (polygon.getAttribute('points') ?? '').split(' ');
+ expect(pairs).toHaveLength(4);
+ for (const pair of pairs) {
+ const [px, py] = pair.split(',').map(parseFloat);
+ expect(px).not.toBeNaN();
+ expect(py).not.toBeNaN();
+ }
+ expect(polygon).toHaveAttribute('fill', '#00ff00');
+ }
+ });
+});
diff --git a/packages/lab/src/ThreeD/ThreeDChart.test.tsx b/packages/lab/src/ThreeD/ThreeDChart.test.tsx
index 9ca7a5ad1f..52c98ca1c2 100644
--- a/packages/lab/src/ThreeD/ThreeDChart.test.tsx
+++ b/packages/lab/src/ThreeD/ThreeDChart.test.tsx
@@ -249,3 +249,41 @@ describe('ThreeDChart keyboard camera', () => {
expect(azimuth()).toBe(35);
});
});
+
+describe('ThreeDChart container sizing', () => {
+ it('renders no svg until the container reports a width', () => {
+ render(
+ <ThreeDChart data={data} xKey="x" yKey="y" zKey="z">
+ <CameraProbe />
+ </ThreeDChart>,
+ );
+ expect(screen.queryByRole('img')).not.toBeInTheDocument();
+
+ reportWidth(600);
+
+ const svg = screen.getByRole('img');
+ expect(svg).toHaveAttribute('width', '600');
+ // Default height is 400.
+ expect(svg).toHaveAttribute('height', '400');
+ });
+
+ it('sizes the svg from the height prop', () => {
+ renderChart({height: 250});
+ const svg = screen.getByRole('img');
+ expect(svg).toHaveAttribute('width', '600');
+ expect(svg).toHaveAttribute('height', '250');
+ });
+});
+
+describe('use3D', () => {
+ it('throws when used outside <ThreeDChart>', () => {
+ function Probe() {
+ use3D();
+ return null;
+ }
+
+ expect(() => render(<Probe />)).toThrow(
+ '3D components must be used inside <ThreeDChart>',
+ );
+ });
+});
diff --git a/packages/lab/src/ThreeD/ThreeDGrid.test.tsx b/packages/lab/src/ThreeD/ThreeDGrid.test.tsx
new file mode 100644
index 0000000000..214dd60ade
--- /dev/null
+++ b/packages/lab/src/ThreeD/ThreeDGrid.test.tsx
@@ -0,0 +1,86 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file ThreeDGrid.test.tsx
+ * @input ThreeDGrid inside a ThreeDChart at 600x400 with the default camera
+ * @output Render-smoke coverage: (divisions + 1) * 2 floor lines with finite
+ * projected endpoints
+ * @position Colocated test for ThreeDGrid.tsx
+ */
+
+import {describe, it, expect, beforeEach, afterEach, vi} from 'vitest';
+import {render, act} from '@testing-library/react';
+import {ThreeDChart} from './ThreeDChart';
+import {ThreeDGrid} from './ThreeDGrid';
+
+const data = [
+ {x: 0, y: 0, z: 0},
+ {x: 1, y: 1, z: 1},
+];
+
+// Capture the ResizeObserver callback so tests can drive the reported width.
+let resizeCallback: ResizeObserverCallback | undefined;
+
+beforeEach(() => {
+ resizeCallback = undefined;
+ vi.stubGlobal(
+ 'ResizeObserver',
+ class {
+ constructor(cb: ResizeObserverCallback) {
+ resizeCallback = cb;
+ }
+ observe() {}
+ unobserve() {}
+ disconnect() {}
+ },
+ );
+});
+
+afterEach(() => {
+ vi.unstubAllGlobals();
+});
+
+function reportWidth(width: number) {
+ act(() => {
+ resizeCallback?.(
+ [{contentRect: {width}} as unknown as ResizeObserverEntry],
+ {} as ResizeObserver,
+ );
+ });
+}
+
+function renderGrid(children: React.ReactNode) {
+ const result = render(
+ <ThreeDChart data={data} xKey="x" yKey="y" zKey="z">
+ {children}
+ </ThreeDChart>,
+ );
+ reportWidth(600);
+ return result;
+}
+
+describe('ThreeDGrid', () => {
+ it('renders two lines per division boundary (12 for the default 5 divisions)', () => {
+ const {container} = renderGrid(<ThreeDGrid />);
+
+ expect(container.querySelectorAll('line')).toHaveLength(12);
+ });
+
+ it('renders (divisions + 1) * 2 lines for a custom division count', () => {
+ const {container} = renderGrid(<ThreeDGrid divisions={2} />);
+
+ expect(container.querySelectorAll('line')).toHaveLength(6);
+ });
+
+ it('projects every line endpoint to finite pixel coordinates', () => {
+ const {container} = renderGrid(<ThreeDGrid />);
+
+ for (const line of container.querySelectorAll('line')) {
+ for (const attr of ['x1', 'y1', 'x2', 'y2']) {
+ expect(Number.isFinite(parseFloat(line.getAttribute(attr) ?? ''))).toBe(
+ true,
+ );
+ }
+ }
+ });
+});
diff --git a/packages/lab/src/ThreeD/ThreeDScatter.test.tsx b/packages/lab/src/ThreeD/ThreeDScatter.test.tsx
new file mode 100644
index 0000000000..b04ef02c98
--- /dev/null
+++ b/packages/lab/src/ThreeD/ThreeDScatter.test.tsx
@@ -0,0 +1,109 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file ThreeDScatter.test.tsx
+ * @input ThreeDScatter inside a ThreeDChart at 600x400 with the default
+ * camera (azimuth 35, elevation 25)
+ * @output Render-smoke coverage: one circle per datum, color, and the
+ * painter's-algorithm depth sort (radius grows with depth, so DOM order
+ * must be strictly increasing in radius for this dataset)
+ * @position Colocated test for ThreeDScatter.tsx
+ */
+
+import {describe, it, expect, beforeEach, afterEach, vi} from 'vitest';
+import {render, act} from '@testing-library/react';
+import {ThreeDChart} from './ThreeDChart';
+import {ThreeDScatter} from './ThreeDScatter';
+
+// Chosen so that data order is NOT depth order under the default camera:
+// depths are roughly -0.32, +0.32, -0.16 — sorted order is rows 0, 2, 1.
+const data = [
+ {x: 0, y: 0, z: 0},
+ {x: 2, y: 2, z: 2},
+ {x: 1, y: 2, z: 0},
+];
+
+// Capture the ResizeObserver callback so tests can drive the reported width.
+let resizeCallback: ResizeObserverCallback | undefined;
+
+beforeEach(() => {
+ resizeCallback = undefined;
+ vi.stubGlobal(
+ 'ResizeObserver',
+ class {
+ constructor(cb: ResizeObserverCallback) {
+ resizeCallback = cb;
+ }
+ observe() {}
+ unobserve() {}
+ disconnect() {}
+ },
+ );
+});
+
+afterEach(() => {
+ vi.unstubAllGlobals();
+});
+
+function reportWidth(width: number) {
+ act(() => {
+ resizeCallback?.(
+ [{contentRect: {width}} as unknown as ResizeObserverEntry],
+ {} as ResizeObserver,
+ );
+ });
+}
+
+function renderScatter(children: React.ReactNode) {
+ const result = render(
+ <ThreeDChart data={data} xKey="x" yKey="y" zKey="z">
+ {children}
+ </ThreeDChart>,
+ );
+ reportWidth(600);
+ return result;
+}
+
+describe('ThreeDScatter', () => {
+ it('renders one circle per datum with the given color', () => {
+ const {container} = renderScatter(<ThreeDScatter color="#ff0000" />);
+
+ const circles = container.querySelectorAll('circle');
+ expect(circles).toHaveLength(3);
+ for (const circle of circles) {
+ expect(circle).toHaveAttribute('fill', '#ff0000');
+ expect(parseFloat(circle.getAttribute('cx') ?? '')).not.toBeNaN();
+ expect(parseFloat(circle.getAttribute('cy') ?? '')).not.toBeNaN();
+ }
+ });
+
+ it('draws far points first: DOM order is sorted by depth (radius ascends)', () => {
+ const {container} = renderScatter(<ThreeDScatter color="#ff0000" />);
+
+ // r = radius * (0.75 + (depth + 0.5) * 0.25) grows monotonically with
+ // depth, and this dataset's data order is not its depth order — an
+ // unsorted render would fail this.
+ const rs = Array.from(container.querySelectorAll('circle'), c =>
+ parseFloat(c.getAttribute('r') ?? ''),
+ );
+ expect(rs).toHaveLength(3);
+ expect(rs[0]).toBeLessThan(rs[1]);
+ expect(rs[1]).toBeLessThan(rs[2]);
+ });
+
+ it('scales circle radius and opacity from the radius and opacity props', () => {
+ const {container} = renderScatter(
+ <ThreeDScatter color="#ff0000" radius={10} opacity={0.5} />,
+ );
+
+ for (const circle of container.querySelectorAll('circle')) {
+ // depthFactor is in (0.5, 1], so r <= radius and opacity <= 0.5.
+ const r = parseFloat(circle.getAttribute('r') ?? '');
+ const fillOpacity = parseFloat(circle.getAttribute('fill-opacity') ?? '');
+ expect(r).toBeGreaterThan(5);
+ expect(r).toBeLessThanOrEqual(10);
+ expect(fillOpacity).toBeGreaterThan(0.25);
+ expect(fillOpacity).toBeLessThanOrEqual(0.5);
+ }
+ });
+});
diff --git a/packages/lab/src/ThreeD/ThreeDScatterGL.test.tsx b/packages/lab/src/ThreeD/ThreeDScatterGL.test.tsx
new file mode 100644
index 0000000000..3a54f37899
--- /dev/null
+++ b/packages/lab/src/ThreeD/ThreeDScatterGL.test.tsx
@@ -0,0 +1,94 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file ThreeDScatterGL.test.tsx
+ * @input ThreeDScatterGL inside a ThreeDChart with
+ * HTMLCanvasElement.prototype.getContext stubbed to return null (jsdom has
+ * no WebGL)
+ * @output Mount smoke coverage: the sibling canvas is created and sized, the
+ * null-context guard prevents a crash, and unmount removes the canvas
+ * @position Colocated test for ThreeDScatterGL.tsx
+ */
+
+import {describe, it, expect, beforeEach, afterEach, vi} from 'vitest';
+import {render, act} from '@testing-library/react';
+import {ThreeDChart} from './ThreeDChart';
+import {ThreeDScatterGL} from './ThreeDScatterGL';
+
+const data = [
+ {x: 0, y: 0, z: 0},
+ {x: 2, y: 2, z: 2},
+];
+
+// Capture the ResizeObserver callback so tests can drive the reported width.
+let resizeCallback: ResizeObserverCallback | undefined;
+
+// jsdom has no WebGL — return null so the component's null-context guard runs.
+const originalGetContext = HTMLCanvasElement.prototype.getContext;
+
+beforeEach(() => {
+ resizeCallback = undefined;
+ vi.stubGlobal(
+ 'ResizeObserver',
+ class {
+ constructor(cb: ResizeObserverCallback) {
+ resizeCallback = cb;
+ }
+ observe() {}
+ unobserve() {}
+ disconnect() {}
+ },
+ );
+ HTMLCanvasElement.prototype.getContext = (() =>
+ null) as typeof HTMLCanvasElement.prototype.getContext;
+});
+
+afterEach(() => {
+ HTMLCanvasElement.prototype.getContext = originalGetContext;
+ vi.unstubAllGlobals();
+});
+
+function reportWidth(width: number) {
+ act(() => {
+ resizeCallback?.(
+ [{contentRect: {width}} as unknown as ResizeObserverEntry],
+ {} as ResizeObserver,
+ );
+ });
+}
+
+describe('ThreeDScatterGL', () => {
+ it('mounts a sibling canvas sized to the chart even when WebGL is unavailable', () => {
+ const {container} = render(
+ <ThreeDChart data={data} xKey="x" yKey="y" zKey="z">
+ <ThreeDScatterGL color="#ff0000" />
+ </ThreeDChart>,
+ );
+ reportWidth(600);
+
+ const canvas = container.querySelector('canvas');
+ expect(canvas).not.toBeNull();
+ // Canvas sits next to the svg, not inside it.
+ expect(canvas?.parentElement).toBe(
+ container.querySelector('svg')?.parentElement,
+ );
+ // CSS size is logical pixels; the buffer is supersampled.
+ expect(canvas?.style.width).toBe('600px');
+ expect(canvas?.style.height).toBe('400px');
+ });
+
+ it('removes the canvas on unmount', () => {
+ const {container, unmount} = render(
+ <ThreeDChart data={data} xKey="x" yKey="y" zKey="z">
+ <ThreeDScatterGL color="#ff0000" />
+ </ThreeDChart>,
+ );
+ reportWidth(600);
+
+ expect(container.querySelector('canvas')).not.toBeNull();
+
+ unmount();
+
+ expect(document.querySelector('canvas')).toBeNull();
+ });
+});
diff --git a/packages/lab/src/ThreeD/ThreeDSurface.test.tsx b/packages/lab/src/ThreeD/ThreeDSurface.test.tsx
new file mode 100644
index 0000000000..06ca505a72
--- /dev/null
+++ b/packages/lab/src/ThreeD/ThreeDSurface.test.tsx
@@ -0,0 +1,164 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file ThreeDSurface.test.tsx
+ * @input ThreeDSurface inside a ThreeDChart at 600x400; grid datasets built
+ * from distinct x/z values
+ * @output Render-smoke coverage: quad-face triangulation counts, four
+ * corners per face, color ramp fill, wireframe mode, degenerate-grid and
+ * missing-cell guards
+ * @position Colocated test for ThreeDSurface.tsx
+ */
+
+import {describe, it, expect, beforeEach, afterEach, vi} from 'vitest';
+import {render, act} from '@testing-library/react';
+import {ThreeDChart} from './ThreeDChart';
+import {ThreeDSurface} from './ThreeDSurface';
+
+/** Full grid over x, z in {0, 1, 2} — a 3x3 mesh with 4 quad faces. */
+const grid3x3: Record<string, number>[] = [];
+for (const x of [0, 1, 2]) {
+ for (const z of [0, 1, 2]) {
+ grid3x3.push({x, y: x + z, z});
+ }
+}
+
+// Capture the ResizeObserver callback so tests can drive the reported width.
+let resizeCallback: ResizeObserverCallback | undefined;
+
+beforeEach(() => {
+ resizeCallback = undefined;
+ vi.stubGlobal(
+ 'ResizeObserver',
+ class {
+ constructor(cb: ResizeObserverCallback) {
+ resizeCallback = cb;
+ }
+ observe() {}
+ unobserve() {}
+ disconnect() {}
+ },
+ );
+});
+
+afterEach(() => {
+ vi.unstubAllGlobals();
+});
+
+function reportWidth(width: number) {
+ act(() => {
+ resizeCallback?.(
+ [{contentRect: {width}} as unknown as ResizeObserverEntry],
+ {} as ResizeObserver,
+ );
+ });
+}
+
+function renderSurface(
+ data: Record<string, number>[],
+ children: React.ReactNode,
+) {
+ const result = render(
+ <ThreeDChart data={data} xKey="x" yKey="y" zKey="z">
+ {children}
+ </ThreeDChart>,
+ );
+ reportWidth(600);
+ return result;
+}
+
+describe('ThreeDSurface', () => {
+ it('triangulates a 3x3 grid into four quad faces', () => {
+ const {container} = renderSurface(
+ grid3x3,
+ <ThreeDSurface colorRange={['#336699']} />,
+ );
+
+ const polygons = container.querySelectorAll('polygon');
+ expect(polygons).toHaveLength(4);
+ for (const polygon of polygons) {
+ const pairs = (polygon.getAttribute('points') ?? '').split(' ');
+ expect(pairs).toHaveLength(4);
+ }
+ });
+
+ it('triangulates a 2x2 grid into a single face', () => {
+ const data = [
+ {x: 0, y: 0, z: 0},
+ {x: 1, y: 1, z: 0},
+ {x: 0, y: 1, z: 1},
+ {x: 1, y: 2, z: 1},
+ ];
+ const {container} = renderSurface(
+ data,
+ <ThreeDSurface colorRange={['#336699']} />,
+ );
+
+ expect(container.querySelectorAll('polygon')).toHaveLength(1);
+ });
+
+ it('fills faces from the color ramp', () => {
+ const {container} = renderSurface(
+ grid3x3,
+ <ThreeDSurface colorRange={['#336699']} />,
+ );
+
+ for (const polygon of container.querySelectorAll('polygon')) {
+ expect(polygon).toHaveAttribute('fill', '#336699');
+ }
+ });
+
+ it('picks the nearest ramp color by face height', () => {
+ // Face heights (normalized avg y over yDomain [0,4]): 0.25, 0.5, 0.5,
+ // 0.75 → with a 2-stop ramp, 0.25 snaps to the low color, the rest high.
+ const {container} = renderSurface(
+ grid3x3,
+ <ThreeDSurface colorRange={['#aaaaaa', '#bbbbbb']} />,
+ );
+
+ const fills = Array.from(container.querySelectorAll('polygon'), p =>
+ p.getAttribute('fill'),
+ );
+ expect(fills.filter(f => f === '#aaaaaa')).toHaveLength(1);
+ expect(fills.filter(f => f === '#bbbbbb')).toHaveLength(3);
+ });
+
+ it('draws unfilled outlines in wireframe mode', () => {
+ const {container} = renderSurface(
+ grid3x3,
+ <ThreeDSurface colorRange={['#336699']} wireframe />,
+ );
+
+ const polygons = container.querySelectorAll('polygon');
+ expect(polygons).toHaveLength(4);
+ for (const polygon of polygons) {
+ expect(polygon).toHaveAttribute('fill', 'none');
+ expect(polygon).toHaveAttribute('stroke', '#336699');
+ }
+ });
+
+ it('renders nothing when the data has fewer than two distinct z values', () => {
+ const flat = [
+ {x: 0, y: 1, z: 0},
+ {x: 1, y: 2, z: 0},
+ {x: 2, y: 1, z: 0},
+ ];
+ const {container} = renderSurface(
+ flat,
+ <ThreeDSurface colorRange={['#336699']} />,
+ );
+
+ expect(container.querySelector('polygon')).toBeNull();
+ });
+
+ it('skips faces with a missing grid cell', () => {
+ const holed = grid3x3.filter(d => !(d.x === 2 && d.z === 2));
+ const {container} = renderSurface(
+ holed,
+ <ThreeDSurface colorRange={['#336699']} />,
+ );
+
+ // Only the face touching the missing (2,2) corner is dropped.
+ expect(container.querySelectorAll('polygon')).toHaveLength(3);
+ });
+});
diff --git a/packages/vega/package.json b/packages/vega/package.json
index 7a6ab8968c..c5e3505514 100644
--- a/packages/vega/package.json
+++ b/packages/vega/package.json
@@ -44,6 +44,8 @@
"scripts": {
"build": "tsup && tsc --project tsconfig.json --emitDeclarationOnly --declaration --noEmit false --outDir dist",
"dev": "tsup --watch",
+ "test": "vitest run --root ../..",
+ "test:watch": "vitest --root ../..",
"typecheck": "tsc --noEmit"
},
"peerDependencies": {
diff --git a/packages/vega/src/VegaChart.test.tsx b/packages/vega/src/VegaChart.test.tsx
new file mode 100644
index 0000000000..c9fd6abcf0
--- /dev/null
+++ b/packages/vega/src/VegaChart.test.tsx
@@ -0,0 +1,345 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file VegaChart.test.tsx
+ * @input Uses vitest, @testing-library/react, VegaChart, mocked vega + vega-lite
+ * @output Functional tests for the VegaChart View lifecycle and error contract
+ * @position Colocated test for VegaChart.tsx (issue #4295 vega coverage)
+ */
+
+import {describe, it, expect, vi, beforeEach} from 'vitest';
+import {render, act} from '@testing-library/react';
+import React from 'react';
+import {VegaChart} from './VegaChart';
+import type {AnySpec} from './types';
+
+const {parseMock, compileMock, views, FakeView} = vi.hoisted(() => {
+ /**
+ * Stand-in for vega's View. Records constructor args and lifecycle calls,
+ * and exposes a manually controlled runAsync() promise so tests decide
+ * when (and how) each run settles.
+ */
+ class FakeView {
+ runtime: unknown;
+ options: Record<string, unknown>;
+ runPromise: Promise<void>;
+ resolveRun!: () => void;
+ rejectRun!: (err: unknown) => void;
+ data = vi.fn().mockReturnThis();
+ finalize = vi.fn();
+ runAsync = vi.fn(() => this.runPromise);
+
+ constructor(runtime: unknown, options: Record<string, unknown>) {
+ this.runtime = runtime;
+ this.options = options;
+ this.runPromise = new Promise<void>((resolve, reject) => {
+ this.resolveRun = resolve;
+ this.rejectRun = reject;
+ });
+ views.push(this);
+ }
+ }
+
+ const views: FakeView[] = [];
+ const parseMock = vi.fn((spec: unknown) => ({runtimeFor: spec}));
+ const compileMock = vi.fn((spec: unknown) => ({spec: {compiledFrom: spec}}));
+ return {parseMock, compileMock, views, FakeView};
+});
+
+vi.mock('vega', () => ({parse: parseMock, View: FakeView}));
+vi.mock('vega-lite', () => ({compile: compileMock}));
+
+const VEGA_LITE_SPEC = {
+ $schema: 'https://vega.github.io/schema/vega-lite/v5.json',
+ mark: 'bar',
+} as unknown as AnySpec;
+
+const VEGA_SPEC = {
+ $schema: 'https://vega.github.io/schema/vega/v6.json',
+ marks: [],
+} as unknown as AnySpec;
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ views.length = 0;
+});
+
+describe('VegaChart', () => {
+ describe('spec handling', () => {
+ it('compiles vega-lite specs with compileOptions and parses the compiled output', () => {
+ const compileOptions = {config: {background: 'red'}};
+ render(
+ <VegaChart spec={VEGA_LITE_SPEC} compileOptions={compileOptions} />,
+ );
+
+ expect(compileMock).toHaveBeenCalledTimes(1);
+ expect(compileMock).toHaveBeenCalledWith(VEGA_LITE_SPEC, compileOptions);
+ const compiled = compileMock.mock.results[0].value.spec;
+ expect(parseMock).toHaveBeenCalledTimes(1);
+ expect(parseMock.mock.calls[0][0]).toBe(compiled);
+ });
+
+ it('renders plain vega specs directly without invoking the vega-lite compiler', () => {
+ render(<VegaChart spec={VEGA_SPEC} />);
+
+ expect(compileMock).not.toHaveBeenCalled();
+ expect(parseMock).toHaveBeenCalledTimes(1);
+ expect(parseMock.mock.calls[0][0]).toBe(VEGA_SPEC);
+ // No data prop -> no dataset loading either.
+ expect(views).toHaveLength(1);
+ expect(views[0].data).not.toHaveBeenCalled();
+ });
+
+ it('forwards parseConfig and parseOptions to vega.parse', () => {
+ const parseConfig = {background: '#1a1a1a'};
+ const parseOptions = {ast: true};
+ render(
+ <VegaChart
+ spec={VEGA_SPEC}
+ parseConfig={parseConfig}
+ parseOptions={parseOptions}
+ />,
+ );
+
+ expect(parseMock).toHaveBeenCalledWith(
+ VEGA_SPEC,
+ parseConfig,
+ parseOptions,
+ );
+ });
+ });
+
+ describe('View construction', () => {
+ it('constructs the View from the parsed runtime with hover on and the rendered div as container', () => {
+ const {container} = render(<VegaChart spec={VEGA_SPEC} />);
+
+ expect(views).toHaveLength(1);
+ expect(views[0].runtime).toBe(parseMock.mock.results[0].value);
+ expect(views[0].options).toEqual({
+ hover: true,
+ container: container.firstElementChild,
+ });
+ });
+
+ it('lets viewOptions override the hover default while the container stays injected', () => {
+ const {container} = render(
+ <VegaChart
+ spec={VEGA_SPEC}
+ viewOptions={{hover: false, logLevel: 2}}
+ />,
+ );
+
+ expect(views).toHaveLength(1);
+ expect(views[0].options).toEqual({
+ hover: false,
+ logLevel: 2,
+ container: container.firstElementChild,
+ });
+ });
+
+ it('loads each named dataset via view.data before the first run', () => {
+ const table = [{a: 'A', b: 28}];
+ const other = [{x: 1}];
+ render(<VegaChart spec={VEGA_SPEC} data={{table, other}} />);
+
+ expect(views).toHaveLength(1);
+ const view = views[0];
+ expect(view.data).toHaveBeenCalledTimes(2);
+ expect(view.data).toHaveBeenCalledWith('table', table);
+ expect(view.data).toHaveBeenCalledWith('other', other);
+ // Datasets are loaded before the run kicks off.
+ expect(Math.max(...view.data.mock.invocationCallOrder)).toBeLessThan(
+ view.runAsync.mock.invocationCallOrder[0],
+ );
+ });
+
+ it('tears down the old View and builds a new one when the spec identity changes', () => {
+ const {rerender} = render(<VegaChart spec={VEGA_SPEC} />);
+ expect(views).toHaveLength(1);
+
+ rerender(<VegaChart spec={{...VEGA_SPEC}} />);
+
+ expect(views).toHaveLength(2);
+ expect(views[0].finalize).toHaveBeenCalledTimes(1);
+ expect(views[1].finalize).not.toHaveBeenCalled();
+ expect(parseMock).toHaveBeenCalledTimes(2);
+ });
+ });
+
+ describe('error contract', () => {
+ it('reports an unrecognized $schema through onError without constructing a View', () => {
+ const onError = vi.fn();
+ const badSpec = {$schema: 'https://example.com/nope.json'} as AnySpec;
+ const {container} = render(
+ <VegaChart spec={badSpec} onError={onError} />,
+ );
+
+ expect(onError).toHaveBeenCalledTimes(1);
+ const error = onError.mock.calls[0][0];
+ expect(error).toBeInstanceOf(Error);
+ expect(error.message).toContain('Unrecognized $schema URL');
+ expect(compileMock).not.toHaveBeenCalled();
+ expect(parseMock).not.toHaveBeenCalled();
+ expect(views).toHaveLength(0);
+ // The container div still renders; it just stays empty.
+ expect(container.firstElementChild?.tagName).toBe('DIV');
+ });
+
+ it('routes a synchronous compile failure to onError without constructing a View', () => {
+ const onError = vi.fn();
+ const boom = new Error('compile exploded');
+ compileMock.mockImplementationOnce(() => {
+ throw boom;
+ });
+ render(<VegaChart spec={VEGA_LITE_SPEC} onError={onError} />);
+
+ expect(onError).toHaveBeenCalledTimes(1);
+ expect(onError).toHaveBeenCalledWith(boom);
+ expect(views).toHaveLength(0);
+ });
+
+ it('routes a rejected runAsync to onError and suppresses onReady', async () => {
+ const onReady = vi.fn();
+ const onError = vi.fn();
+ render(
+ <VegaChart spec={VEGA_SPEC} onReady={onReady} onError={onError} />,
+ );
+
+ const failure = new Error('render failed');
+ await act(async () => {
+ views[0].rejectRun(failure);
+ });
+
+ expect(onError).toHaveBeenCalledTimes(1);
+ expect(onError).toHaveBeenCalledWith(failure);
+ expect(onReady).not.toHaveBeenCalled();
+ });
+
+ it('wraps non-Error rejection values in an Error before calling onError', async () => {
+ const onError = vi.fn();
+ render(<VegaChart spec={VEGA_SPEC} onError={onError} />);
+
+ await act(async () => {
+ views[0].rejectRun('oops');
+ });
+
+ expect(onError).toHaveBeenCalledTimes(1);
+ const error = onError.mock.calls[0][0];
+ expect(error).toBeInstanceOf(Error);
+ expect(error.message).toBe('oops');
+ });
+
+ it('suppresses onError for rejections that settle after unmount', async () => {
+ const onError = vi.fn();
+ const {unmount} = render(
+ <VegaChart spec={VEGA_SPEC} onError={onError} />,
+ );
+
+ unmount();
+ await act(async () => {
+ views[0].rejectRun(new Error('too late'));
+ });
+
+ expect(onError).not.toHaveBeenCalled();
+ });
+ });
+
+ describe('ready + teardown lifecycle', () => {
+ it('calls onReady with the live View once runAsync resolves', async () => {
+ const onReady = vi.fn();
+ render(<VegaChart spec={VEGA_SPEC} onReady={onReady} />);
+
+ expect(onReady).not.toHaveBeenCalled();
+ await act(async () => {
+ views[0].resolveRun();
+ });
+
+ expect(onReady).toHaveBeenCalledTimes(1);
+ expect(onReady).toHaveBeenCalledWith(views[0]);
+ });
+
+ it('invokes the latest onReady identity without rebuilding the View', async () => {
+ const first = vi.fn();
+ const second = vi.fn();
+ const {rerender} = render(<VegaChart spec={VEGA_SPEC} onReady={first} />);
+ rerender(<VegaChart spec={VEGA_SPEC} onReady={second} />);
+
+ // Same spec identity -> the Effect must not re-run.
+ expect(views).toHaveLength(1);
+ await act(async () => {
+ views[0].resolveRun();
+ });
+
+ expect(first).not.toHaveBeenCalled();
+ expect(second).toHaveBeenCalledTimes(1);
+ expect(second).toHaveBeenCalledWith(views[0]);
+ });
+
+ it('finalizes the View on unmount after a completed run', async () => {
+ const {unmount} = render(<VegaChart spec={VEGA_SPEC} />);
+ await act(async () => {
+ views[0].resolveRun();
+ });
+ expect(views[0].finalize).not.toHaveBeenCalled();
+
+ unmount();
+
+ expect(views[0].finalize).toHaveBeenCalledTimes(1);
+ });
+
+ it('finalizes again when a cancelled run settles, and never fires onReady', async () => {
+ const onReady = vi.fn();
+ const {unmount} = render(
+ <VegaChart spec={VEGA_SPEC} onReady={onReady} />,
+ );
+
+ unmount();
+ // Cleanup finalizes immediately, before the pending run settles.
+ expect(views[0].finalize).toHaveBeenCalledTimes(1);
+
+ await act(async () => {
+ views[0].resolveRun();
+ });
+
+ // The cancelled-run branch finalizes a second time -- current behavior.
+ expect(views[0].finalize).toHaveBeenCalledTimes(2);
+ expect(onReady).not.toHaveBeenCalled();
+ });
+ });
+
+ describe('container div', () => {
+ it('renders a single div and lands className, style, and rest props on it', () => {
+ const {container} = render(
+ <VegaChart
+ spec={VEGA_SPEC}
+ className="chart"
+ style={{width: 100}}
+ id="viz"
+ aria-label="Sales chart"
+ />,
+ );
+
+ expect(container.children).toHaveLength(1);
+ const div = container.firstElementChild as HTMLElement;
+ expect(div.tagName).toBe('DIV');
+ expect(div).toHaveClass('chart');
+ expect(div).toHaveStyle({width: '100px'});
+ expect(div).toHaveAttribute('id', 'viz');
+ expect(div).toHaveAttribute('aria-label', 'Sales chart');
+ });
+
+ it('forwards both function and object refs to the container div', () => {
+ const seen: Array<HTMLDivElement | null> = [];
+ const {container: c1} = render(
+ <VegaChart spec={VEGA_SPEC} ref={node => void seen.push(node)} />,
+ );
+ expect(seen).toEqual([c1.firstElementChild]);
+
+ const objectRef = React.createRef<HTMLDivElement>();
+ const {container: c2} = render(
+ <VegaChart spec={VEGA_SPEC} ref={objectRef} />,
+ );
+ expect(objectRef.current).toBe(c2.firstElementChild);
+ });
+ });
+});
diff --git a/packages/vega/src/schema.test.ts b/packages/vega/src/schema.test.ts
new file mode 100644
index 0000000000..c89f330362
--- /dev/null
+++ b/packages/vega/src/schema.test.ts
@@ -0,0 +1,85 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file schema.test.ts
+ * @input Uses vitest, parseSchema
+ * @output Functional tests for the $schema URL parser
+ * @position Colocated test for schema.ts (issue #4295 vega coverage)
+ */
+
+import {describe, it, expect} from 'vitest';
+import {parseSchema} from './schema';
+
+describe('parseSchema', () => {
+ it('parses a vega-lite schema URL into library and version', () => {
+ expect(
+ parseSchema('https://vega.github.io/schema/vega-lite/v5.json'),
+ ).toEqual({ok: true, library: 'vega-lite', version: 'v5'});
+ });
+
+ it('parses a plain vega schema URL into library and version', () => {
+ expect(parseSchema('https://vega.github.io/schema/vega/v6.json')).toEqual({
+ ok: true,
+ library: 'vega',
+ version: 'v6',
+ });
+ });
+
+ it('extracts multi-part versions from fully versioned URLs', () => {
+ expect(
+ parseSchema('https://vega.github.io/schema/vega-lite/v5.2.0.json'),
+ ).toEqual({ok: true, library: 'vega-lite', version: 'v5.2.0'});
+ });
+
+ it('tolerates proxy prefixes before the schema path', () => {
+ expect(
+ parseSchema(
+ 'https://internal-proxy.example.com/assets/vega.github.io/schema/vega/v5.json',
+ ),
+ ).toEqual({ok: true, library: 'vega', version: 'v5'});
+ });
+
+ it('rejects a missing $schema with a fix-it message', () => {
+ const expected = {
+ ok: false,
+ error:
+ 'Spec is missing a $schema field. Add "$schema": "https://vega.github.io/schema/vega/v5.json" or the vega-lite equivalent.',
+ };
+ expect(parseSchema(undefined)).toEqual(expected);
+ expect(parseSchema(null)).toEqual(expected);
+ });
+
+ it('rejects a non-string $schema and reports the received type', () => {
+ expect(parseSchema(5)).toEqual({
+ ok: false,
+ error: '$schema must be a string, got number.',
+ });
+ expect(parseSchema({url: 'x'})).toEqual({
+ ok: false,
+ error: '$schema must be a string, got object.',
+ });
+ });
+
+ it('rejects URLs that do not match the official schema format', () => {
+ expect(parseSchema('https://example.com/other.json')).toEqual({
+ ok: false,
+ error:
+ 'Unrecognized $schema URL: "https://example.com/other.json". Expected format: https://vega.github.io/schema/{vega|vega-lite}/{version}.json',
+ });
+ expect(parseSchema('')).toEqual({
+ ok: false,
+ error:
+ 'Unrecognized $schema URL: "". Expected format: https://vega.github.io/schema/{vega|vega-lite}/{version}.json',
+ });
+ });
+
+ it('rejects unknown libraries inside the schema URL namespace', () => {
+ expect(
+ parseSchema('https://vega.github.io/schema/vega-embed/v2.json'),
+ ).toEqual({
+ ok: false,
+ error:
+ 'Unknown schema library "vega-embed". Must be "vega" or "vega-lite".',
+ });
+ });
+});
diff --git a/packages/vega/src/vegaLiteConfig.test.ts b/packages/vega/src/vegaLiteConfig.test.ts
new file mode 100644
index 0000000000..a2f5cbd9b6
--- /dev/null
+++ b/packages/vega/src/vegaLiteConfig.test.ts
@@ -0,0 +1,94 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file vegaLiteConfig.test.ts
+ * @input Uses vitest, buildVegaLiteConfig and its exported layout constants
+ * @output Functional tests for the Astryx-themed Vega-Lite config builder
+ * @position Colocated test for vegaLiteConfig.ts (issue #4295 vega coverage)
+ */
+
+import {describe, it, expect} from 'vitest';
+import {
+ buildVegaLiteConfig,
+ DEFAULT_STROKE_WIDTH,
+ DEFAULT_POINT_SIZE,
+ DEFAULT_LEGEND_ORIENT,
+ LEGEND_OFFSET,
+ TITLE_OFFSET,
+} from './vegaLiteConfig';
+
+/** Resolver that makes every resolved token traceable to its name. */
+const token = (name: string) => `resolved(${name})`;
+
+describe('buildVegaLiteConfig', () => {
+ it('resolves chart chrome colors through the provided token resolver', () => {
+ const config = buildVegaLiteConfig(token);
+ expect(config.axis?.domainColor).toBe('resolved(--color-icon-primary)');
+ expect(config.axis?.labelColor).toBe('resolved(--color-text-secondary)');
+ expect(config.background).toBe('resolved(--color-background-card)');
+ expect(config.text?.color).toBe('resolved(--color-text-primary)');
+ expect(config.point?.fill).toBe('resolved(--color-background-card)');
+ expect(config.legend?.labelFont).toBe('resolved(--font-family-body)');
+ expect(config.title?.subtitleColor).toBe(
+ 'resolved(--color-text-secondary)',
+ );
+ });
+
+ it('orders the categorical palette across the ten categorical data tokens', () => {
+ const config = buildVegaLiteConfig(token);
+ expect(config.range?.category).toEqual([
+ 'resolved(--color-data-categorical-blue)',
+ 'resolved(--color-data-categorical-orange)',
+ 'resolved(--color-data-categorical-purple)',
+ 'resolved(--color-data-categorical-green)',
+ 'resolved(--color-data-categorical-pink)',
+ 'resolved(--color-data-categorical-cyan)',
+ 'resolved(--color-data-categorical-red)',
+ 'resolved(--color-data-categorical-teal)',
+ 'resolved(--color-data-categorical-brown)',
+ 'resolved(--color-data-categorical-indigo)',
+ ]);
+ });
+
+ it('builds the diverging range as a blue-to-red ramp around a gray midpoint', () => {
+ const config = buildVegaLiteConfig(token);
+ expect(config.range?.diverging).toEqual([
+ 'resolved(--color-data-blue-5)',
+ 'resolved(--color-data-blue-4)',
+ 'resolved(--color-data-blue-3)',
+ 'resolved(--color-data-blue-2)',
+ 'resolved(--color-data-blue-1)',
+ 'resolved(--color-data-gray-1)',
+ 'resolved(--color-data-red-1)',
+ 'resolved(--color-data-red-2)',
+ 'resolved(--color-data-red-3)',
+ 'resolved(--color-data-red-4)',
+ 'resolved(--color-data-red-5)',
+ ]);
+ // Sequential ranges are ascending blues.
+ expect(config.range?.heatmap).toEqual([
+ 'resolved(--color-data-blue-1)',
+ 'resolved(--color-data-blue-2)',
+ 'resolved(--color-data-blue-3)',
+ 'resolved(--color-data-blue-4)',
+ 'resolved(--color-data-blue-5)',
+ ]);
+ });
+
+ it('applies the structural mark and layout constants', () => {
+ const config = buildVegaLiteConfig(token);
+ expect(config.line?.strokeWidth).toBe(DEFAULT_STROKE_WIDTH);
+ expect(config.line?.strokeWidth).toBe(2);
+ expect(config.point?.size).toBe(DEFAULT_POINT_SIZE);
+ expect(config.point?.size).toBe(64);
+ expect(config.legend?.orient).toBe(DEFAULT_LEGEND_ORIENT);
+ expect(config.legend?.orient).toBe('right');
+ expect(config.legend?.offset).toBe(LEGEND_OFFSET);
+ expect(config.legend?.offset).toBe(16);
+ expect(config.title?.offset).toBe(TITLE_OFFSET);
+ expect(config.title?.offset).toBe(16);
+ expect(config.padding).toBe(16);
+ expect(config.scale?.bandPaddingInner).toBe(0.1);
+ expect(config.view?.stroke).toBeNull();
+ });
+});
diff --git a/vitest.config.ts b/vitest.config.ts
index deadb072d2..48f6df6605 100644
--- a/vitest.config.ts
+++ b/vitest.config.ts
@@ -88,8 +88,8 @@ export default defineConfig({
execArgv: ['--max-old-space-size=4096'],
// Test projects (migrated from vitest.workspace.ts). Partitioning rule
// (nothing can fall through):
- // - `ui` = packages/core + packages/lab + packages/charts + packages/richtext —
- // need jsdom, the StyleX babel
+ // - `ui` = packages/core + packages/lab + packages/charts + packages/richtext
+ // + packages/vega — need jsdom, the StyleX babel
// transform, and the jest-dom setup; inherit all of that from
// the root config via `extends: true`.
// - `node` = everything else (CLI, build tooling, scripts, internal
@@ -116,6 +116,7 @@ export default defineConfig({
'packages/lab/src/**/*.test.{ts,tsx,mjs}',
'packages/charts/src/**/*.test.{ts,tsx,mjs}',
'packages/richtext/src/**/*.test.{ts,tsx,mjs}',
+ 'packages/vega/src/**/*.test.{ts,tsx,mjs}',
],
},
},
@@ -159,6 +160,7 @@ export default defineConfig({
'packages/lab/**',
'packages/charts/**',
'packages/richtext/**',
+ 'packages/vega/**',
],
},
},