From 42e9af9afd4aed6cfa8b3bca63595c95de3f4f41 Mon Sep 17 00:00:00 2001 From: Cindy Zhang Date: Thu, 5 Nov 2026 14:31:10 -0800 Subject: [PATCH 1/5] test(Table): row, cell and wrapper transforms get an immutable context; useTableRowIndex numbers from it (red) Co-authored-by: Humberto Virtudes --- .../core/src/Table/TableRowContext.test.tsx | 212 ++++++++++++++++++ .../rowIndex/useTableRowIndex.test.tsx | 21 ++ 2 files changed, 233 insertions(+) create mode 100644 packages/core/src/Table/TableRowContext.test.tsx diff --git a/packages/core/src/Table/TableRowContext.test.tsx b/packages/core/src/Table/TableRowContext.test.tsx new file mode 100644 index 0000000000000..fe6e8ea70f7a2 --- /dev/null +++ b/packages/core/src/Table/TableRowContext.test.tsx @@ -0,0 +1,212 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +import {describe, it, expect, vi} from 'vitest'; +import {render, screen} from '@testing-library/react'; +import {Table} from './Table'; +import type { + TableColumn, + TablePlugin, + TableRenderContext, + TableRowContext, +} from './types'; + +interface Row extends Record { + id: string; + name: string; +} + +const data: Row[] = [ + {id: 'a', name: 'Alice'}, + {id: 'b', name: 'Bob'}, + {id: 'c', name: 'Carol'}, +]; + +const columns: TableColumn[] = [{key: 'name', header: 'Name'}]; + +describe('Table transform context (FR17, FR20)', () => { + it('passes each body row and cell transform an immutable row context', () => { + const rowContexts: TableRowContext[] = []; + const cellContexts: TableRowContext[] = []; + const plugin: TablePlugin = { + 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( + , + ); + + 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 = { + rowModel: 'flat', + transformBodyRow(props, _item, _index, context) { + keys.push(context?.key); + return props; + }, + }; + render(
); + 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 = { + transformBodyRow(props, _item, _index, context) { + if (context) { + seen.push([context.render.rowModel, context.kind]); + } + return props; + }, + }; + const {unmount} = render( +
, + ); + unmount(); + const tree: TablePlugin = {...undeclared, rowModel: 'tree'}; + render( +
, + ); + 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 = { + transformScrollWrapper(props, context) { + renderContext = context; + return props; + }, + }; + render( +
, + ); + 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 = { + rowModel: 'flat', + transformBodyCell(props, _column, item, _ci, _columns, context) { + indexReader(item.id, context?.logicalIndex); + return props; + }, + }; + const notReading: TablePlugin = { + rowModel: 'flat', + transformBodyCell(props, _column, item) { + nonReader(item.id); + return props; + }, + }; + const reordered = [data[2], data[0], data[1]]; + + const first = render( +
, + ); + indexReader.mockClear(); + first.rerender( +
, + ); + expect(indexReader.mock.calls).toEqual([ + ['c', 0], + ['a', 1], + ['b', 2], + ]); + first.unmount(); + + const second = render( +
, + ); + nonReader.mockClear(); + second.rerender( +
, + ); + 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 = { + rowModel: 'flat', + transformBodyRow(props, item, _index, context) { + counts.push([item.id, context?.logicalRowCount]); + return props; + }, + }; + const {rerender} = render( +
, + ); + counts.length = 0; + rerender( +
, + ); + expect(counts).toEqual([ + ['a', 3], + ['b', 3], + ['c', 3], + ]); + }); +}); diff --git a/packages/core/src/Table/plugins/rowIndex/useTableRowIndex.test.tsx b/packages/core/src/Table/plugins/rowIndex/useTableRowIndex.test.tsx index e91452b7336ac..5e26df3087eb9 100644 --- a/packages/core/src/Table/plugins/rowIndex/useTableRowIndex.test.tsx +++ b/packages/core/src/Table/plugins/rowIndex/useTableRowIndex.test.tsx @@ -41,7 +41,28 @@ function Harness({ ); } +function ContextHarness({rows = data}: {rows?: Row[]}) { + const rowIndex = useTableRowIndex(); + return ( +
+ ); +} + describe('useTableRowIndex', () => { + it('numbers rows from the row context without data, and renumbers after a re-sort', () => { + const {rerender} = render(); + let rows = screen.getAllByRole('row'); + expect(within(rows[1]).getByText('1')).toBeInTheDocument(); + expect(within(rows[3]).getByText('3')).toBeInTheDocument(); + + rerender(); + 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(); const headers = screen.getAllByRole('columnheader'); From a37b00db4a69e9c822dc0c9b2598dcd385d00b86 Mon Sep 17 00:00:00 2001 From: Cindy Zhang Date: Thu, 5 Nov 2026 15:05:36 -0800 Subject: [PATCH 2/5] feat(Table): row, cell and scroll-wrapper transforms get an immutable TableRowContext / TableRenderContext; useTableRowIndex numbers from it Table builds one frozen render context per render and one frozen row context per mounted row, and passes them as the optional last transform argument. A plugin declares rowModel; selection, sticky columns and row index declare 'flat'. Per-plugin tracked contexts record index and count reads, so a moved row re-renders only for a plugin that reads its index. useTableRowIndex numbers from logicalIndex through its own cell transform; data is optional. Split from #8280 (the transform-context piece only). Co-authored-by: Humberto Virtudes --- .changeset/table-row-context.md | 7 + docs/specs/components/Table/Table.spec.md | 3 + packages/core/api-report.md | 27 ++- packages/core/src/Table/BaseTable.tsx | 159 +++++++++++++++--- packages/core/src/Table/index.ts | 2 + .../plugins/rowIndex/useTableRowIndex.tsx | 69 ++++---- .../plugins/selection/useTableSelection.tsx | 1 + .../stickyColumns/useTableStickyColumns.tsx | 1 + .../core/src/Table/tableRowContextUsage.ts | 73 ++++++++ packages/core/src/Table/types.ts | 50 ++++++ .../core/src/Table/useBaseTablePlugins.ts | 7 +- .../core/src/Table/useTableRowIndex.doc.mjs | 13 +- 12 files changed, 350 insertions(+), 62 deletions(-) create mode 100644 .changeset/table-row-context.md create mode 100644 packages/core/src/Table/tableRowContextUsage.ts diff --git a/.changeset/table-row-context.md b/.changeset/table-row-context.md new file mode 100644 index 0000000000000..d58cc800aeac4 --- /dev/null +++ b/.changeset/table-row-context.md @@ -0,0 +1,7 @@ +--- +'@astryxdesign/core': 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` now numbers rows from the context, so its `data` option is optional, and rows that move re-render only for plugins that read the index. + +@cixzhang diff --git a/docs/specs/components/Table/Table.spec.md b/docs/specs/components/Table/Table.spec.md index e6a731008d226..62e12d8b4992a 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, @@ -453,6 +455,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/core/api-report.md b/packages/core/api-report.md index e67337f88e39f..968918a7df988 100644 --- a/packages/core/api-report.md +++ b/packages/core/api-report.md @@ -2958,7 +2958,7 @@ hook useTableFiltering: >(config: UseTableFilt hook useTableGroupedRows: >(config: UseTableGroupedRowsConfig) => UseTableGroupedRowsResult hook useTablePagination: >(config: UseTablePaginationConfig) => TablePlugin hook useTableRowExpansion: >(config: UseTableRowExpansionConfig) => TablePlugin -hook useTableRowIndex: >(config: UseTableRowIndexConfig) => TablePlugin +hook useTableRowIndex: >(config?: UseTableRowIndexConfig) => TablePlugin hook useTableRowStatus: >(config: UseTableRowStatusConfig) => TablePlugin hook useTableSelection: >(config: UseTableSelectionConfig) => TablePlugin hook useTableSelectionState: >(config: UseTableSelectionStateConfig) => UseTableSelectionStateResult @@ -5433,12 +5433,13 @@ interface TableFooterProps extends BaseProps (props of interface TableHeaderCellProps extends BaseProps (props of TableHeaderCell) interface TableHeaderProps extends BaseProps (props of TableHeader) interface TablePlugin = Record> - transformBodyCell?: (props: BodyCellRenderProps, column: TableColumn, item: T, columnIndex: number, columns: ReadonlyArray>) => BodyCellRenderProps - transformBodyRow?: (props: BodyRowRenderProps, item: T, index: number) => BodyRowRenderProps + rowModel?: TableRenderContext['rowModel'] + transformBodyCell?: (props: BodyCellRenderProps, column: TableColumn, item: T, columnIndex: number, columns: ReadonlyArray>, context?: TableRowContext) => BodyCellRenderProps + transformBodyRow?: (props: BodyRowRenderProps, item: T, index: number, context?: TableRowContext) => BodyRowRenderProps transformColumns?: (columns: TableColumn[]) => TableColumn[] transformHeaderCell?: (props: HeaderCellRenderProps, column: TableColumn, columnIndex: number, columns: ReadonlyArray>) => 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> extends Omit, 'plugins' | 'components'> @@ -5473,9 +5474,23 @@ interface TableSelectionState hasSelection: boolean selectedCount: number selectedKeys: ReadonlySet +interface TableRenderContext + headerRowCount: number + logicalRowCount: number + mode: 'data' | 'children' + rowModel: 'flat' | 'tree' | 'grouped' | 'detail' | 'custom' + viewport: React.RefObject interface TableSelectionToolbarProps extends Omit (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' @@ -6213,7 +6228,7 @@ interface UseTableSelectionConfig> onSelectAll: (event: { isAllSelected: boolean }) => void onSelectItem: (event: { item: T; isSelected: boolean }) => void interface UseTableSelectionStateConfig> - data: T[] + data?: T[] getIsItemEnabled?: (item: T) => boolean = () => true getIsItemSelectable?: (item: T) => boolean = () => true idKey: (keyof T & string) | ((item: T) => string) @@ -8690,8 +8705,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 6ebdae69595cd..82a142060b3e4 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,12 @@ import {TableHeaderCell} from './TableHeaderCell'; import {TableHeader} from './TableHeader'; import {TableBody} from './TableBody'; import {mergeProps} from '../utils'; +import {useMergedRefs} from '../hooks/useMergedRefs'; +import { + readsRowCount, + readsRowIndex, + trackRowContext, +} from './tableRowContextUsage'; import {devError} from '../utils/devWarning'; import {EmptyState} from '../EmptyState'; import {Text} from '../Text'; @@ -114,6 +124,56 @@ function applyPlugins( }, 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, + TProps, + TArgs extends unknown[], +>( + plugins: TablePlugin[], + getter: ( + plugin: TablePlugin, + ) => + | ((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) => + 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>( + plugins: ReadonlyArray>, +): 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 +209,7 @@ interface TableRowProps> { textOverflow: 'wrap' | 'truncate'; RowComponent: React.ComponentType; CellComponent: React.ComponentType; + 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 +232,22 @@ function TableRowInner>({ textOverflow, RowComponent, CellComponent, + renderContext, ariaRowIndex, }: TableRowProps): ReactElement { + const context = useMemo( + () => + 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 +262,11 @@ function TableRowInner>({ columnIndex, columns: columns as ReadonlyArray>>, }; - const cellRenderProps = applyPlugins( + const cellRenderProps = applyRowPlugins( plugins, p => p.transformBodyCell, initialBodyCellRenderProps, + context, col, item, columnIndex, @@ -239,7 +315,7 @@ function TableRowInner>({ // 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 +323,7 @@ function TableRowInner>({ xstyle: [], children: <>{cells}, } satisfies BodyRowRenderProps, + context, item, rowIndex, ); @@ -280,9 +357,11 @@ function TableRowInner>({ * 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>( prevProps: TableRowProps, @@ -293,7 +372,22 @@ function areRowPropsEqual>( } 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 +513,23 @@ function BaseTableInner>({ } 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(null); + const renderContext = useMemo( + () => + 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 +733,7 @@ function BaseTableInner>({ textOverflow={textOverflow} RowComponent={RowComponent} CellComponent={CellComponent} + renderContext={renderContext} ariaRowIndex={ ariaRowIndexingEnabled ? firstRowAriaIndex + rowIndex @@ -657,19 +769,28 @@ function BaseTableInner>({ // 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 = ( diff --git a/packages/core/src/Table/index.ts b/packages/core/src/Table/index.ts index 82d7328064c85..1e89ef45a0094 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.tsx b/packages/core/src/Table/plugins/rowIndex/useTableRowIndex.tsx index 04c9006842abe..24dc6e5c23f7b 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,21 +21,21 @@ 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 - * `
` — 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). + * Table gives each body row its position, so the plugin numbers rows without + * the data. `data` and `getRowKey` are a fallback for an index cell that + * renders outside Table's body rows. */ export interface UseTableRowIndexConfig> { - /** 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 + * The data array the table renders (after sort, filter and pagination). + * Only an index cell rendered outside Table's body rows uses it. + */ + data?: T[]; + /** + * Optional key extractor returning a **unique** string per row, for the + * `data` fallback. When provided, the fallback matches rows 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; @@ -45,6 +45,7 @@ export interface UseTableRowIndexConfig> { startFrom?: number; } +const INDEX_COLUMN_KEY = '__rowIndex'; const INDEX_COLUMN_WIDTH = {type: 'pixel' as const, value: 48}; const styles = stylex.create({ @@ -58,24 +59,27 @@ 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(); *
; * ``` */ export function useTableRowIndex>( - config: UseTableRowIndexConfig, + config: UseTableRowIndexConfig = {}, ): TablePlugin { 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 - // (stable across new object identities), otherwise by object reference. + // The fallback lookup for an index cell outside Table's body rows. Keyed by + // getRowKey when provided (stable across new object identities), otherwise + // by object reference. const lookup = useMemo(() => { + if (data == null) { + return () => undefined; + } const map = new Map(); for (let i = 0; i < data.length; i++) { const item = data[i]; @@ -85,19 +89,27 @@ export function useTableRowIndex>( 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 => ({ + return useMemo((): TablePlugin => { + // Table runs a row's cell transforms before it renders the cells, so the + // index cell's renderer finds the position its own transform stored. + const positions = new WeakMap(); + return { + rowModel: 'flat', + transformBodyCell(props, column, item, _columnIndex, _columns, context) { + if (column.key === INDEX_COLUMN_KEY && context != null) { + positions.set(item, context.logicalIndex); + } + return props; + }, transformColumns(columns) { const indexColumn: TableColumn = { - 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 = positions.get(item) ?? lookup(item); if (idx == null) { return null; } @@ -108,7 +120,6 @@ export function useTableRowIndex>( }; 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 b92dcf8fc5346..0a030c1c4be3d 100644 --- a/packages/core/src/Table/plugins/selection/useTableSelection.tsx +++ b/packages/core/src/Table/plugins/selection/useTableSelection.tsx @@ -395,6 +395,7 @@ export function useTableSelection>( return useMemo( (): TablePlugin => ({ + rowModel: 'flat', transformTableContext(children: ReactNode) { return ( diff --git a/packages/core/src/Table/plugins/stickyColumns/useTableStickyColumns.tsx b/packages/core/src/Table/plugins/stickyColumns/useTableStickyColumns.tsx index cf0428dc2e198..3fa24e03b4783 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>( return useMemo( (): TablePlugin => ({ + 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 0000000000000..426348969bacd --- /dev/null +++ b/packages/core/src/Table/tableRowContextUsage.ts @@ -0,0 +1,73 @@ +// 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'; + +const indexReadingPlugins = new WeakSet(); +const countReadingPlugins = new WeakSet(); +const trackedContexts = new WeakMap< + TableRowContext, + WeakMap +>(); + +/** Whether a transform of the plugin has read a row's `logicalIndex`. */ +export function readsRowIndex>( + plugin: TablePlugin, +): boolean { + return indexReadingPlugins.has(plugin); +} + +/** Whether a transform of the plugin has read a row count. */ +export function readsRowCount>( + plugin: TablePlugin, +): 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>( + plugin: TablePlugin, + 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() { + countReadingPlugins.add(plugin); + return context.render.logicalRowCount; + }, + }); + const tracked: TableRowContext = Object.freeze({ + ...context, + render, + get logicalIndex() { + indexReadingPlugins.add(plugin); + return context.logicalIndex; + }, + get 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 bd6b93e36c52a..9ae3e630e3162 100644 --- a/packages/core/src/Table/types.ts +++ b/packages/core/src/Table/types.ts @@ -422,6 +422,47 @@ 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 `
`. Its reference is stable. */ + readonly viewport: React.RefObject; +} + +/** Immutable facts about one body row that Table passes to its transforms. */ +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 +490,12 @@ export type TableContextActions = export interface TablePlugin< T extends Record = Record, > { + /** + * 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, @@ -476,6 +523,7 @@ export interface TablePlugin< props: BodyRowRenderProps, item: T, index: number, + context?: TableRowContext, ) => BodyRowRenderProps; /** * Transform each body `
` props. @@ -489,6 +537,7 @@ export interface TablePlugin< item: T, columnIndex: number, columns: ReadonlyArray>, + context?: TableRowContext, ) => BodyCellRenderProps; /** * Transform the scroll-wrapper region — the `
` wrapping the `` @@ -498,6 +547,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 a86796a0a861a..7f20f27f91621 100644 --- a/packages/core/src/Table/useBaseTablePlugins.ts +++ b/packages/core/src/Table/useBaseTablePlugins.ts @@ -89,6 +89,9 @@ function sortPluginEntries>( // ====================================================================== // 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>( // 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 1ea3344c8be07..7722a08e5a5a8 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. Table gives each row its position, so the plugin needs no data.', 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 fallback: the data array the table renders (post sort/filter/page). Only an index cell rendered outside the table body rows uses it.', }, { 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 for the data fallback, returning a unique string per row. When provided, the fallback matches rows 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. Table supplies each row position; no data needed.', 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 fallback data array, for an index cell outside the table body rows.', + getRowKey: 'Optional key extractor for the data fallback; otherwise items match by reference.', label: "Header label for the index column. Default '#'.", startFrom: 'First index value. Default 1.', }, From 6f787b2a9dfc775b328696f9a8df8d06803807e0 Mon Sep 17 00:00:00 2001 From: Cindy Zhang Date: Thu, 5 Nov 2026 15:47:52 -0800 Subject: [PATCH 3/5] fix(Table): a context read after the transform warns in development; docs say to read during the transform Read tracking sees only reads made while the transform runs. A callback that reads logicalIndex later can see a stale value on a memoized row, so the tracked getters warn once in development outside their plugin's transform, and TableRowContext and the body transforms say to copy values in time. The story and CLI block stop passing data to useTableRowIndex. Co-authored-by: Humberto Virtudes --- .../stories/TableRowIndex.stories.tsx | 15 ++-- .../Table/TableRowIndexTable.doc.mjs | 2 +- .../components/Table/TableRowIndexTable.tsx | 2 +- packages/core/src/Table/BaseTable.tsx | 5 +- .../core/src/Table/TableRowContext.test.tsx | 74 ++++++++++++++++++- .../plugins/rowIndex/useTableRowIndex.tsx | 5 +- .../core/src/Table/tableRowContextUsage.ts | 32 ++++++++ packages/core/src/Table/types.ts | 14 +++- 8 files changed, 129 insertions(+), 20 deletions(-) diff --git a/apps/storybook/stories/TableRowIndex.stories.tsx b/apps/storybook/stories/TableRowIndex.stories.tsx index 33cdeba17b651..37e39241b6874 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({data: tracks}); + const rowIndex = useTableRowIndex(); return (
{ const rowIndex = useTableRowIndex({ - 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(sortConfig); - // Pass the sorted data + a stable key so the index tracks the sorted order. - const rowIndex = useTableRowIndex({ - data: sortedData, - getRowKey: item => item.id, - }); + const rowIndex = useTableRowIndex(); const plugins = useMemo( () => ({rowIndex, sort: sortPlugin}), [rowIndex, sortPlugin], 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 6600d7689c871..8094d3bb69ff1 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 4297ee00d926d..2eb763755056a 100644 --- a/packages/cli/assets/templates/blocks/components/Table/TableRowIndexTable.tsx +++ b/packages/cli/assets/templates/blocks/components/Table/TableRowIndexTable.tsx @@ -33,7 +33,7 @@ const columns: TableColumn[] = [ export default function TableRowIndexTable() { // Pass the rendered data array — numbering follows its order. - const rowIndex = useTableRowIndex({data: tracks}); + const rowIndex = useTableRowIndex(); return (
- transform(props, ...values, trackRowContext(plugin, context)); + runPluginTransform(plugin, () => + transform(props, ...values, trackRowContext(plugin, context)), + ); }, initial, ...args, diff --git a/packages/core/src/Table/TableRowContext.test.tsx b/packages/core/src/Table/TableRowContext.test.tsx index fe6e8ea70f7a2..f4d6767af2c2a 100644 --- a/packages/core/src/Table/TableRowContext.test.tsx +++ b/packages/core/src/Table/TableRowContext.test.tsx @@ -1,7 +1,8 @@ // Copyright (c) Meta Platforms, Inc. and affiliates. -import {describe, it, expect, vi} from 'vitest'; -import {render, screen} from '@testing-library/react'; +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, @@ -24,6 +25,11 @@ const data: Row[] = [ const columns: TableColumn[] = [{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[] = []; @@ -209,4 +215,68 @@ describe('Table transform context (FR17, FR20)', () => { ['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 = { + 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( +
, + ); + rerender( +
, + ); + 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 = { + rowModel: 'flat', + transformBodyCell(props, _column, _item, _ci, _columns, context) { + return { + ...props, + htmlProps: { + ...props.htmlProps, + onClick: () => { + lateRead(context?.logicalIndex); + }, + }, + }; + }, + }; + render( +
, + ); + 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/plugins/rowIndex/useTableRowIndex.tsx b/packages/core/src/Table/plugins/rowIndex/useTableRowIndex.tsx index 24dc6e5c23f7b..8199ca06a147e 100644 --- a/packages/core/src/Table/plugins/rowIndex/useTableRowIndex.tsx +++ b/packages/core/src/Table/plugins/rowIndex/useTableRowIndex.tsx @@ -90,8 +90,9 @@ export function useTableRowIndex>( }, [data, getRowKey]); return useMemo((): TablePlugin => { - // Table runs a row's cell transforms before it renders the cells, so the - // index cell's renderer finds the position its own transform stored. + // 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(); return { rowModel: 'flat', diff --git a/packages/core/src/Table/tableRowContextUsage.ts b/packages/core/src/Table/tableRowContextUsage.ts index 426348969bacd..508a59fa10d8c 100644 --- a/packages/core/src/Table/tableRowContextUsage.ts +++ b/packages/core/src/Table/tableRowContextUsage.ts @@ -9,6 +9,7 @@ */ import type {TablePlugin, TableRowContext} from './types'; +import {warnOnce} from '../utils/devWarning'; const indexReadingPlugins = new WeakSet(); const countReadingPlugins = new WeakSet(); @@ -16,6 +17,34 @@ const trackedContexts = new WeakMap< TableRowContext, WeakMap >(); +let transformingPlugin: object | null = null; + +/** Run one plugin transform; context reads inside it are in time. */ +export function runPluginTransform(plugin: object, transform: () => R): R { + const outer = transformingPlugin; + transformingPlugin = plugin; + try { + return transform(); + } finally { + transformingPlugin = outer; + } +} + +/** + * A read after the transform returned (from a callback the transform made) + * is not tracked in time. A row that does not re-render keeps its old + * context, so the 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>( @@ -52,6 +81,7 @@ export function trackRowContext>( const render = Object.freeze({ ...context.render, get logicalRowCount() { + warnIfLate(plugin, 'render.logicalRowCount'); countReadingPlugins.add(plugin); return context.render.logicalRowCount; }, @@ -60,10 +90,12 @@ export function trackRowContext>( ...context, render, get logicalIndex() { + warnIfLate(plugin, 'logicalIndex'); indexReadingPlugins.add(plugin); return context.logicalIndex; }, get logicalRowCount() { + warnIfLate(plugin, 'logicalRowCount'); countReadingPlugins.add(plugin); return context.logicalRowCount; }, diff --git a/packages/core/src/Table/types.ts b/packages/core/src/Table/types.ts index 9ae3e630e3162..cfc5a0cb45e50 100644 --- a/packages/core/src/Table/types.ts +++ b/packages/core/src/Table/types.ts @@ -442,7 +442,11 @@ export interface TableRenderContext { readonly viewport: React.RefObject; } -/** Immutable facts about one body row that Table passes to its transforms. */ +/** + * 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; @@ -518,7 +522,10 @@ export interface TablePlugin< columnIndex: number, columns: ReadonlyArray>, ) => HeaderCellRenderProps; - /** Transform each body `` props */ + /** + * Transform each body `` props. Read `context` values during the + * transform, not later in a callback it returns. + */ transformBodyRow?: ( props: BodyRowRenderProps, item: T, @@ -526,7 +533,8 @@ export interface TablePlugin< context?: TableRowContext, ) => BodyRowRenderProps; /** - * Transform each body `
` props. + * Transform each body `` 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). From a485f6751726188345c2851b46be25e7da902cf1 Mon Sep 17 00:00:00 2001 From: Cindy Zhang Date: Thu, 5 Nov 2026 15:48:18 -0800 Subject: [PATCH 4/5] chore(changeset): the Table context change names @astryxdesign/cli for the numbered-rows block --- .changeset/table-row-context.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/.changeset/table-row-context.md b/.changeset/table-row-context.md index d58cc800aeac4..b0b72e360acd0 100644 --- a/.changeset/table-row-context.md +++ b/.changeset/table-row-context.md @@ -1,7 +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` now numbers rows from the context, so its `data` option is optional, and rows that move re-render only for plugins that read the index. +[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` now numbers rows from the context, so its `data` option is optional, 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 From 1f0cbd32e5830a7d4976d258bc6dc868dbd36817 Mon Sep 17 00:00:00 2001 From: Cindy Zhang Date: Thu, 5 Nov 2026 16:23:44 -0800 Subject: [PATCH 5/5] fix(useTableRowIndex): a passed data array still orders the numbers; only the no-data form uses the row context Legacy row-index configuration continues: a caller who passes data (a grouped table with its ungrouped rows, a subset view) keeps numbering from that array. useTableRowIndex() numbers from logicalIndex. Co-authored-by: Humberto Virtudes --- .changeset/table-row-context.md | 2 +- .../components/Table/TableRowIndexTable.tsx | 2 +- .../rowIndex/useTableRowIndex.test.tsx | 19 ++++++++++++ .../plugins/rowIndex/useTableRowIndex.tsx | 29 +++++++++---------- .../core/src/Table/tableRowContextUsage.ts | 6 ++-- .../core/src/Table/useTableRowIndex.doc.mjs | 12 ++++---- 6 files changed, 43 insertions(+), 27 deletions(-) diff --git a/.changeset/table-row-context.md b/.changeset/table-row-context.md index b0b72e360acd0..4a0c091045321 100644 --- a/.changeset/table-row-context.md +++ b/.changeset/table-row-context.md @@ -3,6 +3,6 @@ '@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` now numbers rows from the context, so its `data` option is optional, 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`. +[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/packages/cli/assets/templates/blocks/components/Table/TableRowIndexTable.tsx b/packages/cli/assets/templates/blocks/components/Table/TableRowIndexTable.tsx index 2eb763755056a..67a758abf3407 100644 --- a/packages/cli/assets/templates/blocks/components/Table/TableRowIndexTable.tsx +++ b/packages/cli/assets/templates/blocks/components/Table/TableRowIndexTable.tsx @@ -32,7 +32,7 @@ const columns: TableColumn[] = [ ]; export default function TableRowIndexTable() { - // Pass the rendered data array — numbering follows its order. + // Table gives each row its position, so numbering follows the rendered rows. const rowIndex = useTableRowIndex(); return ( diff --git a/packages/core/src/Table/plugins/rowIndex/useTableRowIndex.test.tsx b/packages/core/src/Table/plugins/rowIndex/useTableRowIndex.test.tsx index 5e26df3087eb9..989dca73fab29 100644 --- a/packages/core/src/Table/plugins/rowIndex/useTableRowIndex.test.tsx +++ b/packages/core/src/Table/plugins/rowIndex/useTableRowIndex.test.tsx @@ -49,6 +49,25 @@ function ContextHarness({rows = data}: {rows?: Row[]}) { } 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({data}); + return ( + + ); + } + render(); + 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(); let rows = screen.getAllByRole('row'); diff --git a/packages/core/src/Table/plugins/rowIndex/useTableRowIndex.tsx b/packages/core/src/Table/plugins/rowIndex/useTableRowIndex.tsx index 8199ca06a147e..66811bf034c07 100644 --- a/packages/core/src/Table/plugins/rowIndex/useTableRowIndex.tsx +++ b/packages/core/src/Table/plugins/rowIndex/useTableRowIndex.tsx @@ -21,22 +21,20 @@ import type {TableColumn, TablePlugin} from '../../types'; /** * Configuration for {@link useTableRowIndex}. * - * Table gives each body row its position, so the plugin numbers rows without - * the data. `data` and `getRowKey` are a fallback for an index cell that - * renders outside Table's body rows. + * 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> { /** - * The data array the table renders (after sort, filter and pagination). - * Only an index cell rendered outside Table's body rows uses it. + * 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, for the - * `data` fallback. When provided, the fallback matches rows by the returned - * string (stable across new object identities); otherwise by reference - * identity. For a stable plugin identity across renders, memoize this with - * `useCallback`. + * 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 '#' */ @@ -73,12 +71,11 @@ export function useTableRowIndex>( ): TablePlugin { const {data, getRowKey, label = '#', startFrom = 1} = config; - // The fallback lookup for an index cell outside Table's body rows. Keyed by - // getRowKey when provided (stable across new object identities), otherwise - // by object reference. + // 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 () => undefined; + return null; } const map = new Map(); for (let i = 0; i < data.length; i++) { @@ -97,7 +94,7 @@ export function useTableRowIndex>( return { rowModel: 'flat', transformBodyCell(props, column, item, _columnIndex, _columns, context) { - if (column.key === INDEX_COLUMN_KEY && context != null) { + if (lookup == null && column.key === INDEX_COLUMN_KEY && context) { positions.set(item, context.logicalIndex); } return props; @@ -110,7 +107,7 @@ export function useTableRowIndex>( align: 'end', resizable: false, renderCell: (item: T) => { - const idx = positions.get(item) ?? lookup(item); + const idx = lookup == null ? positions.get(item) : lookup(item); if (idx == null) { return null; } diff --git a/packages/core/src/Table/tableRowContextUsage.ts b/packages/core/src/Table/tableRowContextUsage.ts index 508a59fa10d8c..2618b8e54e077 100644 --- a/packages/core/src/Table/tableRowContextUsage.ts +++ b/packages/core/src/Table/tableRowContextUsage.ts @@ -31,9 +31,9 @@ export function runPluginTransform(plugin: object, transform: () => R): R { } /** - * A read after the transform returned (from a callback the transform made) - * is not tracked in time. A row that does not re-render keeps its old - * context, so the read can return a stale index or count. + * 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) { diff --git a/packages/core/src/Table/useTableRowIndex.doc.mjs b/packages/core/src/Table/useTableRowIndex.doc.mjs index 7722a08e5a5a8..2d12239edc852 100644 --- a/packages/core/src/Table/useTableRowIndex.doc.mjs +++ b/packages/core/src/Table/useTableRowIndex.doc.mjs @@ -7,19 +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 rows the table renders (reflecting the current sort / filter / pagination view) and starts at 1 by default. Table gives each row its position, so the plugin needs no data.', + '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: - 'Optional fallback: the data array the table renders (post sort/filter/page). Only an index cell rendered outside the table body rows uses it.', + '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 for the data fallback, returning a unique string per row. When provided, the fallback matches rows by the returned string; otherwise 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', @@ -39,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 rows (current sort/filter/page view), 1-based by default. Table supplies each row position; no data needed.', + '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: 'Optional fallback data array, for an index cell outside the table body rows.', - getRowKey: 'Optional key extractor for the data fallback; 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.', },