Skip to content

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

TypeScript

fix(lab): accessible names and data-table fallbacks for charts (#4382)

Baraa Hamodibd18aeed7ea1
diff --git a/packages/charts/src/Chart.test.tsx b/packages/charts/src/Chart.test.tsx
new file mode 100644
index 0000000000..9644955756
--- /dev/null
+++ b/packages/charts/src/Chart.test.tsx
@@ -0,0 +1,129 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Chart.test.tsx
+ * @input Uses vitest, @testing-library/react, Chart root + bar mark
+ * @output Unit tests for Chart accessibility (WCAG 1.1.1)
+ * @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 {Chart} from './Chart';
+import {bar} from './marks';
+
+const data = [
+ {month: 'Jan', revenue: 100, profit: 20},
+ {month: 'Feb', revenue: 200, profit: 40},
+ {month: 'Mar', revenue: 150, profit: 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('Chart accessible name', () => {
+ it('exposes the svg as a named image with a default label', () => {
+ render(
+ <Chart
+ data={data}
+ xKey="month"
+ series={[bar('revenue'), bar('profit')]}
+ />,
+ );
+ reportWidth(600);
+
+ expect(
+ screen.getByRole('img', {name: 'Chart of revenue, profit by month'}),
+ ).toBeInTheDocument();
+ });
+
+ it('prefers the title prop as the accessible name', () => {
+ render(
+ <Chart
+ data={data}
+ xKey="month"
+ series={[bar('revenue')]}
+ title="Quarterly revenue"
+ />,
+ );
+ reportWidth(600);
+
+ expect(
+ screen.getByRole('img', {name: 'Quarterly revenue'}),
+ ).toBeInTheDocument();
+ });
+});
+
+describe('Chart data table fallback', () => {
+ it('renders a visually hidden table mirroring the data', () => {
+ render(
+ <Chart
+ data={data}
+ xKey="month"
+ series={[bar('revenue'), bar('profit')]}
+ />,
+ );
+ reportWidth(600);
+
+ const table = screen.getByRole('table');
+ expect(table).toBeInTheDocument();
+
+ expect(
+ screen.getByRole('columnheader', {name: 'month'}),
+ ).toBeInTheDocument();
+ expect(
+ screen.getByRole('columnheader', {name: 'revenue'}),
+ ).toBeInTheDocument();
+ expect(
+ screen.getByRole('columnheader', {name: 'profit'}),
+ ).toBeInTheDocument();
+
+ expect(screen.getByRole('rowheader', {name: 'Feb'})).toBeInTheDocument();
+ expect(screen.getByRole('cell', {name: '200'})).toBeInTheDocument();
+ expect(screen.getByRole('cell', {name: '40'})).toBeInTheDocument();
+
+ // Visually hidden, but still in the a11y tree.
+ const wrapper = table.parentElement as HTMLElement;
+ expect(wrapper.getAttribute('class')).toBeTruthy();
+ expect(wrapper).not.toHaveAttribute('hidden');
+ });
+
+ it('skips the table when the dataset exceeds the size cutoff', () => {
+ const big = Array.from({length: 101}, (_, i) => ({
+ month: `m${i}`,
+ revenue: i,
+ }));
+ render(<Chart data={big} xKey="month" series={[bar('revenue')]} />);
+ reportWidth(600);
+
+ expect(screen.queryByRole('table')).not.toBeInTheDocument();
+ });
+});
diff --git a/packages/charts/src/Chart.tsx b/packages/charts/src/Chart.tsx
index 6ad3d824dc..f95617c6fc 100644
--- a/packages/charts/src/Chart.tsx
+++ b/packages/charts/src/Chart.tsx
@@ -9,6 +9,10 @@
* 1. Runs the layout engine (scales + stacking + grouping)
* 2. Calls each series' resolve() and render() methods
* 3. Provides a single event layer for interaction children
+ *
+ * Accessibility: the svg is exposed as a named image (role="img"; `title` or a
+ * derived default as aria-label), and small datasets are mirrored in a
+ * visually hidden data table for screen reader users.
*/
'use client';
@@ -28,6 +32,7 @@ import {computeLayout} from './layout';
import {ChartProvider} from './ChartContext';
import {Text} from '@astryxdesign/core';
import {VStack, HStack} from '@astryxdesign/core';
+import {VisuallyHidden} from '@astryxdesign/core';
import * as stylex from '@stylexjs/stylex';
import {ChartLegend, type ChartLegendProps} from './ChartLegend';
import {deriveLegendItems} from './legend';
@@ -62,6 +67,18 @@ export interface ChartProps {
const DEFAULT_MARGIN: ChartMargin = {top: 24, right: 24, bottom: 32, left: 48};
+/**
+ * Maximum number of data points (rows × data keys) for which the visually
+ * hidden data-table fallback is rendered. Beyond this a table is more noise
+ * than signal for screen reader users, so larger charts are name-only.
+ */
+const MAX_TABLE_POINTS = 100;
+
+/** Stringify a cell value for the hidden data table. */
+function tableCell(value: unknown): string {
+ return value == null ? '' : String(value);
+}
+
const styles = stylex.create({
container: {
width: '100%',
@@ -250,6 +267,23 @@ export function Chart({
[innerWidth, innerHeight, margin, data, xKey, layout, onPointer],
);
+ // ─── Accessibility ─────────────────────────────────────────────────────
+ // The svg is exposed as a named image. `title` (when given) is the name;
+ // otherwise an English default is derived from the primary series + x key.
+ const primarySeries = series.filter(s => !isUtilityMarkType(s.type));
+ const accessibleLabel =
+ title ??
+ (primarySeries.length > 0
+ ? `Chart of ${primarySeries
+ .map(s => s.label ?? s.key)
+ .join(', ')} by ${xKey}`
+ : 'Chart');
+ const tableKeys = Array.from(new Set(primarySeries.flatMap(s => s.dataKeys)));
+ const showDataTable =
+ data.length > 0 &&
+ tableKeys.length > 0 &&
+ data.length * tableKeys.length <= MAX_TABLE_POINTS;
+
// ─── Legend ────────────────────────────────────────────────────────────
const legendConfig = legend === true ? {} : legend || null;
@@ -309,6 +343,7 @@ export function Chart({
</VStack>
)}
</ChartProvider>
+ {renderDataTable()}
</div>
);
@@ -316,9 +351,10 @@ export function Chart({
return (
<svg
ref={svgRef}
+ role="img"
width="100%"
height={safeHeight}
- aria-label={title ?? undefined}
+ aria-label={accessibleLabel}
aria-describedby={subtitle ? descId : undefined}>
{title && <title>{title}</title>}
{subtitle && <desc id={descId}>{subtitle}</desc>}
@@ -373,4 +409,37 @@ export function Chart({
</svg>
);
}
+
+ function renderDataTable() {
+ if (!showDataTable) {
+ return null;
+ }
+ return (
+ <VisuallyHidden as="div">
+ <table>
+ <caption>{`${accessibleLabel} data`}</caption>
+ <thead>
+ <tr>
+ <th scope="col">{xKey}</th>
+ {tableKeys.map(key => (
+ <th key={key} scope="col">
+ {key}
+ </th>
+ ))}
+ </tr>
+ </thead>
+ <tbody>
+ {data.map((d, i) => (
+ <tr key={i}>
+ <th scope="row">{tableCell(d[xKey])}</th>
+ {tableKeys.map(key => (
+ <td key={key}>{tableCell(d[key])}</td>
+ ))}
+ </tr>
+ ))}
+ </tbody>
+ </table>
+ </VisuallyHidden>
+ );
+ }
}
diff --git a/packages/lab/src/Chart/Chart.test.tsx b/packages/lab/src/Chart/Chart.test.tsx
new file mode 100644
index 0000000000..7a6df5d88d
--- /dev/null
+++ b/packages/lab/src/Chart/Chart.test.tsx
@@ -0,0 +1,126 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Chart.test.tsx
+ * @input Uses vitest, @testing-library/react, Chart component
+ * @output Unit tests for Chart accessibility (WCAG 1.1.1)
+ * @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 {Chart} from './Chart';
+
+const data = [
+ {month: 'Jan', revenue: 100, profit: 20},
+ {month: 'Feb', revenue: 200, profit: 40},
+ {month: 'Mar', revenue: 150, profit: 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('Chart accessible name', () => {
+ it('exposes the svg as a named image with a default label', () => {
+ render(
+ <Chart data={data} xKey="month" yKeys={['revenue', 'profit']}>
+ <g />
+ </Chart>,
+ );
+ reportWidth(600);
+
+ expect(
+ screen.getByRole('img', {name: 'Chart of revenue, profit by month'}),
+ ).toBeInTheDocument();
+ });
+
+ it('uses a custom label when provided', () => {
+ render(
+ <Chart data={data} xKey="month" yKeys={['revenue']} label="Q1 revenue">
+ <g />
+ </Chart>,
+ );
+ reportWidth(600);
+
+ expect(screen.getByRole('img', {name: 'Q1 revenue'})).toBeInTheDocument();
+ });
+});
+
+describe('Chart data table fallback', () => {
+ it('renders a visually hidden table mirroring the data', () => {
+ render(
+ <Chart data={data} xKey="month" yKeys={['revenue', 'profit']}>
+ <g />
+ </Chart>,
+ );
+ reportWidth(600);
+
+ const table = screen.getByRole('table');
+ expect(table).toBeInTheDocument();
+
+ // Column headers: x key + each y key
+ expect(
+ screen.getByRole('columnheader', {name: 'month'}),
+ ).toBeInTheDocument();
+ expect(
+ screen.getByRole('columnheader', {name: 'revenue'}),
+ ).toBeInTheDocument();
+ expect(
+ screen.getByRole('columnheader', {name: 'profit'}),
+ ).toBeInTheDocument();
+
+ // Row headers and values
+ expect(screen.getByRole('rowheader', {name: 'Feb'})).toBeInTheDocument();
+ expect(screen.getByRole('cell', {name: '200'})).toBeInTheDocument();
+ expect(screen.getByRole('cell', {name: '40'})).toBeInTheDocument();
+
+ // Visually hidden, but still in the a11y tree (StyleX clip class attached,
+ // not display:none/hidden — jsdom does not apply the stylesheet itself).
+ const wrapper = table.parentElement as HTMLElement;
+ expect(wrapper.getAttribute('class')).toBeTruthy();
+ expect(wrapper).not.toHaveAttribute('hidden');
+ });
+
+ it('skips the table when the dataset exceeds the size cutoff', () => {
+ const big = Array.from({length: 101}, (_, i) => ({
+ month: `m${i}`,
+ revenue: i,
+ }));
+ render(
+ <Chart data={big} xKey="month" yKeys={['revenue']}>
+ <g />
+ </Chart>,
+ );
+ reportWidth(600);
+
+ expect(screen.queryByRole('table')).not.toBeInTheDocument();
+ });
+});
diff --git a/packages/lab/src/Chart/Chart.tsx b/packages/lab/src/Chart/Chart.tsx
index b8a69d34b2..7bf559c2d8 100644
--- a/packages/lab/src/Chart/Chart.tsx
+++ b/packages/lab/src/Chart/Chart.tsx
@@ -7,6 +7,10 @@
*
* Handles the d3 margin convention: outer SVG at full size, inner <g> translated
* by margins. Children receive scales and dimensions via context.
+ *
+ * Accessibility: the svg is exposed as a named image (role="img" + aria-label,
+ * overridable via `label`), and small datasets are mirrored in a visually
+ * hidden data table so screen reader users can read the underlying values.
*/
import {
@@ -20,6 +24,7 @@ import {
} from 'react';
import {scaleLinear, scaleBand} from 'd3-scale';
import type {ScaleLinear} from 'd3-scale';
+import {VisuallyHidden} from '@astryxdesign/core/VisuallyHidden';
import {isBandScale} from './utils';
import {ChartProvider} from './ChartContext';
import type {ChartMargin, ChartScale} from './types';
@@ -75,12 +80,31 @@ export interface ChartProps {
* interference on mobile.
*/
interactive?: boolean;
+ /**
+ * Accessible name for the chart, announced by screen readers (the svg is
+ * exposed as `role="img"`). Defaults to an English description derived from
+ * the keys (e.g. "Chart of revenue by month") — pass a localized string to
+ * override.
+ */
+ label?: string;
/** Chart contents — axes, marks, tooltips */
children: ReactNode;
}
const DEFAULT_MARGIN: ChartMargin = {top: 16, right: 16, bottom: 32, left: 48};
+/**
+ * Maximum number of data points (rows × series) for which the visually hidden
+ * data-table fallback is rendered. Beyond this a table is more noise than
+ * signal for screen reader users, so larger charts are name-only.
+ */
+const MAX_TABLE_POINTS = 100;
+
+/** Stringify a cell value for the hidden data table. */
+function tableCell(value: unknown): string {
+ return value == null ? '' : String(value);
+}
+
/**
* Root chart container. Computes scales from data and provides them to children.
*
@@ -103,6 +127,7 @@ export function Chart({
yDomain: yDomainProp,
xDomain: xDomainProp,
interactive = false,
+ label,
children,
}: ChartProps) {
const containerRef = useRef<HTMLDivElement>(null);
@@ -289,11 +314,18 @@ export function Chart({
userSelect: interactive ? 'none' : undefined,
};
+ const accessibleLabel = label ?? `Chart of ${yKeys.join(', ')} by ${xKey}`;
+ const showDataTable =
+ data.length > 0 &&
+ data.length * Math.max(yKeys.length, 1) <= MAX_TABLE_POINTS;
+
return (
<div ref={containerRef} style={containerStyle}>
{containerWidth > 0 && (
<svg
ref={svgRef}
+ role="img"
+ aria-label={accessibleLabel}
width={containerWidth}
height={height}
style={interactive ? {touchAction: 'none'} : undefined}>
@@ -307,6 +339,33 @@ export function Chart({
</g>
</svg>
)}
+ {showDataTable && (
+ <VisuallyHidden as="div">
+ <table>
+ <caption>{`${accessibleLabel} data`}</caption>
+ <thead>
+ <tr>
+ <th scope="col">{xKey}</th>
+ {yKeys.map(key => (
+ <th key={key} scope="col">
+ {key}
+ </th>
+ ))}
+ </tr>
+ </thead>
+ <tbody>
+ {data.map((d, i) => (
+ <tr key={i}>
+ <th scope="row">{tableCell(d[xKey])}</th>
+ {yKeys.map(key => (
+ <td key={key}>{tableCell(d[key])}</td>
+ ))}
+ </tr>
+ ))}
+ </tbody>
+ </table>
+ </VisuallyHidden>
+ )}
</div>
);
}
diff --git a/packages/lab/src/Radial/RadialChart.test.tsx b/packages/lab/src/Radial/RadialChart.test.tsx
new file mode 100644
index 0000000000..3ea2f5b059
--- /dev/null
+++ b/packages/lab/src/Radial/RadialChart.test.tsx
@@ -0,0 +1,157 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @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
+ */
+
+import {describe, it, expect, beforeEach, afterEach, vi} from 'vitest';
+import {render, screen, act} from '@testing-library/react';
+import {RadialChart} from './RadialChart';
+
+const spiderData = [
+ {name: 'modelA', speed: 8, handling: 6, comfort: 7},
+ {name: 'modelB', speed: 5, handling: 9, comfort: 6},
+];
+
+const pieData = [
+ {region: 'NA', revenue: 60},
+ {region: 'EU', revenue: 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('RadialChart accessible name', () => {
+ it('names the svg from the axes in spider mode', () => {
+ render(
+ <RadialChart data={spiderData} axes={['speed', 'handling', 'comfort']}>
+ <g />
+ </RadialChart>,
+ );
+ reportWidth(500);
+
+ expect(
+ screen.getByRole('img', {
+ name: 'Radar chart of speed, handling, comfort',
+ }),
+ ).toBeInTheDocument();
+ });
+
+ it('names the svg from the value key in pie mode', () => {
+ render(
+ <RadialChart data={pieData} valueKey="revenue" labelKey="region">
+ <g />
+ </RadialChart>,
+ );
+ reportWidth(500);
+
+ expect(
+ screen.getByRole('img', {name: 'Pie chart of revenue'}),
+ ).toBeInTheDocument();
+ });
+
+ it('uses a custom label when provided', () => {
+ render(
+ <RadialChart
+ data={pieData}
+ valueKey="revenue"
+ labelKey="region"
+ label="Revenue by region">
+ <g />
+ </RadialChart>,
+ );
+ reportWidth(500);
+
+ expect(
+ screen.getByRole('img', {name: 'Revenue by region'}),
+ ).toBeInTheDocument();
+ });
+});
+
+describe('RadialChart data table fallback', () => {
+ it('renders slice labels, values, and percentages in pie mode', () => {
+ render(
+ <RadialChart data={pieData} valueKey="revenue" labelKey="region">
+ <g />
+ </RadialChart>,
+ );
+ reportWidth(500);
+
+ const table = screen.getByRole('table');
+ expect(table).toBeInTheDocument();
+
+ expect(screen.getByRole('rowheader', {name: 'NA'})).toBeInTheDocument();
+ expect(screen.getByRole('cell', {name: '60'})).toBeInTheDocument();
+ expect(screen.getByRole('cell', {name: '60.0%'})).toBeInTheDocument();
+ expect(screen.getByRole('rowheader', {name: 'EU'})).toBeInTheDocument();
+ expect(screen.getByRole('cell', {name: '40.0%'})).toBeInTheDocument();
+
+ // Visually hidden, but still in the a11y tree.
+ const wrapper = table.parentElement as HTMLElement;
+ expect(wrapper.getAttribute('class')).toBeTruthy();
+ expect(wrapper).not.toHaveAttribute('hidden');
+ });
+
+ it('renders one row per series across the axes in spider mode', () => {
+ render(
+ <RadialChart data={spiderData} axes={['speed', 'handling', 'comfort']}>
+ <g />
+ </RadialChart>,
+ );
+ reportWidth(500);
+
+ expect(
+ screen.getByRole('columnheader', {name: 'speed'}),
+ ).toBeInTheDocument();
+ expect(screen.getByRole('rowheader', {name: 'modelA'})).toBeInTheDocument();
+ expect(screen.getByRole('rowheader', {name: 'modelB'})).toBeInTheDocument();
+ expect(screen.getByRole('cell', {name: '8'})).toBeInTheDocument();
+ expect(screen.getByRole('cell', {name: '9'})).toBeInTheDocument();
+ });
+
+ it('skips the table when the dataset exceeds the size cutoff', () => {
+ const big = Array.from({length: 101}, (_, i) => ({
+ region: `r${i}`,
+ revenue: i + 1,
+ }));
+ render(
+ <RadialChart data={big} valueKey="revenue" labelKey="region">
+ <g />
+ </RadialChart>,
+ );
+ reportWidth(500);
+
+ expect(screen.queryByRole('table')).not.toBeInTheDocument();
+ });
+});
diff --git a/packages/lab/src/Radial/RadialChart.tsx b/packages/lab/src/Radial/RadialChart.tsx
index b1aa54a6c3..f2a027c975 100644
--- a/packages/lab/src/Radial/RadialChart.tsx
+++ b/packages/lab/src/Radial/RadialChart.tsx
@@ -7,6 +7,10 @@
*
* Owns the radial coordinate space: center, radius, angle/radius scales.
* Same Tier 1 guarantee as Chart — all children map through the same context.
+ *
+ * Accessibility: the svg is exposed as a named image (role="img" + aria-label,
+ * overridable via `label`), and small datasets are mirrored in a visually
+ * hidden data table (slices in pie mode, axis values in spider mode).
*/
import {
@@ -16,6 +20,7 @@ import {
useState,
useLayoutEffect,
} from 'react';
+import {VisuallyHidden} from '@astryxdesign/core/VisuallyHidden';
import {RadialProvider} from './RadialContext';
import type {RadialMode} from './types';
@@ -52,9 +57,32 @@ export interface RadialChartProps {
* Enable touch interaction mode — blocks scroll on mobile.
*/
interactive?: boolean;
+ /**
+ * Accessible name for the chart, announced by screen readers (the svg is
+ * exposed as `role="img"`). Defaults to an English description derived from
+ * the mode and keys (e.g. "Radar chart of speed, handling" or
+ * "Pie chart of revenue") — pass a localized string to override.
+ */
+ label?: string;
children: ReactNode;
}
+/**
+ * Maximum number of data points (rows × axes in spider mode, slices in pie
+ * mode) for which the visually hidden data-table fallback is rendered. Beyond
+ * this a table is more noise than signal, so larger charts are name-only.
+ */
+const MAX_TABLE_POINTS = 100;
+
+/**
+ * Row header for a spider-mode table row: the first string field in the row
+ * (the same heuristic RadialArea uses to match its `dataKey`), else the index.
+ */
+function spiderRowHeader(row: Record<string, unknown>, index: number): string {
+ const name = Object.values(row).find(v => typeof v === 'string');
+ return typeof name === 'string' ? name : `Series ${index + 1}`;
+}
+
/**
* Root radial chart container. Computes angular/radial scales and provides
* them to children via context.
@@ -82,6 +110,7 @@ export function RadialChart({
labelKey,
innerRadius: innerRadiusFraction = 0,
padAngle = 0.02,
+ label,
children,
}: RadialChartProps) {
const containerRef = useRef<HTMLDivElement>(null);
@@ -202,13 +231,85 @@ export function RadialChart({
[cx, cy, outerRadius, innerRadiusPx, data, mode, spiderCtx, pieCtx],
);
+ const accessibleLabel =
+ label ??
+ (mode === 'spider'
+ ? `Radar chart of ${(axes ?? []).join(', ')}`
+ : `Pie chart of ${valueKey ?? 'values'}`);
+
+ const slices = pieCtx.slices ?? [];
+ const showPieTable =
+ mode === 'pie' && slices.length > 0 && slices.length <= MAX_TABLE_POINTS;
+ const showSpiderTable =
+ mode === 'spider' &&
+ axes != null &&
+ axes.length > 0 &&
+ data.length > 0 &&
+ data.length * axes.length <= MAX_TABLE_POINTS;
+
return (
<div ref={containerRef} style={{width: '100%'}}>
{containerWidth > 0 && (
- <svg width={containerWidth} height={height}>
+ <svg
+ role="img"
+ aria-label={accessibleLabel}
+ width={containerWidth}
+ height={height}>
<RadialProvider value={ctx}>{children}</RadialProvider>
</svg>
)}
+ {showPieTable && (
+ <VisuallyHidden as="div">
+ <table>
+ <caption>{`${accessibleLabel} data`}</caption>
+ <thead>
+ <tr>
+ <th scope="col">{labelKey ?? 'Label'}</th>
+ <th scope="col">{valueKey}</th>
+ <th scope="col">Percentage</th>
+ </tr>
+ </thead>
+ <tbody>
+ {slices.map((slice, i) => (
+ <tr key={i}>
+ <th scope="row">{slice.key}</th>
+ <td>{String(slice.value)}</td>
+ <td>{`${(slice.percentage * 100).toFixed(1)}%`}</td>
+ </tr>
+ ))}
+ </tbody>
+ </table>
+ </VisuallyHidden>
+ )}
+ {showSpiderTable && (
+ <VisuallyHidden as="div">
+ <table>
+ <caption>{`${accessibleLabel} data`}</caption>
+ <thead>
+ <tr>
+ <th scope="col">Series</th>
+ {axes.map(key => (
+ <th key={key} scope="col">
+ {key}
+ </th>
+ ))}
+ </tr>
+ </thead>
+ <tbody>
+ {data.map((row, i) => (
+ <tr key={i}>
+ <th scope="row">{spiderRowHeader(row, i)}</th>
+ {axes.map(key => (
+ <td key={key}>
+ {row[key] == null ? '' : String(row[key])}
+ </td>
+ ))}
+ </tr>
+ ))}
+ </tbody>
+ </table>
+ </VisuallyHidden>
+ )}
</div>
);
}
diff --git a/packages/lab/src/Sankey/SankeyChart.test.tsx b/packages/lab/src/Sankey/SankeyChart.test.tsx
index c4de6967c7..58c713d84a 100644
--- a/packages/lab/src/Sankey/SankeyChart.test.tsx
+++ b/packages/lab/src/Sankey/SankeyChart.test.tsx
@@ -75,3 +75,98 @@ describe('SankeyChart scroll container', () => {
).not.toBeInTheDocument();
});
});
+
+describe('SankeyChart accessible name', () => {
+ it('names the svg when the chart does not scroll', () => {
+ render(
+ <SankeyChart nodes={nodes} links={links} minColumnWidth={50}>
+ <SankeyNode />
+ </SankeyChart>,
+ );
+ reportWidth(1000);
+
+ expect(screen.getByRole('img', {name: 'Sankey chart'})).toBeInTheDocument();
+ });
+
+ it('names the svg when the chart scrolls', () => {
+ render(
+ <SankeyChart nodes={nodes} links={links} minColumnWidth={400}>
+ <SankeyNode />
+ </SankeyChart>,
+ );
+ reportWidth(300);
+
+ expect(screen.getByRole('img', {name: 'Sankey chart'})).toBeInTheDocument();
+ });
+
+ it('applies a custom label to both the svg and the scroll region', () => {
+ render(
+ <SankeyChart
+ nodes={nodes}
+ links={links}
+ minColumnWidth={400}
+ label="Traffic flow">
+ <SankeyNode />
+ </SankeyChart>,
+ );
+ reportWidth(300);
+
+ expect(screen.getByRole('img', {name: 'Traffic flow'})).toBeInTheDocument();
+ expect(
+ screen.getByRole('group', {name: 'Traffic flow'}),
+ ).toBeInTheDocument();
+ });
+});
+
+describe('SankeyChart data table fallback', () => {
+ it('renders a visually hidden table of flows', () => {
+ render(
+ <SankeyChart nodes={nodes} links={links} minColumnWidth={50}>
+ <SankeyNode />
+ </SankeyChart>,
+ );
+ reportWidth(1000);
+
+ const table = screen.getByRole('table');
+ expect(table).toBeInTheDocument();
+
+ expect(
+ screen.getByRole('columnheader', {name: 'From'}),
+ ).toBeInTheDocument();
+ expect(screen.getByRole('columnheader', {name: 'To'})).toBeInTheDocument();
+ expect(
+ screen.getByRole('columnheader', {name: 'Value'}),
+ ).toBeInTheDocument();
+
+ // Link a → b (value 5), labels resolved from node definitions.
+ expect(screen.getByRole('rowheader', {name: 'A'})).toBeInTheDocument();
+ expect(screen.getByRole('rowheader', {name: 'B'})).toBeInTheDocument();
+ expect(screen.getAllByRole('cell', {name: '5'})).toHaveLength(2);
+
+ // Visually hidden, but still in the a11y tree.
+ const wrapper = table.parentElement as HTMLElement;
+ expect(wrapper.getAttribute('class')).toBeTruthy();
+ expect(wrapper).not.toHaveAttribute('hidden');
+ });
+
+ it('skips the table when there are too many links', () => {
+ const manyNodes = Array.from({length: 102}, (_, i) => ({
+ id: `n${i}`,
+ label: `N${i}`,
+ value: 1,
+ }));
+ const manyLinks = Array.from({length: 101}, (_, i) => ({
+ source: `n${i}`,
+ target: `n${i + 1}`,
+ value: 1,
+ }));
+ render(
+ <SankeyChart nodes={manyNodes} links={manyLinks} minColumnWidth={5}>
+ <SankeyNode />
+ </SankeyChart>,
+ );
+ reportWidth(1000);
+
+ expect(screen.queryByRole('table')).not.toBeInTheDocument();
+ });
+});
diff --git a/packages/lab/src/Sankey/SankeyChart.tsx b/packages/lab/src/Sankey/SankeyChart.tsx
index c619b52c2c..678090eaed 100644
--- a/packages/lab/src/Sankey/SankeyChart.tsx
+++ b/packages/lab/src/Sankey/SankeyChart.tsx
@@ -7,6 +7,10 @@
*
* When columns × minColumnWidth exceeds the container, the chart
* scrolls horizontally rather than squishing columns together.
+ *
+ * Accessibility: the svg is exposed as a named image (role="img" + aria-label,
+ * overridable via `label`) in both the scrolling and non-scrolling paths, and
+ * small graphs are mirrored in a visually hidden From/To/Value table.
*/
import {
@@ -16,6 +20,7 @@ import {
useState,
useLayoutEffect,
} from 'react';
+import {VisuallyHidden} from '@astryxdesign/core/VisuallyHidden';
import {SankeyProvider} from './SankeyContext';
import {computeLayout} from './layout';
import type {SankeyNodeDatum, SankeyLinkDatum, SankeyColumn} from './types';
@@ -51,10 +56,25 @@ export interface SankeyChartProps {
* When total min width exceeds the container, horizontal scrolling activates.
*/
minColumnWidth?: number;
+ /**
+ * Accessible name for the chart, announced by screen readers. Applied to the
+ * svg (`role="img"`) and, when the chart scrolls, to the focusable scroll
+ * region. Pass a localized string to override the English default.
+ *
+ * @default 'Sankey chart'
+ */
+ label?: string;
/** Chart contents */
children: ReactNode;
}
+/**
+ * Maximum number of links for which the visually hidden data-table fallback is
+ * rendered. Beyond this a table is more noise than signal, so larger charts
+ * are name-only.
+ */
+const MAX_TABLE_LINKS = 100;
+
/** Resolve column count from raw column input or auto-detect from graph */
function resolveColumnCount(
columns: SankeyColumn[] | undefined,
@@ -131,6 +151,7 @@ export function SankeyChart({
nodeGap = 14,
nodeColor,
minColumnWidth = 160,
+ label = 'Sankey chart',
children,
}: SankeyChartProps) {
const containerRef = useRef<HTMLDivElement>(null);
@@ -197,17 +218,25 @@ export function SankeyChart({
};
}, [layout, chartWidth, height, nodeWidth, nodeColor]);
+ const nodeLabelById = useMemo(
+ () => new Map(nodes.map(n => [n.id, n.label || n.id])),
+ [nodes],
+ );
+ const showDataTable = links.length > 0 && links.length <= MAX_TABLE_LINKS;
+
return (
<div ref={containerRef} style={{width: '100%'}}>
{ctx && (
<div
role={needsScroll ? 'group' : undefined}
- aria-label={needsScroll ? 'Sankey chart' : undefined}
+ aria-label={needsScroll ? label : undefined}
tabIndex={needsScroll ? 0 : undefined}
style={
needsScroll ? {overflowX: 'auto', overflowY: 'hidden'} : undefined
}>
<svg
+ role="img"
+ aria-label={label}
width={chartWidth}
height={height}
style={{overflow: 'visible', display: 'block'}}>
@@ -215,6 +244,31 @@ export function SankeyChart({
</svg>
</div>
)}
+ {showDataTable && (
+ <VisuallyHidden as="div">
+ <table>
+ <caption>{`${label} data`}</caption>
+ <thead>
+ <tr>
+ <th scope="col">From</th>
+ <th scope="col">To</th>
+ <th scope="col">Value</th>
+ </tr>
+ </thead>
+ <tbody>
+ {links.map((link, i) => (
+ <tr key={i}>
+ <th scope="row">
+ {nodeLabelById.get(link.source) ?? link.source}
+ </th>
+ <td>{nodeLabelById.get(link.target) ?? link.target}</td>
+ <td>{String(link.value)}</td>
+ </tr>
+ ))}
+ </tbody>
+ </table>
+ </VisuallyHidden>
+ )}
</div>
);
}
diff --git a/vitest.config.ts b/vitest.config.ts
index 074b405f89..d31d53b92d 100644
--- a/vitest.config.ts
+++ b/vitest.config.ts
@@ -63,6 +63,12 @@ export default defineConfig({
find: /^@astryxdesign\/core\/(.*)$/,
replacement: path.join(coreSrc, '$1'),
},
+ // Map the bare specifier to source too (charts package tests import
+ // runtime components like Text/VisuallyHidden from the package root).
+ {
+ find: /^@astryxdesign\/core$/,
+ replacement: path.join(coreSrc, 'index.ts'),
+ },
],
},
test: {
@@ -82,7 +88,7 @@ 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 — need jsdom, the StyleX babel
+ // - `ui` = packages/core + packages/lab + packages/charts — 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
@@ -100,6 +106,7 @@ export default defineConfig({
include: [
'packages/core/src/**/*.test.{ts,tsx,mjs}',
'packages/lab/src/**/*.test.{ts,tsx,mjs}',
+ 'packages/charts/src/**/*.test.{ts,tsx,mjs}',
],
},
},
@@ -138,6 +145,7 @@ export default defineConfig({
...configDefaults.exclude,
'packages/core/**',
'packages/lab/**',
+ 'packages/charts/**',
],
},
},