Skip to content

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

TypeScript

feat(core): Table row index as a table-level ARIA concern (#3939) (#4124)

Humberto Virtudesb7d7f4b61f9d
diff --git a/.changeset/table-aria-rowindex.md b/.changeset/table-aria-rowindex.md
new file mode 100644
index 0000000000..3879d3eb17
--- /dev/null
+++ b/.changeset/table-aria-rowindex.md
@@ -0,0 +1,6 @@
+---
+'@astryxdesign/core': patch
+---
+
+[feat] Table: `rowIndexStart` and `rowCount` props expose row numbering as a table-level ARIA concern, so `aria-rowindex`/`aria-rowcount` reflect a row's position in the full dataset: correct across pagination and even when no visible index column is rendered. Opt-in; tables that set neither prop are unchanged. Closes #3939.
+@humbertovirtudes
diff --git a/apps/storybook/stories/TableRowIndex.stories.tsx b/apps/storybook/stories/TableRowIndex.stories.tsx
index a265ee2e87..33cdeba17b 100644
--- a/apps/storybook/stories/TableRowIndex.stories.tsx
+++ b/apps/storybook/stories/TableRowIndex.stories.tsx
@@ -5,12 +5,15 @@ import type {Meta, StoryObj} from '@storybook/react';
import {
Table,
useTableRowIndex,
+ useTablePagination,
useTableSortable,
useTableSortableState,
proportional,
pixel,
} from '@astryxdesign/core/Table';
import type {TableColumn, TableSortState} from '@astryxdesign/core/Table';
+import {Text} from '@astryxdesign/core/Text';
+import {VStack} from '@astryxdesign/core/Layout';
// =============================================================================
// Sample Data
@@ -128,3 +131,92 @@ export const RenumbersWithSort: Story = {
);
},
};
+
+// =============================================================================
+// Table-level ARIA row index (#3939)
+// =============================================================================
+
+interface Contact extends Record<string, unknown> {
+ id: string;
+ name: string;
+ city: string;
+}
+
+const contacts: Contact[] = Array.from({length: 42}, (_, i) => ({
+ id: `c${i + 1}`,
+ name: `Contact ${i + 1}`,
+ city: ['Lisbon', 'Tokyo', 'Oslo', 'Cairo'][i % 4],
+}));
+
+const contactColumns: TableColumn<Contact>[] = [
+ {key: 'name', header: 'Name', width: proportional(2)},
+ {key: 'city', header: 'City', width: proportional(1)},
+];
+
+/**
+ * The row ordinal is an accessibility concern, not just a visible column. Pass
+ * `rowCount` (and, for a windowed view, `rowIndexStart`) to emit `aria-rowindex`
+ * on every `<tr>` and `aria-rowcount` on the `<table>`, correct even when no
+ * visible `#` column is rendered. Inspect the DOM: rows carry `aria-rowindex`
+ * with no index column in sight.
+ */
+export const AriaRowIndexNoVisibleColumn: Story = {
+ render: () => (
+ <VStack gap={2}>
+ <Text type="body">
+ No visible index column, but each row still exposes aria-rowindex, and
+ the table exposes aria-rowcount. Inspect the DOM to verify.
+ </Text>
+ <Table
+ data={contacts.slice(0, 5)}
+ columns={contactColumns}
+ idKey="id"
+ rowCount={contacts.length}
+ />
+ </VStack>
+ ),
+};
+
+/**
+ * With pagination, `aria-rowindex` must reflect the row's position in the
+ * **full** dataset, not the current page. Pass `rowIndexStart` as the offset of
+ * the first visible row (`(page - 1) * pageSize + 1`) and `rowCount` as the
+ * total. On page 3 below, the first row announces as row 21 of 42. The visible
+ * `useTableRowIndex` numbering is seeded from the same offset so both agree.
+ */
+export const AriaRowIndexWithPagination: Story = {
+ render: () => {
+ const pageSize = 10;
+ const [page, setPage] = useState(3);
+ const start = (page - 1) * pageSize;
+ const pageData = contacts.slice(start, start + pageSize);
+
+ const pagination = useTablePagination<Contact>({
+ page,
+ onPageChange: setPage,
+ totalItems: contacts.length,
+ pageSize,
+ });
+ const rowIndex = useTableRowIndex<Contact>({
+ data: pageData,
+ getRowKey: item => item.id,
+ startFrom: start + 1,
+ });
+ const plugins = useMemo(
+ () => ({rowIndex, pagination}),
+ [rowIndex, pagination],
+ );
+
+ return (
+ <Table
+ data={pageData}
+ columns={contactColumns}
+ idKey="id"
+ hasHover
+ rowIndexStart={start + 1}
+ rowCount={contacts.length}
+ plugins={plugins}
+ />
+ );
+ },
+};
diff --git a/packages/core/src/Table/BaseTable.tsx b/packages/core/src/Table/BaseTable.tsx
index 71eabed3f7..21a8830084 100644
--- a/packages/core/src/Table/BaseTable.tsx
+++ b/packages/core/src/Table/BaseTable.tsx
@@ -134,6 +134,12 @@ interface TableRowProps<T extends Record<string, unknown>> {
textOverflow: 'wrap' | 'truncate';
RowComponent: React.ComponentType<TableRowComponentProps>;
CellComponent: React.ComponentType<TableCellComponentProps>;
+ /**
+ * 1-based ARIA row index for this row's position in the full dataset.
+ * `undefined` when the table hasn't opted into ARIA row indexing, in which
+ * case no `aria-rowindex` is emitted (native table semantics).
+ */
+ ariaRowIndex?: number;
}
/**
@@ -150,6 +156,7 @@ function TableRowInner<T extends Record<string, unknown>>({
textOverflow,
RowComponent,
CellComponent,
+ ariaRowIndex,
}: TableRowProps<T>): ReactElement {
// Build cells first
const cells = columns.map((col, columnIndex) => {
@@ -211,12 +218,14 @@ function TableRowInner<T extends Record<string, unknown>>({
);
});
- // Apply plugin transforms for row (with pre-rendered children)
+ // Apply plugin transforms for row (with pre-rendered children).
+ // Seed `aria-rowindex` (when the table opts into ARIA row indexing) as a
+ // base htmlProp so plugins compose over it and can still override.
const rowRenderProps = applyPlugins(
plugins,
p => p.transformBodyRow,
{
- htmlProps: {},
+ htmlProps: ariaRowIndex == null ? {} : {'aria-rowindex': ariaRowIndex},
xstyle: [],
children: <>{cells}</>,
} satisfies BodyRowRenderProps,
@@ -256,6 +265,9 @@ function areRowPropsEqual<T extends Record<string, unknown>>(
if (prevProps.rowIndex !== nextProps.rowIndex) {
return false;
}
+ if (prevProps.ariaRowIndex !== nextProps.ariaRowIndex) {
+ return false;
+ }
if (prevProps.columns !== nextProps.columns) {
return false;
@@ -323,6 +335,8 @@ function BaseTableInner<T extends Record<string, unknown>>({
textOverflow = 'wrap',
scrollWrapper: ScrollWrapper,
emptyState,
+ rowIndexStart,
+ rowCount,
xstyle,
className,
style,
@@ -333,6 +347,18 @@ function BaseTableInner<T extends Record<string, unknown>>({
// Use stable empty array when no plugins provided
const plugins = pluginsProp ?? (EMPTY_PLUGINS as TablePlugin<T>[]);
+ // ARIA row indexing. The row ordinal is an accessibility concern that is
+ // independent of any visible index column: when the consumer opts in (by
+ // passing rowIndexStart or rowCount), body rows carry `aria-rowindex`
+ // reflecting their position in the full dataset, and the <table> carries
+ // `aria-rowcount`. `aria-rowindex` is 1-based and counts data rows from
+ // `rowIndexStart` (default 1); a windowed/paginated view passes the offset
+ // of its first visible row. `aria-rowcount` is `rowCount` when known, or
+ // `-1` (ARIA's "unknown count") for a windowed view with an unknown total.
+ const ariaRowIndexingEnabled = rowIndexStart != null || rowCount != null;
+ const firstRowAriaIndex = rowIndexStart ?? 1;
+ const ariaRowCount = ariaRowIndexingEnabled ? (rowCount ?? -1) : undefined;
+
const RowComponent = TableRow as React.ComponentType<TableRowComponentProps>;
const CellComponent =
TableCell as React.ComponentType<TableCellComponentProps>;
@@ -486,6 +512,7 @@ function BaseTableInner<T extends Record<string, unknown>>({
let tableElement: ReactNode = (
<table
ref={ref}
+ {...(ariaRowCount != null ? {'aria-rowcount': ariaRowCount} : null)}
{...tableRenderProps.htmlProps}
{...mergeProps(
themeProps('base-table'),
@@ -530,6 +557,11 @@ function BaseTableInner<T extends Record<string, unknown>>({
textOverflow={textOverflow}
RowComponent={RowComponent}
CellComponent={CellComponent}
+ ariaRowIndex={
+ ariaRowIndexingEnabled
+ ? firstRowAriaIndex + rowIndex
+ : undefined
+ }
/>
);
})
diff --git a/packages/core/src/Table/Table.doc.mjs b/packages/core/src/Table/Table.doc.mjs
index 0e67708ef6..4e6c8c0bdb 100644
--- a/packages/core/src/Table/Table.doc.mjs
+++ b/packages/core/src/Table/Table.doc.mjs
@@ -93,6 +93,17 @@ export const docs = {
type: 'Record<string, TablePlugin<T>>',
description: 'Named plugins that extend table behavior via the transform pipeline. Converted to an ordered array internally.',
},
+ {
+ name: 'rowIndexStart',
+ type: 'number',
+ description: 'ARIA row index (1-based) for the first rendered body row. The row ordinal is an accessibility concern independent of any visible index column, so setting this (or rowCount) makes the table emit aria-rowindex on body rows and aria-rowcount on the table. For a paginated/windowed view, pass the offset of the first visible row (e.g. (page - 1) * pageSize + 1) so aria-rowindex reflects position in the full dataset. Data-driven mode only.',
+ default: '1',
+ },
+ {
+ name: 'rowCount',
+ type: 'number',
+ description: 'Total number of body rows across all pages/windows, used for aria-rowcount so assistive tech can announce "row X of Y" against the full dataset. When omitted but rowIndexStart is set (windowed view with an unknown total), aria-rowcount is set to -1 per the ARIA unknown-count convention. Data-driven mode only.',
+ },
{
name: 'children',
type: 'ReactNode',
diff --git a/packages/core/src/Table/Table.test.tsx b/packages/core/src/Table/Table.test.tsx
index df9650dd56..01a7872748 100644
--- a/packages/core/src/Table/Table.test.tsx
+++ b/packages/core/src/Table/Table.test.tsx
@@ -1451,3 +1451,88 @@ describe('emptyState', () => {
});
});
});
+
+describe('ARIA row indexing (#3939)', () => {
+ const bodyRows = (container: HTMLElement): HTMLTableRowElement[] =>
+ Array.from(container.querySelectorAll('tbody tr'));
+
+ it('emits no aria-rowindex/aria-rowcount by default', () => {
+ const {container} = render(<Table data={users} columns={columns} />);
+ expect(screen.getByRole('table')).not.toHaveAttribute('aria-rowcount');
+ for (const row of bodyRows(container)) {
+ expect(row).not.toHaveAttribute('aria-rowindex');
+ }
+ });
+
+ it('numbers rows from 1 when rowCount is provided', () => {
+ const {container} = render(
+ <Table data={users} columns={columns} rowCount={users.length} />,
+ );
+ expect(screen.getByRole('table')).toHaveAttribute(
+ 'aria-rowcount',
+ String(users.length),
+ );
+ const indices = bodyRows(container).map(r =>
+ r.getAttribute('aria-rowindex'),
+ );
+ expect(indices).toEqual(['1', '2', '3']);
+ });
+
+ it('offsets aria-rowindex by rowIndexStart for a paginated view', () => {
+ // Page 3 of a 10-per-page dataset: first visible row is dataset row 21.
+ const {container} = render(
+ <Table
+ data={users}
+ columns={columns}
+ rowIndexStart={21}
+ rowCount={100}
+ />,
+ );
+ expect(screen.getByRole('table')).toHaveAttribute('aria-rowcount', '100');
+ const indices = bodyRows(container).map(r =>
+ r.getAttribute('aria-rowindex'),
+ );
+ expect(indices).toEqual(['21', '22', '23']);
+ });
+
+ it('sets aria-rowcount to -1 (unknown) when only rowIndexStart is given', () => {
+ // Windowed/cursor pagination: offset known, total unknown.
+ const {container} = render(
+ <Table data={users} columns={columns} rowIndexStart={5} />,
+ );
+ expect(screen.getByRole('table')).toHaveAttribute('aria-rowcount', '-1');
+ const indices = bodyRows(container).map(r =>
+ r.getAttribute('aria-rowindex'),
+ );
+ expect(indices).toEqual(['5', '6', '7']);
+ });
+
+ it('does not assign an ARIA row index to the header row', () => {
+ render(<Table data={users} columns={columns} rowCount={users.length} />);
+ const header = screen.getAllByRole('row')[0];
+ expect(header).not.toHaveAttribute('aria-rowindex');
+ });
+
+ it('lets a plugin override the seeded aria-rowindex', () => {
+ const plugin: TablePlugin<User> = {
+ transformBodyRow(props, _item, index) {
+ return {
+ ...props,
+ htmlProps: {...props.htmlProps, 'aria-rowindex': 100 + index},
+ };
+ },
+ };
+ const {container} = render(
+ <Table
+ data={users}
+ columns={columns}
+ rowCount={users.length}
+ plugins={{custom: plugin}}
+ />,
+ );
+ const indices = bodyRows(container).map(r =>
+ r.getAttribute('aria-rowindex'),
+ );
+ expect(indices).toEqual(['100', '101', '102']);
+ });
+});
diff --git a/packages/core/src/Table/types.ts b/packages/core/src/Table/types.ts
index 719fabe292..3521776908 100644
--- a/packages/core/src/Table/types.ts
+++ b/packages/core/src/Table/types.ts
@@ -540,6 +540,39 @@ export interface BaseTableProps<
/** Plugins to transform render props at each level */
plugins?: TablePlugin<T>[];
+ /**
+ * ARIA row index (1-based) assigned to the **first** rendered body row.
+ *
+ * The row ordinal is an accessibility concern independent of any visible
+ * index column: `aria-rowindex` on each `<tr>` should reflect the row's
+ * position in the **full** dataset, not just the current page. For a
+ * paginated / windowed view, pass the offset of the first visible row,
+ * e.g. `(page - 1) * pageSize + 1`.
+ *
+ * Setting this (or {@link rowCount}) opts the table into emitting
+ * `aria-rowindex` on body rows and `aria-rowcount` on the `<table>`. Data
+ * rows are numbered from this value; the header row keeps native table
+ * semantics and is not assigned an ARIA row index (so the visible
+ * `useTableRowIndex` numbering and `aria-rowindex` stay in agreement).
+ *
+ * Applies to data-driven mode only (ignored in children mode).
+ *
+ * @default 1
+ */
+ rowIndexStart?: number;
+ /**
+ * Total number of body rows across **all** pages/windows, used for
+ * `aria-rowcount` on the `<table>`. Provide this for paginated data so
+ * assistive tech can announce "row X of Y" against the full dataset.
+ *
+ * When omitted but {@link rowIndexStart} is set (a windowed view with an
+ * unknown total, e.g. cursor pagination), `aria-rowcount` is set to `-1`
+ * per the ARIA convention for an unknown row count.
+ *
+ * Applies to data-driven mode only (ignored in children mode).
+ */
+ rowCount?: number;
+
/** Children mode — render `<tr>`/`<td>` directly instead of data-driven */
children?: ReactNode;
/**