Skip to content

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

TypeScript

feat(Table): plugins get an immutable row and render context; useTableRowIndex numbers from it (#10171)

Cindy Zhang5e0f3d3cb585
diff --git a/.changeset/table-row-context.md b/.changeset/table-row-context.md
new file mode 100644
index 0000000000..4a0c091045
--- /dev/null
+++ b/.changeset/table-row-context.md
@@ -0,0 +1,8 @@
+---
+'@astryxdesign/core': patch
+'@astryxdesign/cli': patch
+---
+
+[feat] Table plugins can now read where a row sits. Table passes each body row and cell transform an immutable `TableRowContext` (the row's key, its zero-based `logicalIndex` in the complete data, the row and header counts, and the row model). It passes the scroll-wrapper transform a `TableRenderContext` with a stable `viewport` reference. A plugin declares `rowModel: 'flat'` when its body transforms keep one row per data item. `useTableSelection` and `useTableStickyColumns` declare it. `useTableRowIndex()` without options now numbers rows from the context (passing `data` still numbers from that array), and rows that move re-render only for plugins that read the index. Read context values during the transform; a later read from a callback warns in development. The CLI's numbered-rows block no longer passes `data`.
+
+@cixzhang
diff --git a/apps/storybook/stories/TableRowIndex.stories.tsx b/apps/storybook/stories/TableRowIndex.stories.tsx
index 33cdeba17b..37e39241b6 100644
--- a/apps/storybook/stories/TableRowIndex.stories.tsx
+++ b/apps/storybook/stories/TableRowIndex.stories.tsx
@@ -60,7 +60,7 @@ type Story = StoryObj;
*/
export const Default: Story = {
render: () => {
- const rowIndex = useTableRowIndex<Track>({data: tracks});
+ const rowIndex = useTableRowIndex<Track>();
return (
<Table
data={tracks}
@@ -79,7 +79,6 @@ export const Default: Story = {
export const CustomLabelAndStart: Story = {
render: () => {
const rowIndex = useTableRowIndex<Track>({
- data: tracks,
label: 'No.',
startFrom: 0,
});
@@ -96,9 +95,9 @@ export const CustomLabelAndStart: Story = {
};
/**
- * The index reflects the current view: with sorting active, pass the **sorted**
- * data to `useTableRowIndex` so numbering renumbers as the order changes. Sort
- * by Plays to see rows renumber 1..n in the new order.
+ * The index reflects the current view: Table gives each row its position, so
+ * numbering renumbers as the sort order changes. Sort by Plays to see rows
+ * renumber 1..n in the new order.
*/
export const RenumbersWithSort: Story = {
render: () => {
@@ -111,11 +110,7 @@ export const RenumbersWithSort: Story = {
onSortChange: setSort,
});
const sortPlugin = useTableSortable<Track>(sortConfig);
- // Pass the sorted data + a stable key so the index tracks the sorted order.
- const rowIndex = useTableRowIndex<Track>({
- data: sortedData,
- getRowKey: item => item.id,
- });
+ const rowIndex = useTableRowIndex<Track>();
const plugins = useMemo(
() => ({rowIndex, sort: sortPlugin}),
[rowIndex, sortPlugin],
diff --git a/docs/specs/components/Table/Table.spec.md b/docs/specs/components/Table/Table.spec.md
index 7688f00cb2..dde5591451 100644
--- a/docs/specs/components/Table/Table.spec.md
+++ b/docs/specs/components/Table/Table.spec.md
@@ -18,6 +18,8 @@ verified_by:
packages/core/src/Table/__tests__/Table.a11y.test.tsx,
packages/core/src/Table/__tests__/Table.a11y.chromium.spec.ts,
packages/core/src/Table/Table.perf.test.tsx,
+ packages/core/src/Table/TableRowContext.test.tsx,
+ packages/core/src/Table/plugins/rowIndex/useTableRowIndex.test.tsx,
packages/core/src/Table/plugins/selection/useTableSelection.test.tsx,
packages/core/src/Table/plugins/sortable/useTableSortable.test.tsx,
packages/core/src/Table/plugins/sortable/__tests__/useTableSortable.a11y.test.tsx,
@@ -457,6 +459,7 @@ for this aggregate ownership.
| FR14 | `__tests__/TableRowGlide.a11y.browser.spec.ts` screenshot checks of the divider mid-glide, in pinned columns, and under an open detail panel; `plugins/rowExpansion/useTableRowExpansion.glide.test.tsx` for the divider an open panel carries | a theme with a custom divider colour; an app override of a row's border; both mid-glide and on a pinned cell; an open detail panel's divider under the same theme and override | a divider whose width, style or colour differs from the row's border, or that drops a theme or app override, fails | `audit:Table/theming` |
| FR15 | `plugins/rowExpansion/useTableRowExpansion.glide.test.tsx` and `__tests__/TableRowGlide.a11y.browser.spec.ts`: row expansion with and without `animatedLayout`, plus source inspection of the panel's entrance and its hide on close | open and close with the handle; without it; reduced motion under a coarse and a fine pointer; a glyph turn beside the glide; a `dividers="grid"` and a `dividers="columns"` table with the option | rows that jump with the handle in a table without column lines, a closing panel that animates or leaves its space empty before the rows arrive, a panel and rows on different motion, a glyph on its own timing beside the glide, travel under reduced motion, or any motion without the handle a table with column lines that glides or animates its panel, or one whose glyph does not keep its own turn, fails | `audit:Table/plugins` |
| Accessibility contract | `__tests__/Table.a11y.test.tsx` and `__tests__/Table.a11y.chromium.spec.ts` bind Table to the base Table contract (`internal/a11y-spec`), composing each module's contract only for the states rendered with that module: the sort module contract (`plugins/sortable/__tests__/useTableSortable.a11y.ts`) for the sorted state; `__tests__/TableScroll.a11y.chromium.spec.ts` keeps the Scroll region evidence | Labelled data-driven, sorted descending, composed RTL with row headers, and empty data | Losing the table role or declared name, row, header, or cell roles, or a part leaving its row or the table, fails the base binding; a missing or stale `aria-sort` fails the composed sort module contract. | `audit:Table/accessibility` |
+| FR17 transform context | `TableRowContext.test.tsx` and `plugins/rowIndex/useTableRowIndex.test.tsx`: row, cell and scroll-wrapper contexts, row-model admission, read-tracked re-rendering, and row numbering from the context | Keys with and without `idKey`; flat, undeclared and declared row models; a re-sort with and without an index read; an appended row with a count read; numbering after a re-sort without `data` | A missing or mutable context, a renumbered or stale index, a moved row re-rendered for a plugin that never reads its index, or numbering from a data lookup fails | `audit:Table/plugins` |
| FR16-FR22 | Pending parent protocol, render-count, API-compile, lifecycle and browser tests plus the module verification maps | Canonical type/key collisions; first-party flat declarations and diagnostic full-render fallbacks; invalid/unknown modes; both owner orders; optional context arities; full/empty/loading/windowed data; pinned paint; native focus and no-op frames | A second key/offset/renderer, order-selected owner, full cell work before slicing, stale source/ref, empty-loading contradiction, or removed focus destination fails | `audit:Table/plugins` |
| Module backlink | `scripts/check-knowledge.mjs` | Active parent and colocated module record | A missing, duplicate, mis-parented, wrong-kind, misnamed, or undiscovered module record fails knowledge validation. | `audit:Table/modules` |
| Theming anatomy map | `scripts/check-knowledge.mjs`, `themingTargets.test.ts`, and CLI parent-aware target discovery tests | Canonical anatomy and eight current targets | Missing, extra, duplicated, prefixed, stale, or independently owned member mappings fail repository validation or discovery coverage. | `audit:Table/theming` |
diff --git a/packages/cli/assets/templates/blocks/components/Table/TableRowIndexTable.doc.mjs b/packages/cli/assets/templates/blocks/components/Table/TableRowIndexTable.doc.mjs
index 6600d7689c..8094d3bb69 100644
--- a/packages/cli/assets/templates/blocks/components/Table/TableRowIndexTable.doc.mjs
+++ b/packages/cli/assets/templates/blocks/components/Table/TableRowIndexTable.doc.mjs
@@ -7,7 +7,7 @@ export const doc = {
name: 'useTableRowIndex — Numbered Rows',
displayName: 'useTableRowIndex — Numbered Rows',
description:
- 'A table with a prepended row-number column via useTableRowIndex. Numbering is monospaced, right-aligned, and follows the rendered data order.',
+ 'A table with a prepended row-number column via useTableRowIndex. Numbering is monospaced, right-aligned, and follows the rows the table renders.',
isReady: true,
aspectRatio: 16 / 9,
componentsUsed: ['Table'],
diff --git a/packages/cli/assets/templates/blocks/components/Table/TableRowIndexTable.tsx b/packages/cli/assets/templates/blocks/components/Table/TableRowIndexTable.tsx
index 4297ee00d9..67a758abf3 100644
--- a/packages/cli/assets/templates/blocks/components/Table/TableRowIndexTable.tsx
+++ b/packages/cli/assets/templates/blocks/components/Table/TableRowIndexTable.tsx
@@ -32,8 +32,8 @@ const columns: TableColumn<Track>[] = [
];
export default function TableRowIndexTable() {
- // Pass the rendered data array — numbering follows its order.
- const rowIndex = useTableRowIndex<Track>({data: tracks});
+ // Table gives each row its position, so numbering follows the rendered rows.
+ const rowIndex = useTableRowIndex<Track>();
return (
<Table
diff --git a/packages/core/api-report.md b/packages/core/api-report.md
index 434b368dea..3a61846646 100644
--- a/packages/core/api-report.md
+++ b/packages/core/api-report.md
@@ -2970,7 +2970,7 @@ hook useTableFiltering: <T extends Record<string, unknown>>(config: UseTableFilt
hook useTableGroupedRows: <T extends Record<string, unknown>>(config: UseTableGroupedRowsConfig<T>) => UseTableGroupedRowsResult<T>
hook useTablePagination: <T extends Record<string, unknown>>(config: UseTablePaginationConfig) => TablePlugin<T>
hook useTableRowExpansion: <T extends Record<string, unknown>>(config: UseTableRowExpansionConfig<T>) => TablePlugin<T>
-hook useTableRowIndex: <T extends Record<string, unknown>>(config: UseTableRowIndexConfig<T>) => TablePlugin<T>
+hook useTableRowIndex: <T extends Record<string, unknown>>(config?: UseTableRowIndexConfig<T>) => TablePlugin<T>
hook useTableRowStatus: <T extends Record<string, unknown>>(config: UseTableRowStatusConfig<T>) => TablePlugin<T>
hook useTableSelection: <T extends Record<string, unknown>>(config: UseTableSelectionConfig<T>) => TablePlugin<T>
hook useTableSelectionState: <T extends Record<string, unknown>>(config: UseTableSelectionStateConfig<T>) => UseTableSelectionStateResult<T>
@@ -5462,12 +5462,13 @@ interface TableFooterProps extends BaseProps<HTMLTableSectionElement> (props of
interface TableHeaderCellProps extends BaseProps<HTMLTableCellElement> (props of TableHeaderCell)
interface TableHeaderProps extends BaseProps<HTMLTableSectionElement> (props of TableHeader)
interface TablePlugin<T extends Record<string, unknown> = Record<string, unknown>>
- transformBodyCell?: (props: BodyCellRenderProps, column: TableColumn<T>, item: T, columnIndex: number, columns: ReadonlyArray<TableColumn<T>>) => BodyCellRenderProps
- transformBodyRow?: (props: BodyRowRenderProps, item: T, index: number) => BodyRowRenderProps
+ rowModel?: TableRenderContext['rowModel']
+ transformBodyCell?: (props: BodyCellRenderProps, column: TableColumn<T>, item: T, columnIndex: number, columns: ReadonlyArray<TableColumn<T>>, context?: TableRowContext) => BodyCellRenderProps
+ transformBodyRow?: (props: BodyRowRenderProps, item: T, index: number, context?: TableRowContext) => BodyRowRenderProps
transformColumns?: (columns: TableColumn<T>[]) => TableColumn<T>[]
transformHeaderCell?: (props: HeaderCellRenderProps, column: TableColumn<T>, columnIndex: number, columns: ReadonlyArray<TableColumn<T>>) => HeaderCellRenderProps
transformHeaderRow?: (props: HeaderRowRenderProps) => HeaderRowRenderProps
- transformScrollWrapper?: (props: ScrollWrapperRenderProps) => ScrollWrapperRenderProps
+ transformScrollWrapper?: (props: ScrollWrapperRenderProps, context?: TableRenderContext) => ScrollWrapperRenderProps
transformTable?: (props: TableRenderProps) => TableRenderProps
transformTableContext?: (children: ReactNode) => ReactNode
interface TableProps<T extends Record<string, unknown>> extends Omit<BaseTableProps<T>, 'plugins' | 'components'>
@@ -5502,9 +5503,23 @@ interface TableSelectionState
hasSelection: boolean
selectedCount: number
selectedKeys: ReadonlySet<string>
+interface TableRenderContext
+ headerRowCount: number
+ logicalRowCount: number
+ mode: 'data' | 'children'
+ rowModel: 'flat' | 'tree' | 'grouped' | 'detail' | 'custom'
+ viewport: React.RefObject<HTMLDivElement | null>
interface TableSelectionToolbarProps extends Omit<ToolbarProps, 'endContent' | 'label'> (props of TableSelectionToolbar)
interface TableSemanticRowStatus
color?: never
+interface TableRowContext
+ headerRowCount: number
+ identityStatus: 'valid' | 'missing' | 'invalid' | 'duplicate'
+ key: string | number | undefined
+ kind: 'product' | 'synthetic' | 'unknown'
+ logicalIndex: number
+ logicalRowCount: number
+ render: TableRenderContext
icon?: never
label: string
status: 'success' | 'warning' | 'error'
@@ -6244,7 +6259,7 @@ interface UseTableSelectionConfig<T extends Record<string, unknown>>
onSelectAll: (event: { isAllSelected: boolean }) => void
onSelectItem: (event: { item: T; isSelected: boolean }) => void
interface UseTableSelectionStateConfig<T extends Record<string, unknown>>
- data: T[]
+ data?: T[]
getIsItemEnabled?: (item: T) => boolean = () => true
getIsItemSelectable?: (item: T) => boolean = () => true
idKey: (keyof T & string) | ((item: T) => string)
@@ -8731,8 +8746,10 @@ TableVerticalAlign (.)
UseTableColumnResizeConfig (.)
UseTableColumnSettingsConfig (.)
UseTableColumnSettingsStateConfig (.)
+TableRenderContext (.)
UseTableColumnSettingsStateReturn (.)
UseTableFilteringConfig (.)
+TableRowContext (.)
UseTableGroupedRowsConfig (.)
UseTableGroupedRowsResult (.)
UseTablePaginationConfig (.)
diff --git a/packages/core/src/Table/BaseTable.tsx b/packages/core/src/Table/BaseTable.tsx
index 6ebdae6959..0ce3f46f15 100644
--- a/packages/core/src/Table/BaseTable.tsx
+++ b/packages/core/src/Table/BaseTable.tsx
@@ -3,8 +3,9 @@
'use client';
/**
* @file BaseTable.tsx
- * @input React, types.ts, columnUtils.ts
- * @output Exports BaseTable component
+ * @input React, types.ts, columnUtils.ts, tableRowContextUsage.ts
+ * @output Exports BaseTable component; passes a TableRowContext to body row
+ * and cell transforms and a TableRenderContext to scroll-wrapper transforms
* @position Core structural component; wrapped by Table.tsx
*
* SYNC: When modified, update these files to stay in sync:
@@ -17,6 +18,7 @@
import {
memo,
useId,
+ useMemo,
useRef,
type ReactElement,
type ReactNode,
@@ -35,6 +37,8 @@ import type {
BodyRowRenderProps,
BodyCellRenderProps,
ScrollWrapperRenderProps,
+ TableRenderContext,
+ TableRowContext,
TableRowComponentProps,
TableCellComponentProps,
TableHeaderCellComponentProps,
@@ -51,6 +55,13 @@ import {TableHeaderCell} from './TableHeaderCell';
import {TableHeader} from './TableHeader';
import {TableBody} from './TableBody';
import {mergeProps} from '../utils';
+import {useMergedRefs} from '../hooks/useMergedRefs';
+import {
+ readsRowCount,
+ readsRowIndex,
+ runPluginTransform,
+ trackRowContext,
+} from './tableRowContextUsage';
import {devError} from '../utils/devWarning';
import {EmptyState} from '../EmptyState';
import {Text} from '../Text';
@@ -114,6 +125,58 @@ function applyPlugins<TPlugin, TProps, TArgs extends unknown[]>(
}, initial);
}
+/**
+ * Run a row-level pipeline. Each transform gets the row context as its last
+ * argument, tracked per plugin so row memoization knows what it reads.
+ */
+function applyRowPlugins<
+ T extends Record<string, unknown>,
+ TProps,
+ TArgs extends unknown[],
+>(
+ plugins: TablePlugin<T>[],
+ getter: (
+ plugin: TablePlugin<T>,
+ ) =>
+ | ((props: TProps, ...args: [...TArgs, TableRowContext?]) => TProps)
+ | undefined,
+ initial: TProps,
+ context: TableRowContext,
+ ...args: TArgs
+): TProps {
+ return applyPlugins(
+ plugins,
+ plugin => {
+ const transform = getter(plugin);
+ return transform == null
+ ? undefined
+ : (props: TProps, ...values: TArgs) =>
+ runPluginTransform(plugin, () =>
+ transform(props, ...values, trackRowContext(plugin, context)),
+ );
+ },
+ initial,
+ ...args,
+ );
+}
+
+/**
+ * The row model the plugins admit: the first non-flat declaration, `custom`
+ * for a body transform that declares no model, otherwise `flat`.
+ */
+function resolveRowModel<T extends Record<string, unknown>>(
+ plugins: ReadonlyArray<TablePlugin<T>>,
+): TableRenderContext['rowModel'] {
+ const modifier = plugins.find(
+ plugin =>
+ plugin.rowModel !== 'flat' &&
+ (plugin.rowModel != null ||
+ plugin.transformBodyRow != null ||
+ plugin.transformBodyCell != null),
+ );
+ return modifier == null ? 'flat' : (modifier.rowModel ?? 'custom');
+}
+
// =============================================================================
// Memoized Table Row Component
// =============================================================================
@@ -149,6 +212,7 @@ interface TableRowProps<T extends Record<string, unknown>> {
textOverflow: 'wrap' | 'truncate';
RowComponent: React.ComponentType<TableRowComponentProps>;
CellComponent: React.ComponentType<TableCellComponentProps>;
+ renderContext: TableRenderContext;
/**
* 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
@@ -171,8 +235,22 @@ function TableRowInner<T extends Record<string, unknown>>({
textOverflow,
RowComponent,
CellComponent,
+ renderContext,
ariaRowIndex,
}: TableRowProps<T>): ReactElement {
+ const context = useMemo<TableRowContext>(
+ () =>
+ Object.freeze({
+ key: rowKey,
+ identityStatus: 'valid',
+ kind: renderContext.rowModel === 'flat' ? 'product' : 'unknown',
+ logicalIndex: rowIndex,
+ logicalRowCount: renderContext.logicalRowCount,
+ headerRowCount: renderContext.headerRowCount,
+ render: renderContext,
+ }),
+ [rowKey, rowIndex, renderContext],
+ );
// Build cells first
const cells = columns.map((col, columnIndex) => {
// Apply column alignment to body cells
@@ -187,10 +265,11 @@ function TableRowInner<T extends Record<string, unknown>>({
columnIndex,
columns: columns as ReadonlyArray<TableColumn<Record<string, unknown>>>,
};
- const cellRenderProps = applyPlugins(
+ const cellRenderProps = applyRowPlugins(
plugins,
p => p.transformBodyCell,
initialBodyCellRenderProps,
+ context,
col,
item,
columnIndex,
@@ -239,7 +318,7 @@ function TableRowInner<T extends Record<string, unknown>>({
// 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(
+ const rowRenderProps = applyRowPlugins(
plugins,
p => p.transformBodyRow,
{
@@ -247,6 +326,7 @@ function TableRowInner<T extends Record<string, unknown>>({
xstyle: [],
children: <>{cells}</>,
} satisfies BodyRowRenderProps,
+ context,
item,
rowIndex,
);
@@ -280,9 +360,11 @@ function TableRowInner<T extends Record<string, unknown>>({
* Shallow compares the item object and checks if columns/plugins references changed.
*
* The row index reaches a row's output only through a plugin's
- * `transformBodyRow` (cells get no index), so it is compared only when some
- * plugin has one: a re-sort that moves rows then re-renders none of them
- * unless a plugin can show the index (row numbering, conditional formatting).
+ * `transformBodyRow`, or through a cell transform that reads the context's
+ * `logicalIndex`, so it is compared only for those plugins: a re-sort that
+ * moves rows then re-renders none of them unless a plugin can show the index
+ * (row numbering, conditional formatting). A changed row count re-renders
+ * rows only when a plugin has read a count.
*/
function areRowPropsEqual<T extends Record<string, unknown>>(
prevProps: TableRowProps<T>,
@@ -293,7 +375,22 @@ function areRowPropsEqual<T extends Record<string, unknown>>(
}
if (
prevProps.rowIndex !== nextProps.rowIndex &&
- nextProps.plugins.some(plugin => plugin.transformBodyRow != null)
+ nextProps.plugins.some(
+ plugin => plugin.transformBodyRow != null || readsRowIndex(plugin),
+ )
+ ) {
+ return false;
+ }
+ const prevRender = prevProps.renderContext;
+ const nextRender = nextProps.renderContext;
+ if (
+ prevRender !== nextRender &&
+ (prevRender.mode !== nextRender.mode ||
+ prevRender.rowModel !== nextRender.rowModel ||
+ prevRender.headerRowCount !== nextRender.headerRowCount ||
+ prevRender.viewport !== nextRender.viewport ||
+ (prevRender.logicalRowCount !== nextRender.logicalRowCount &&
+ nextProps.plugins.some(readsRowCount)))
) {
return false;
}
@@ -419,6 +516,23 @@ function BaseTableInner<T extends Record<string, unknown>>({
}
const resolvedColumns = resolvedColumnsRef.current;
+ const mode = children ? 'children' : 'data';
+ const rowModel = resolveRowModel(plugins);
+ const logicalRowCount = data?.length ?? 0;
+ const headerRowCount = mode === 'data' && resolvedColumns.length > 0 ? 1 : 0;
+ const viewportRef = useRef<HTMLDivElement | null>(null);
+ const renderContext = useMemo<TableRenderContext>(
+ () =>
+ Object.freeze({
+ mode,
+ rowModel,
+ logicalRowCount,
+ headerRowCount,
+ viewport: viewportRef,
+ }),
+ [mode, rowModel, logicalRowCount, headerRowCount],
+ );
+
// Resolve all column widths in a single pass — produces per-column
// inline styles and the aggregate table min-width.
const resolvedWidths = resolveColumnWidths(resolvedColumns);
@@ -622,6 +736,7 @@ function BaseTableInner<T extends Record<string, unknown>>({
textOverflow={textOverflow}
RowComponent={RowComponent}
CellComponent={CellComponent}
+ renderContext={renderContext}
ariaRowIndex={
ariaRowIndexingEnabled
? firstRowAriaIndex + rowIndex
@@ -657,19 +772,28 @@ function BaseTableInner<T extends Record<string, unknown>>({
// Before rendering the wrapper, run the plugin `transformScrollWrapper`
// pipeline so plugins can attach a ref to the scroll container (scroll-aware
// sticky shadows, virtualization) and inject before/after chrome.
- if (ScrollWrapper) {
- const scrollWrapperRenderProps = applyPlugins(
- plugins,
- p => p.transformScrollWrapper,
- {
- htmlProps: {},
- xstyle: [],
- } satisfies ScrollWrapperRenderProps,
- );
-
+ const scrollWrapperRenderProps = ScrollWrapper
+ ? applyPlugins(
+ plugins,
+ p => p.transformScrollWrapper,
+ {
+ htmlProps: {},
+ xstyle: [],
+ } satisfies ScrollWrapperRenderProps,
+ renderContext,
+ )
+ : null;
+ const scrollWrapperRef = useMergedRefs(
+ viewportRef,
+ scrollWrapperRenderProps?.htmlProps.ref,
+ );
+ if (ScrollWrapper && scrollWrapperRenderProps) {
tableElement = (
<ScrollWrapper
- htmlProps={scrollWrapperRenderProps.htmlProps}
+ htmlProps={{
+ ...scrollWrapperRenderProps.htmlProps,
+ ref: scrollWrapperRef,
+ }}
xstyle={scrollWrapperRenderProps.xstyle}
beforeTable={scrollWrapperRenderProps.beforeTable}
afterTable={scrollWrapperRenderProps.afterTable}>
diff --git a/packages/core/src/Table/TableRowContext.test.tsx b/packages/core/src/Table/TableRowContext.test.tsx
new file mode 100644
index 0000000000..f4d6767af2
--- /dev/null
+++ b/packages/core/src/Table/TableRowContext.test.tsx
@@ -0,0 +1,282 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+import {describe, it, expect, vi, afterEach} from 'vitest';
+import {fireEvent, render, screen} from '@testing-library/react';
+import {__resetDevWarnings} from '../utils/devWarning';
+import {Table} from './Table';
+import type {
+ TableColumn,
+ TablePlugin,
+ TableRenderContext,
+ TableRowContext,
+} from './types';
+
+interface Row extends Record<string, unknown> {
+ id: string;
+ name: string;
+}
+
+const data: Row[] = [
+ {id: 'a', name: 'Alice'},
+ {id: 'b', name: 'Bob'},
+ {id: 'c', name: 'Carol'},
+];
+
+const columns: TableColumn<Row>[] = [{key: 'name', header: 'Name'}];
+
+describe('Table transform context (FR17, FR20)', () => {
+ afterEach(() => {
+ __resetDevWarnings();
+ vi.restoreAllMocks();
+ });
+
+ it('passes each body row and cell transform an immutable row context', () => {
+ const rowContexts: TableRowContext[] = [];
+ const cellContexts: TableRowContext[] = [];
+ const plugin: TablePlugin<Row> = {
+ rowModel: 'flat',
+ transformBodyRow(props, _item, _index, context) {
+ if (context) {
+ rowContexts.push(context);
+ }
+ return props;
+ },
+ transformBodyCell(props, _column, _item, _ci, _columns, context) {
+ if (context) {
+ cellContexts.push(context);
+ }
+ return props;
+ },
+ };
+ render(
+ <Table data={data} columns={columns} idKey="id" plugins={{plugin}} />,
+ );
+
+ expect(rowContexts.map(c => [c.key, c.logicalIndex])).toEqual([
+ ['a', 0],
+ ['b', 1],
+ ['c', 2],
+ ]);
+ const [first] = rowContexts;
+ expect(first.identityStatus).toBe('valid');
+ expect(first.kind).toBe('product');
+ expect(first.logicalRowCount).toBe(3);
+ expect(first.headerRowCount).toBe(1);
+ expect(first.render.mode).toBe('data');
+ expect(first.render.rowModel).toBe('flat');
+ expect(first.render.logicalRowCount).toBe(3);
+ expect(Object.isFrozen(first)).toBe(true);
+ expect(Object.isFrozen(first.render)).toBe(true);
+ expect(cellContexts.map(c => c.logicalIndex)).toEqual([0, 1, 2]);
+ });
+
+ it('keys a row by its index when there is no idKey', () => {
+ const keys: TableRowContext['key'][] = [];
+ const plugin: TablePlugin<Row> = {
+ rowModel: 'flat',
+ transformBodyRow(props, _item, _index, context) {
+ keys.push(context?.key);
+ return props;
+ },
+ };
+ render(<Table data={data} columns={columns} plugins={{plugin}} />);
+ expect(keys).toEqual([0, 1, 2]);
+ });
+
+ it('admits a custom row model for an undeclared body transform, and a declared model as declared', () => {
+ const seen: [string, string][] = [];
+ const undeclared: TablePlugin<Row> = {
+ transformBodyRow(props, _item, _index, context) {
+ if (context) {
+ seen.push([context.render.rowModel, context.kind]);
+ }
+ return props;
+ },
+ };
+ const {unmount} = render(
+ <Table
+ data={data.slice(0, 1)}
+ columns={columns}
+ idKey="id"
+ plugins={{undeclared}}
+ />,
+ );
+ unmount();
+ const tree: TablePlugin<Row> = {...undeclared, rowModel: 'tree'};
+ render(
+ <Table
+ data={data.slice(0, 1)}
+ columns={columns}
+ idKey="id"
+ plugins={{tree}}
+ />,
+ );
+ expect(seen).toEqual([
+ ['custom', 'unknown'],
+ ['tree', 'unknown'],
+ ]);
+ });
+
+ it('passes the scroll-wrapper transform the render context, whose viewport is the scroll container', () => {
+ let renderContext: TableRenderContext | undefined;
+ const plugin: TablePlugin<Row> = {
+ transformScrollWrapper(props, context) {
+ renderContext = context;
+ return props;
+ },
+ };
+ render(
+ <Table data={data} columns={columns} idKey="id" plugins={{plugin}} />,
+ );
+ expect(renderContext?.mode).toBe('data');
+ expect(renderContext?.rowModel).toBe('flat');
+ const viewport = renderContext?.viewport.current;
+ expect(viewport).toBeInstanceOf(HTMLDivElement);
+ expect(viewport?.contains(screen.getByRole('table'))).toBe(true);
+ });
+
+ it('re-renders moved rows only for a plugin that reads the index', () => {
+ const indexReader = vi.fn();
+ const nonReader = vi.fn();
+ const reading: TablePlugin<Row> = {
+ rowModel: 'flat',
+ transformBodyCell(props, _column, item, _ci, _columns, context) {
+ indexReader(item.id, context?.logicalIndex);
+ return props;
+ },
+ };
+ const notReading: TablePlugin<Row> = {
+ rowModel: 'flat',
+ transformBodyCell(props, _column, item) {
+ nonReader(item.id);
+ return props;
+ },
+ };
+ const reordered = [data[2], data[0], data[1]];
+
+ const first = render(
+ <Table data={data} columns={columns} idKey="id" plugins={{reading}} />,
+ );
+ indexReader.mockClear();
+ first.rerender(
+ <Table
+ data={reordered}
+ columns={columns}
+ idKey="id"
+ plugins={{reading}}
+ />,
+ );
+ expect(indexReader.mock.calls).toEqual([
+ ['c', 0],
+ ['a', 1],
+ ['b', 2],
+ ]);
+ first.unmount();
+
+ const second = render(
+ <Table data={data} columns={columns} idKey="id" plugins={{notReading}} />,
+ );
+ nonReader.mockClear();
+ second.rerender(
+ <Table
+ data={reordered}
+ columns={columns}
+ idKey="id"
+ plugins={{notReading}}
+ />,
+ );
+ expect(nonReader).not.toHaveBeenCalled();
+ });
+
+ it('re-renders existing rows for a new row count only when a plugin reads a count', () => {
+ const counts: [string, number | undefined][] = [];
+ const plugin: TablePlugin<Row> = {
+ rowModel: 'flat',
+ transformBodyRow(props, item, _index, context) {
+ counts.push([item.id, context?.logicalRowCount]);
+ return props;
+ },
+ };
+ const {rerender} = render(
+ <Table
+ data={data.slice(0, 2)}
+ columns={columns}
+ idKey="id"
+ plugins={{plugin}}
+ />,
+ );
+ counts.length = 0;
+ rerender(
+ <Table data={data} columns={columns} idKey="id" plugins={{plugin}} />,
+ );
+ expect(counts).toEqual([
+ ['a', 3],
+ ['b', 3],
+ ['c', 3],
+ ]);
+ });
+
+ it('gives a callback that copied the index during the transform the current position after a re-sort', () => {
+ const clicked = vi.fn();
+ const plugin: TablePlugin<Row> = {
+ rowModel: 'flat',
+ transformBodyCell(props, _column, item, _ci, _columns, context) {
+ const position = context?.logicalIndex;
+ return {
+ ...props,
+ htmlProps: {
+ ...props.htmlProps,
+ onClick: () => {
+ clicked(item.id, position);
+ },
+ },
+ };
+ },
+ };
+ const {rerender} = render(
+ <Table data={data} columns={columns} idKey="id" plugins={{plugin}} />,
+ );
+ rerender(
+ <Table
+ data={[data[2], data[0], data[1]]}
+ columns={columns}
+ idKey="id"
+ plugins={{plugin}}
+ />,
+ );
+ fireEvent.click(screen.getByText('Carol'));
+ fireEvent.click(screen.getByText('Alice'));
+ expect(clicked.mock.calls).toEqual([
+ ['c', 0],
+ ['a', 1],
+ ]);
+ });
+
+ it('warns in development when a callback reads the index after its transform returned', () => {
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ const lateRead = vi.fn();
+ const plugin: TablePlugin<Row> = {
+ rowModel: 'flat',
+ transformBodyCell(props, _column, _item, _ci, _columns, context) {
+ return {
+ ...props,
+ htmlProps: {
+ ...props.htmlProps,
+ onClick: () => {
+ lateRead(context?.logicalIndex);
+ },
+ },
+ };
+ },
+ };
+ render(
+ <Table data={data} columns={columns} idKey="id" plugins={{plugin}} />,
+ );
+ fireEvent.click(screen.getByText('Alice'));
+ expect(
+ warn.mock.calls.some(([message]) =>
+ String(message).includes('after its transform returned'),
+ ),
+ ).toBe(true);
+ });
+});
diff --git a/packages/core/src/Table/index.ts b/packages/core/src/Table/index.ts
index 82d7328064..1e89ef45a0 100644
--- a/packages/core/src/Table/index.ts
+++ b/packages/core/src/Table/index.ts
@@ -81,6 +81,8 @@ export type {
BodyCellRenderProps,
ScrollWrapperRenderProps,
BaseTableProps,
+ TableRenderContext,
+ TableRowContext,
} from './types';
export type {
TableProps,
diff --git a/packages/core/src/Table/plugins/rowIndex/useTableRowIndex.test.tsx b/packages/core/src/Table/plugins/rowIndex/useTableRowIndex.test.tsx
index e91452b733..989dca73fa 100644
--- a/packages/core/src/Table/plugins/rowIndex/useTableRowIndex.test.tsx
+++ b/packages/core/src/Table/plugins/rowIndex/useTableRowIndex.test.tsx
@@ -41,7 +41,47 @@ function Harness({
);
}
+function ContextHarness({rows = data}: {rows?: Row[]}) {
+ const rowIndex = useTableRowIndex<Row>();
+ return (
+ <Table data={rows} columns={columns} idKey="id" plugins={{rowIndex}} />
+ );
+}
+
describe('useTableRowIndex', () => {
+ it('numbers from a passed data array, not from row positions', () => {
+ // The table shows Bob and Carol; the caller's data orders the numbers.
+ function Subset() {
+ const rowIndex = useTableRowIndex<Row>({data});
+ return (
+ <Table
+ data={[data[1], data[2]]}
+ columns={columns}
+ idKey="id"
+ plugins={{rowIndex}}
+ />
+ );
+ }
+ render(<Subset />);
+ const rows = screen.getAllByRole('row');
+ expect(within(rows[1]).getByText('2')).toBeInTheDocument();
+ expect(within(rows[2]).getByText('3')).toBeInTheDocument();
+ });
+
+ it('numbers rows from the row context without data, and renumbers after a re-sort', () => {
+ const {rerender} = render(<ContextHarness />);
+ let rows = screen.getAllByRole('row');
+ expect(within(rows[1]).getByText('1')).toBeInTheDocument();
+ expect(within(rows[3]).getByText('3')).toBeInTheDocument();
+
+ rerender(<ContextHarness rows={[data[2], data[0], data[1]]} />);
+ rows = screen.getAllByRole('row');
+ expect(within(rows[1]).getByText('Carol')).toBeInTheDocument();
+ expect(within(rows[1]).getByText('1')).toBeInTheDocument();
+ expect(within(rows[2]).getByText('Alice')).toBeInTheDocument();
+ expect(within(rows[2]).getByText('2')).toBeInTheDocument();
+ });
+
it('prepends a header cell with the default label', () => {
render(<Harness />);
const headers = screen.getAllByRole('columnheader');
diff --git a/packages/core/src/Table/plugins/rowIndex/useTableRowIndex.tsx b/packages/core/src/Table/plugins/rowIndex/useTableRowIndex.tsx
index 04c9006842..66811bf034 100644
--- a/packages/core/src/Table/plugins/rowIndex/useTableRowIndex.tsx
+++ b/packages/core/src/Table/plugins/rowIndex/useTableRowIndex.tsx
@@ -4,7 +4,7 @@
/**
* @file useTableRowIndex.tsx
- * @input React, StyleX, Table types + the rendered data array
+ * @input React, StyleX, Table types, and each body row's TableRowContext
* @output Exports useTableRowIndex hook + config type
* @position Row-index plugin; consumed by Table via plugins prop
*
@@ -21,22 +21,20 @@ import type {TableColumn, TablePlugin} from '../../types';
/**
* Configuration for {@link useTableRowIndex}.
*
- * Astryx's `renderCell` receives only the row item (not its position), so the
- * plugin needs the rendered `data` array — the same array passed to
- * `<Table data>` — to derive each row's 1-based ordinal. Pass `getRowKey` when
- * items don't have a stable identity by reference (e.g. new objects each
- * render); it must return a **unique** string per row (duplicate keys collapse
- * to a single ordinal).
+ * Without `data`, the plugin numbers each body row from the position Table
+ * gives it. With `data`, numbers follow that array, as before.
*/
export interface UseTableRowIndexConfig<T extends Record<string, unknown>> {
- /** The data array currently rendered by the table (post sort/filter/page). */
- data: T[];
/**
- * Optional key extractor returning a **unique** string per row. When
- * provided, index lookup is keyed by the returned string (stable across new
- * object identities); otherwise items are matched by reference identity.
- * For a stable plugin identity across renders, memoize this with
- * `useCallback`.
+ * Optional: the array whose order the numbers follow. Omit it to number
+ * rows from the positions Table gives them.
+ */
+ data?: T[];
+ /**
+ * Optional key extractor returning a **unique** string per row, used with
+ * `data`. When provided, rows match `data` by the returned string (stable
+ * across new object identities); otherwise by reference identity. For a
+ * stable plugin identity across renders, memoize this with `useCallback`.
*/
getRowKey?: (item: T) => string;
/** Header label for the index column. @default '#' */
@@ -45,6 +43,7 @@ export interface UseTableRowIndexConfig<T extends Record<string, unknown>> {
startFrom?: number;
}
+const INDEX_COLUMN_KEY = '__rowIndex';
const INDEX_COLUMN_WIDTH = {type: 'pixel' as const, value: 48};
const styles = stylex.create({
@@ -58,24 +57,26 @@ const styles = stylex.create({
/**
* Returns a {@link TablePlugin} that prepends a right-aligned, monospaced
- * row-number column. Numbering follows the order of the rendered `data` array,
- * so it reflects the current sort / filter / pagination view.
+ * row-number column. Numbering follows the rows the table renders, so it
+ * reflects the current sort / filter / pagination view.
*
* @example
* ```
- * const rowIndex = useTableRowIndex({data});
+ * const rowIndex = useTableRowIndex();
* <Table data={data} columns={columns} idKey="id" plugins={{rowIndex}} />;
* ```
*/
export function useTableRowIndex<T extends Record<string, unknown>>(
- config: UseTableRowIndexConfig<T>,
+ config: UseTableRowIndexConfig<T> = {},
): TablePlugin<T> {
const {data, getRowKey, label = '#', startFrom = 1} = config;
- // Single item → ordinal lookup, built in one pass and rebuilt only when the
- // data array or key extractor changes. Keyed by getRowKey when provided
+ // The lookup into a caller's `data`. Keyed by getRowKey when provided
// (stable across new object identities), otherwise by object reference.
const lookup = useMemo(() => {
+ if (data == null) {
+ return null;
+ }
const map = new Map<unknown, number>();
for (let i = 0; i < data.length; i++) {
const item = data[i];
@@ -85,19 +86,28 @@ export function useTableRowIndex<T extends Record<string, unknown>>(
map.get(getRowKey ? getRowKey(item) : item);
}, [data, getRowKey]);
- // The plugin object depends only on the stable lookup and the presentational
- // props — not on data directly — so it stays as stable as its inputs allow.
- return useMemo(
- (): TablePlugin<T> => ({
+ return useMemo((): TablePlugin<T> => {
+ // Table runs each cell's transforms just before it renders that cell. So
+ // the index cell's renderer reads the position that its own transform
+ // stored.
+ const positions = new WeakMap<T, number>();
+ return {
+ rowModel: 'flat',
+ transformBodyCell(props, column, item, _columnIndex, _columns, context) {
+ if (lookup == null && column.key === INDEX_COLUMN_KEY && context) {
+ positions.set(item, context.logicalIndex);
+ }
+ return props;
+ },
transformColumns(columns) {
const indexColumn: TableColumn<T> = {
- key: '__rowIndex',
+ key: INDEX_COLUMN_KEY,
header: label,
width: INDEX_COLUMN_WIDTH,
align: 'end',
resizable: false,
renderCell: (item: T) => {
- const idx = lookup(item);
+ const idx = lookup == null ? positions.get(item) : lookup(item);
if (idx == null) {
return null;
}
@@ -108,7 +118,6 @@ export function useTableRowIndex<T extends Record<string, unknown>>(
};
return [indexColumn, ...columns];
},
- }),
- [label, startFrom, lookup],
- );
+ };
+ }, [label, startFrom, lookup]);
}
diff --git a/packages/core/src/Table/plugins/selection/useTableSelection.tsx b/packages/core/src/Table/plugins/selection/useTableSelection.tsx
index 8f5bf31999..c09b288c33 100644
--- a/packages/core/src/Table/plugins/selection/useTableSelection.tsx
+++ b/packages/core/src/Table/plugins/selection/useTableSelection.tsx
@@ -399,6 +399,7 @@ export function useTableSelection<T extends Record<string, unknown>>(
return useMemo(
(): TablePlugin<T> => ({
+ rowModel: 'flat',
transformTableContext(children: ReactNode) {
return (
<SelectionStoreContext value={store}>
diff --git a/packages/core/src/Table/plugins/stickyColumns/useTableStickyColumns.tsx b/packages/core/src/Table/plugins/stickyColumns/useTableStickyColumns.tsx
index cf0428dc2e..3fa24e03b4 100644
--- a/packages/core/src/Table/plugins/stickyColumns/useTableStickyColumns.tsx
+++ b/packages/core/src/Table/plugins/stickyColumns/useTableStickyColumns.tsx
@@ -611,6 +611,7 @@ export function useTableStickyColumns<T extends Record<string, unknown>>(
return useMemo(
(): TablePlugin<T> => ({
+ rowModel: 'flat',
transformTableContext(children: ReactNode): ReactNode {
return (
<>
diff --git a/packages/core/src/Table/tableRowContextUsage.ts b/packages/core/src/Table/tableRowContextUsage.ts
new file mode 100644
index 0000000000..2618b8e54e
--- /dev/null
+++ b/packages/core/src/Table/tableRowContextUsage.ts
@@ -0,0 +1,105 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file tableRowContextUsage.ts
+ * @input Immutable row contexts and the plugins whose transforms read them
+ * @output Per-plugin tracked contexts, and which plugins read the row index or
+ * the row count
+ * @position Private to BaseTable's row memoization; plugins never import it
+ */
+
+import type {TablePlugin, TableRowContext} from './types';
+import {warnOnce} from '../utils/devWarning';
+
+const indexReadingPlugins = new WeakSet<object>();
+const countReadingPlugins = new WeakSet<object>();
+const trackedContexts = new WeakMap<
+ TableRowContext,
+ WeakMap<object, TableRowContext>
+>();
+let transformingPlugin: object | null = null;
+
+/** Run one plugin transform; context reads inside it are in time. */
+export function runPluginTransform<R>(plugin: object, transform: () => R): R {
+ const outer = transformingPlugin;
+ transformingPlugin = plugin;
+ try {
+ return transform();
+ } finally {
+ transformingPlugin = outer;
+ }
+}
+
+/**
+ * Tracking sees only reads made during the transform. A row that does not
+ * re-render keeps its old context, so a later read can return a stale index
+ * or count.
+ */
+function warnIfLate(plugin: object, field: string): void {
+ if (transformingPlugin !== plugin) {
+ warnOnce(
+ `table-row-context-late-read-${field}`,
+ 'Table',
+ `A plugin read TableRowContext.${field} after its transform returned. ` +
+ 'Read context values during the transform and copy them into any callback it returns.',
+ );
+ }
+}
+
+/** Whether a transform of the plugin has read a row's `logicalIndex`. */
+export function readsRowIndex<T extends Record<string, unknown>>(
+ plugin: TablePlugin<T>,
+): boolean {
+ return indexReadingPlugins.has(plugin);
+}
+
+/** Whether a transform of the plugin has read a row count. */
+export function readsRowCount<T extends Record<string, unknown>>(
+ plugin: TablePlugin<T>,
+): boolean {
+ return countReadingPlugins.has(plugin);
+}
+
+/**
+ * The context as one plugin sees it. Its getters record which values the
+ * plugin reads, so a row re-renders for a moved index or a changed count only
+ * when a plugin can show it. The values stay the same as the context's.
+ */
+export function trackRowContext<T extends Record<string, unknown>>(
+ plugin: TablePlugin<T>,
+ context: TableRowContext,
+): TableRowContext {
+ let byPlugin = trackedContexts.get(context);
+ if (byPlugin == null) {
+ byPlugin = new WeakMap();
+ trackedContexts.set(context, byPlugin);
+ }
+ const cached = byPlugin.get(plugin);
+ if (cached != null) {
+ return cached;
+ }
+ const render = Object.freeze({
+ ...context.render,
+ get logicalRowCount() {
+ warnIfLate(plugin, 'render.logicalRowCount');
+ countReadingPlugins.add(plugin);
+ return context.render.logicalRowCount;
+ },
+ });
+ const tracked: TableRowContext = Object.freeze({
+ ...context,
+ render,
+ get logicalIndex() {
+ warnIfLate(plugin, 'logicalIndex');
+ indexReadingPlugins.add(plugin);
+ return context.logicalIndex;
+ },
+ get logicalRowCount() {
+ warnIfLate(plugin, 'logicalRowCount');
+ countReadingPlugins.add(plugin);
+ return context.logicalRowCount;
+ },
+ });
+ byPlugin.set(plugin, tracked);
+ return tracked;
+}
diff --git a/packages/core/src/Table/types.ts b/packages/core/src/Table/types.ts
index bd6b93e36c..cfc5a0cb45 100644
--- a/packages/core/src/Table/types.ts
+++ b/packages/core/src/Table/types.ts
@@ -422,6 +422,51 @@ export type TableContextActions =
// Plugin Interface
// =============================================================================
+/**
+ * Immutable facts about the table that Table passes to row, cell and
+ * scroll-wrapper transforms.
+ */
+export interface TableRenderContext {
+ /** The branch Table renders: `data` rows from `data`, or caller `children`. */
+ readonly mode: 'data' | 'children';
+ /**
+ * The row model the plugins admit. `flat` unless a plugin declares another
+ * model, or has a body transform and declares none (`custom`).
+ */
+ readonly rowModel: 'flat' | 'tree' | 'grouped' | 'detail' | 'custom';
+ /** The number of product rows in the complete `data` input. */
+ readonly logicalRowCount: number;
+ /** The number of header rows: 1 when Table renders a header, else 0. */
+ readonly headerRowCount: number;
+ /** The scroll container around the `<table>`. Its reference is stable. */
+ readonly viewport: React.RefObject<HTMLDivElement | null>;
+}
+
+/**
+ * Immutable facts about one body row that Table passes to its transforms.
+ * Read its values during the transform, and copy what a returned callback
+ * needs: a row that does not re-render keeps its old context.
+ */
+export interface TableRowContext {
+ /** The row's key: its `idKey` value, or its index when there is no `idKey`. */
+ readonly key: string | number | undefined;
+ /** Whether the key is a usable identity. */
+ readonly identityStatus: 'valid' | 'missing' | 'invalid' | 'duplicate';
+ /** `product` for a row of a flat dataset; `unknown` for another row model. */
+ readonly kind: 'product' | 'synthetic' | 'unknown';
+ /**
+ * The zero-based position of the row in the complete `data` input. A row
+ * keeps this index when only some rows are mounted.
+ */
+ readonly logicalIndex: number;
+ /** The number of product rows in the complete `data` input. */
+ readonly logicalRowCount: number;
+ /** The number of header rows: 1 when Table renders a header, else 0. */
+ readonly headerRowCount: number;
+ /** The table's render context. */
+ readonly render: TableRenderContext;
+}
+
/**
* Table plugin — transforms render props at each structural level.
* Plugins compose by sequential application (first plugin's output feeds next).
@@ -449,6 +494,12 @@ export type TableContextActions =
export interface TablePlugin<
T extends Record<string, unknown> = Record<string, unknown>,
> {
+ /**
+ * The row model this plugin's body transforms keep. Declare `'flat'` when
+ * they keep one product row per data item. A body transform without a
+ * declaration makes the table's row model `custom`.
+ */
+ readonly rowModel?: TableRenderContext['rowModel'];
/**
* Transform the column definitions before rendering.
* Runs before any element-level transforms. Use to filter, reorder,
@@ -471,14 +522,19 @@ export interface TablePlugin<
columnIndex: number,
columns: ReadonlyArray<TableColumn<T>>,
) => HeaderCellRenderProps;
- /** Transform each body `<tr>` props */
+ /**
+ * Transform each body `<tr>` props. Read `context` values during the
+ * transform, not later in a callback it returns.
+ */
transformBodyRow?: (
props: BodyRowRenderProps,
item: T,
index: number,
+ context?: TableRowContext,
) => BodyRowRenderProps;
/**
- * Transform each body `<td>` props.
+ * Transform each body `<td>` props. Read `context` values during the
+ * transform, not later in a callback it returns.
*
* `columnIndex` and the full `columns` list are provided for plugins that
* need to reason about column position (e.g. cumulative sticky offsets).
@@ -489,6 +545,7 @@ export interface TablePlugin<
item: T,
columnIndex: number,
columns: ReadonlyArray<TableColumn<T>>,
+ context?: TableRowContext,
) => BodyCellRenderProps;
/**
* Transform the scroll-wrapper region — the `<div>` wrapping the `<table>`
@@ -498,6 +555,7 @@ export interface TablePlugin<
*/
transformScrollWrapper?: (
props: ScrollWrapperRenderProps,
+ context?: TableRenderContext,
) => ScrollWrapperRenderProps;
/** Wrap the table output in context providers */
transformTableContext?: (children: ReactNode) => ReactNode;
diff --git a/packages/core/src/Table/useBaseTablePlugins.ts b/packages/core/src/Table/useBaseTablePlugins.ts
index a86796a0a8..7f20f27f91 100644
--- a/packages/core/src/Table/useBaseTablePlugins.ts
+++ b/packages/core/src/Table/useBaseTablePlugins.ts
@@ -89,6 +89,9 @@ function sortPluginEntries<T extends Record<string, unknown>>(
// ======================================================================
// Plugin Validation (dev mode only)
// ======================================================================
+/** Known declaration fields on the TablePlugin interface. */
+const VALID_DECLARATION_KEYS = new Set(['rowModel']);
+
/** Known transform method names on the TablePlugin interface. */
const VALID_TRANSFORM_KEYS = new Set([
'transformColumns',
@@ -117,11 +120,11 @@ function validatePlugin<T extends Record<string, unknown>>(
// Warn about unknown keys (likely misspelled transform names)
for (const key of keys) {
- if (!VALID_TRANSFORM_KEYS.has(key)) {
+ if (!VALID_TRANSFORM_KEYS.has(key) && !VALID_DECLARATION_KEYS.has(key)) {
devWarn(
'Table',
`Plugin "${name}" has unknown key "${key}". ` +
- `Valid keys: ${[...VALID_TRANSFORM_KEYS].join(', ')}. ` +
+ `Valid keys: ${[...VALID_DECLARATION_KEYS, ...VALID_TRANSFORM_KEYS].join(', ')}. ` +
`This key will be ignored.`,
);
}
diff --git a/packages/core/src/Table/useTableRowIndex.doc.mjs b/packages/core/src/Table/useTableRowIndex.doc.mjs
index 1ea3344c8b..2d12239edc 100644
--- a/packages/core/src/Table/useTableRowIndex.doc.mjs
+++ b/packages/core/src/Table/useTableRowIndex.doc.mjs
@@ -7,20 +7,19 @@ export const docs = {
subComponentOf: 'Table',
displayName: 'useTableRowIndex',
description:
- 'Hook that returns a TablePlugin which prepends a right-aligned, monospaced row-number column. Numbering follows the rendered data order (reflecting the current sort / filter / pagination view) and starts at 1 by default. Astryx renderCell receives only the row item, so the plugin takes the rendered data array to derive each ordinal.',
+ 'Hook that returns a TablePlugin which prepends a right-aligned, monospaced row-number column. Numbering follows the rows the table renders (reflecting the current sort / filter / pagination view) and starts at 1 by default. Without data, Table gives each row its position; with data, numbers follow that array.',
props: [
{
name: 'data',
type: 'T[]',
description:
- 'The data array currently rendered by the table (post sort/filter/page). Numbering follows this order.',
- required: true,
+ 'Optional: the array whose order the numbers follow. Omit it to number rows from the positions Table gives them.',
},
{
name: 'getRowKey',
type: '(item: T) => string',
description:
- 'Optional key extractor returning a unique string per row. When provided, index lookup is keyed by the returned string; otherwise items are matched by reference identity. Memoize with useCallback for a stable plugin identity.',
+ 'Optional key extractor used with data, returning a unique string per row. When provided, rows match data by the returned string; otherwise by reference identity. Memoize with useCallback for a stable plugin identity.',
},
{
name: 'label',
@@ -40,10 +39,10 @@ export const docs = {
/** @type {import('@astryxdesign/cli/authoring').ComponentTranslationDoc} */
export const docsDense = {
description:
- 'Returns a TablePlugin that prepends a right-aligned monospaced row-number column. Numbering follows the rendered data order (current sort/filter/page view), 1-based by default. Pass the rendered data array; renderCell only receives the item so the plugin derives ordinals from it.',
+ 'Returns a TablePlugin that prepends a right-aligned monospaced row-number column. Numbering follows the rendered rows (current sort/filter/page view), 1-based by default. Without data, Table supplies each row position; with data, numbers follow it.',
propDescriptions: {
- data: 'The rendered data array (post sort/filter/page). Numbering follows this order.',
- getRowKey: 'Optional key extractor returning a unique string per row; otherwise items match by reference.',
+ data: 'Optional array whose order the numbers follow; omit to use Table row positions.',
+ getRowKey: 'Optional key extractor used with data; otherwise items match by reference.',
label: "Header label for the index column. Default '#'.",
startFrom: 'First index value. Default 1.',
},