An open source design system that's fully customizable and agent ready
TypeScript
feat(core): add useTableRowIndex plugin (#3756)
Humberto Virtudes3f8142720b1d
diff --git a/.changeset/table-row-index.md b/.changeset/table-row-index.mdnew file mode 100644index 0000000000..307a8d86cd--- /dev/null+++ b/.changeset/table-row-index.md@@ -0,0 +1,13 @@+---+'@astryxdesign/core': patch+---++[feat] Add `useTableRowIndex` — a plugin that prepends a right-aligned,+monospaced row-number column.++- Numbering follows the rendered `data` order, so it reflects the current+ sort / filter / pagination view (pass the sorted/paged array).+- `getRowKey` for stable keyed lookup; `label` and `startFrom` to customize+ the header and starting ordinal.++@humbertovirtudesdiff --git a/apps/sandbox/src/app/(sandbox)/pages/table-lab/page.tsx b/apps/sandbox/src/app/(sandbox)/pages/table-lab/page.tsxindex 39a28102c8..da943088c3 100644--- a/apps/sandbox/src/app/(sandbox)/pages/table-lab/page.tsx+++ b/apps/sandbox/src/app/(sandbox)/pages/table-lab/page.tsx@@ -48,6 +48,7 @@ import {useTableRowExpansion,useTableRowExpansionState,useTableGroupedRows,+ useTableRowIndex,} from '@astryxdesign/core/Table';import type {TablePlugin, TableSortState} from '@astryxdesign/core/Table';@@ -70,7 +71,8 @@ type PluginId =| 'columnResize'| 'stickyColumns'| 'rowExpansion'- | 'groupedRows';+ | 'groupedRows'+ | 'rowIndex';interface PluginMeta {id: PluginId;@@ -110,6 +112,11 @@ const PLUGIN_REGISTRY: PluginMeta[] = [label: 'Grouped Rows',description: 'Collapsible sections grouped by team',},+ {+ id: 'rowIndex',+ label: 'Row Index',+ description: 'Prepend a monospaced row-number column',+ },];// =============================================================================@@ -231,11 +238,20 @@ function useLabPlugins({summary.push(`${collapsedGroups.size} groups collapsed`);}+ // --- row index ---+ const rowIndexPlugin = useTableRowIndex<LabRow>({+ data: dataAfterPage,+ getRowKey: item => item.id,+ });+// Assemble enabled plugins in a stable order.const plugins: Record<string, TablePlugin<LabRow>> = {};if (enabled.groupedRows) {plugins.grouped = grouped.plugin;}+ if (enabled.rowIndex) {+ plugins.rowIndex = rowIndexPlugin;+ }if (enabled.sortable) {plugins.sort = sortPlugin;}@@ -414,6 +430,7 @@ export default function TableLabPage() {stickyColumns: false,rowExpansion: false,groupedRows: false,+ rowIndex: false,});const baseData = useMemo(() => generateRows(rowCount), [rowCount]);diff --git a/apps/storybook/stories/TableRowIndex.stories.tsx b/apps/storybook/stories/TableRowIndex.stories.tsxnew file mode 100644index 0000000000..a265ee2e87--- /dev/null+++ b/apps/storybook/stories/TableRowIndex.stories.tsx@@ -0,0 +1,130 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++import {useMemo, useState} from 'react';+import type {Meta, StoryObj} from '@storybook/react';+import {+ Table,+ useTableRowIndex,+ useTableSortable,+ useTableSortableState,+ proportional,+ pixel,+} from '@astryxdesign/core/Table';+import type {TableColumn, TableSortState} from '@astryxdesign/core/Table';++// =============================================================================+// Sample Data+// =============================================================================++interface Track extends Record<string, unknown> {+ id: string;+ title: string;+ artist: string;+ plays: number;+}++const tracks: Track[] = [+ {id: 't1', title: 'Nightfall', artist: 'Ava Chen', plays: 1820},+ {id: 't2', title: 'Ember', artist: 'Liam Park', plays: 942},+ {id: 't3', title: 'Tidal', artist: 'Zoe Vega', plays: 3310},+ {id: 't4', title: 'Cinder', artist: 'Max Ross', plays: 604},+ {id: 't5', title: 'Halcyon', artist: 'Mia Cole', plays: 2075},+];++const columns: TableColumn<Track>[] = [+ {key: 'title', header: 'Title', width: proportional(2)},+ {key: 'artist', header: 'Artist', width: proportional(2)},+ {+ key: 'plays',+ header: 'Plays',+ width: pixel(90),+ align: 'end',+ sortable: true,+ },+];++const meta: Meta = {+ title: 'Core/TableRowIndex',+ tags: ['autodocs'],+};++export default meta;+type Story = StoryObj;++/**+ * A monospaced, right-aligned row-number column is prepended to the table.+ * Numbering follows the rendered data order and starts at 1 by default.+ */+export const Default: Story = {+ render: () => {+ const rowIndex = useTableRowIndex<Track>({data: tracks});+ return (+ <Table+ data={tracks}+ columns={columns}+ idKey="id"+ hasHover+ plugins={{rowIndex}}+ />+ );+ },+};++/**+ * Customize the header `label` and the `startFrom` offset (e.g. 0-based).+ */+export const CustomLabelAndStart: Story = {+ render: () => {+ const rowIndex = useTableRowIndex<Track>({+ data: tracks,+ label: 'No.',+ startFrom: 0,+ });+ return (+ <Table+ data={tracks}+ columns={columns}+ idKey="id"+ hasHover+ plugins={{rowIndex}}+ />+ );+ },+};++/**+ * 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.+ */+export const RenumbersWithSort: Story = {+ render: () => {+ const [sort, setSort] = useState<TableSortState>([+ {sortKey: 'plays', direction: 'descending'},+ ]);+ const {sortedData, sortConfig} = useTableSortableState<Track>({+ data: tracks,+ sort,+ 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 plugins = useMemo(+ () => ({rowIndex, sort: sortPlugin}),+ [rowIndex, sortPlugin],+ );+ return (+ <Table+ data={sortedData}+ columns={columns}+ idKey="id"+ hasHover+ plugins={plugins}+ />+ );+ },+};diff --git a/packages/cli/templates/blocks/components/Table/TableRowIndexTable.doc.mjs b/packages/cli/templates/blocks/components/Table/TableRowIndexTable.doc.mjsnew file mode 100644index 0000000000..424245f6a5--- /dev/null+++ b/packages/cli/templates/blocks/components/Table/TableRowIndexTable.doc.mjs@@ -0,0 +1,14 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('../../../../../core/src/docs-types').TemplateDoc} */+export const doc = {+ type: 'block',+ exampleFor: 'useTableRowIndex',+ 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.',+ isReady: true,+ aspectRatio: 16 / 9,+ componentsUsed: ['Table'],+};diff --git a/packages/cli/templates/blocks/components/Table/TableRowIndexTable.tsx b/packages/cli/templates/blocks/components/Table/TableRowIndexTable.tsxnew file mode 100644index 0000000000..4297ee00d9--- /dev/null+++ b/packages/cli/templates/blocks/components/Table/TableRowIndexTable.tsx@@ -0,0 +1,47 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++'use client';++import {+ Table,+ useTableRowIndex,+ proportional,+ pixel,+} from '@astryxdesign/core/Table';+import type {TableColumn} from '@astryxdesign/core/Table';++interface Track extends Record<string, unknown> {+ id: string;+ title: string;+ artist: string;+ plays: number;+}++const tracks: Track[] = [+ {id: 't1', title: 'Nightfall', artist: 'Ava Chen', plays: 1820},+ {id: 't2', title: 'Ember', artist: 'Liam Park', plays: 942},+ {id: 't3', title: 'Tidal', artist: 'Zoe Vega', plays: 3310},+ {id: 't4', title: 'Cinder', artist: 'Max Ross', plays: 604},+ {id: 't5', title: 'Halcyon', artist: 'Mia Cole', plays: 2075},+];++const columns: TableColumn<Track>[] = [+ {key: 'title', header: 'Title', width: proportional(2)},+ {key: 'artist', header: 'Artist', width: proportional(2)},+ {key: 'plays', header: 'Plays', width: pixel(90), align: 'end'},+];++export default function TableRowIndexTable() {+ // Pass the rendered data array — numbering follows its order.+ const rowIndex = useTableRowIndex<Track>({data: tracks});++ return (+ <Table+ data={tracks}+ columns={columns}+ idKey="id"+ hasHover+ plugins={{rowIndex}}+ />+ );+}diff --git a/packages/core/src/Table/index.ts b/packages/core/src/Table/index.tsindex 8bd5f5e63c..b3cca024c7 100644--- a/packages/core/src/Table/index.ts+++ b/packages/core/src/Table/index.ts@@ -27,6 +27,7 @@ export {useTableColumnSettingsState} from './plugins/columnSettings';export {useTableColumnResize} from './plugins/columnResize';export {useTableStickyColumns} from './plugins/stickyColumns';export {useTableGroupedRows} from './plugins/groupedRows';+export {useTableRowIndex} from './plugins/rowIndex';export {useTableRowExpansion,useTableRowExpansionState,@@ -103,6 +104,7 @@ export type {export type {UseTableColumnResizeConfig} from './plugins/columnResize';export type {UseTableStickyColumnsConfig} from './plugins/stickyColumns';export type {UseTableRowExpansionConfig} from './plugins/rowExpansion';+export type {UseTableRowIndexConfig} from './plugins/rowIndex';export type {UseTableGroupedRowsConfig,UseTableGroupedRowsResult,diff --git a/packages/core/src/Table/plugins/rowIndex/index.ts b/packages/core/src/Table/plugins/rowIndex/index.tsnew file mode 100644index 0000000000..9727851356--- /dev/null+++ b/packages/core/src/Table/plugins/rowIndex/index.ts@@ -0,0 +1,4 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++export {useTableRowIndex} from './useTableRowIndex';+export type {UseTableRowIndexConfig} from './useTableRowIndex';diff --git a/packages/core/src/Table/plugins/rowIndex/useTableRowIndex.test.tsx b/packages/core/src/Table/plugins/rowIndex/useTableRowIndex.test.tsxnew file mode 100644index 0000000000..e91452b733--- /dev/null+++ b/packages/core/src/Table/plugins/rowIndex/useTableRowIndex.test.tsx@@ -0,0 +1,132 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++import {describe, it, expect} from 'vitest';+import {render, screen, within} from '@testing-library/react';+import {Table} from '../../Table';+import type {TableColumn} from '../../types';+import {useTableRowIndex} from './useTableRowIndex';++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'}];++function Harness({+ rows = data,+ label,+ startFrom,+ useKey = false,+}: {+ rows?: Row[];+ label?: string;+ startFrom?: number;+ useKey?: boolean;+}) {+ const rowIndex = useTableRowIndex<Row>({+ data: rows,+ label,+ startFrom,+ getRowKey: useKey ? item => item.id : undefined,+ });+ return (+ <Table data={rows} columns={columns} idKey="id" plugins={{rowIndex}} />+ );+}++describe('useTableRowIndex', () => {+ it('prepends a header cell with the default label', () => {+ render(<Harness />);+ const headers = screen.getAllByRole('columnheader');+ // First column is the index column.+ expect(within(headers[0]).getByText('#')).toBeInTheDocument();+ });++ it('numbers rows 1..n by default', () => {+ render(<Harness />);+ expect(screen.getByText('1')).toBeInTheDocument();+ expect(screen.getByText('2')).toBeInTheDocument();+ expect(screen.getByText('3')).toBeInTheDocument();+ });++ it('respects startFrom', () => {+ render(<Harness startFrom={0} />);+ expect(screen.getByText('0')).toBeInTheDocument();+ expect(screen.getByText('2')).toBeInTheDocument();+ expect(screen.queryByText('3')).not.toBeInTheDocument();+ });++ it('supports a custom label', () => {+ render(<Harness label="Row" />);+ const headers = screen.getAllByRole('columnheader');+ expect(within(headers[0]).getByText('Row')).toBeInTheDocument();+ });++ it('numbers a single row', () => {+ render(<Harness rows={[{id: 'a', name: 'Alice'}]} />);+ const rows = screen.getAllByRole('row');+ expect(within(rows[1]).getByText('1')).toBeInTheDocument();+ expect(within(rows[1]).getByText('Alice')).toBeInTheDocument();+ });++ it('renders the index header with empty data and no row numbers', () => {+ render(<Harness rows={[]} />);+ const headers = screen.getAllByRole('columnheader');+ expect(within(headers[0]).getByText('#')).toBeInTheDocument();+ // No body rows → no ordinals.+ expect(screen.queryByText('1')).not.toBeInTheDocument();+ });++ it('renumbers when the data order changes (reference path)', () => {+ const {rerender} = render(<Harness rows={data} />);+ let rows = screen.getAllByRole('row');+ // rows[0] is the header row.+ expect(within(rows[1]).getByText('Alice')).toBeInTheDocument();+ expect(within(rows[1]).getByText('1')).toBeInTheDocument();++ // Reorder: Carol, Alice, Bob (same object identities, new order).+ rerender(<Harness 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('renumbers when the data order changes (keyed path)', () => {+ // With getRowKey provided, the keyed lookup must still produce ordinals in+ // the new order. If the keyed branch were broken it would return undefined+ // and render no numbers — so this fails for the right reason.+ const {rerender} = render(<Harness rows={data} useKey />);+ let rows = screen.getAllByRole('row');+ expect(within(rows[1]).getByText('Alice')).toBeInTheDocument();+ expect(within(rows[1]).getByText('1')).toBeInTheDocument();++ rerender(<Harness rows={[data[1], data[2], data[0]]} useKey />);+ rows = screen.getAllByRole('row');+ expect(within(rows[1]).getByText('Bob')).toBeInTheDocument();+ expect(within(rows[1]).getByText('1')).toBeInTheDocument();+ expect(within(rows[3]).getByText('Alice')).toBeInTheDocument();+ expect(within(rows[3]).getByText('3')).toBeInTheDocument();+ });++ it('keyed path resolves ordinals across fresh object identities', () => {+ // Simulates a re-fetch: brand-new objects with the same ids. Keyed lookup+ // must map them correctly.+ const fresh: Row[] = [+ {id: 'a', name: 'Alice'},+ {id: 'b', name: 'Bob'},+ ];+ render(<Harness rows={fresh} useKey />);+ const rows = screen.getAllByRole('row');+ expect(within(rows[1]).getByText('1')).toBeInTheDocument();+ expect(within(rows[2]).getByText('2')).toBeInTheDocument();+ });+});diff --git a/packages/core/src/Table/plugins/rowIndex/useTableRowIndex.tsx b/packages/core/src/Table/plugins/rowIndex/useTableRowIndex.tsxnew file mode 100644index 0000000000..85651e6702--- /dev/null+++ b/packages/core/src/Table/plugins/rowIndex/useTableRowIndex.tsx@@ -0,0 +1,114 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++'use client';++/**+ * @file useTableRowIndex.tsx+ * @input React, StyleX, Table types + the rendered data array+ * @output Exports useTableRowIndex hook + config type+ * @position Row-index plugin; consumed by Table via plugins prop+ *+ * SYNC: When modified, update these files to stay in sync:+ * - /packages/core/src/Table/index.ts (exports)+ */++import {useMemo, type ReactNode} from 'react';+import * as stylex from '@stylexjs/stylex';+import {colorVars, typeScaleVars} from '../../../theme/tokens.stylex';++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).+ */+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`.+ */+ getRowKey?: (item: T) => string;+ /** Header label for the index column. @default '#' */+ label?: ReactNode;+ /** First index value. @default 1 */+ startFrom?: number;+}++const INDEX_COLUMN_WIDTH = {type: 'pixel' as const, value: 48};++const styles = stylex.create({+ index: {+ fontFamily: 'var(--font-family-code)',+ fontSize: typeScaleVars['--text-supporting-size'],+ fontVariantNumeric: 'tabular-nums',+ color: colorVars['--color-text-secondary'],+ },+});++/**+ * 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.+ *+ * @example+ * ```tsx+ * const rowIndex = useTableRowIndex({data});+ * <Table data={data} columns={columns} idKey="id" plugins={{rowIndex}} />;+ * ```+ */+export function useTableRowIndex<T extends Record<string, unknown>>(+ 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+ // (stable across new object identities), otherwise by object reference.+ const lookup = useMemo(() => {+ const map = new Map<unknown, number>();+ for (let i = 0; i < data.length; i++) {+ const item = data[i];+ map.set(getRowKey ? getRowKey(item) : item, i);+ }+ return (item: T): number | undefined =>+ 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> => ({+ transformColumns(columns) {+ const indexColumn: TableColumn<T> = {+ key: '__rowIndex',+ header: label,+ width: INDEX_COLUMN_WIDTH,+ align: 'end',+ resizable: false,+ renderCell: (item: T) => {+ const idx = lookup(item);+ if (idx == null) {+ return null;+ }+ return (+ <span {...stylex.props(styles.index)}>{idx + startFrom}</span>+ );+ },+ };+ return [indexColumn, ...columns];+ },+ }),+ [label, startFrom, lookup],+ );+}diff --git a/packages/core/src/Table/useTableRowIndex.doc.mjs b/packages/core/src/Table/useTableRowIndex.doc.mjsnew file mode 100644index 0000000000..f88e5c20df--- /dev/null+++ b/packages/core/src/Table/useTableRowIndex.doc.mjs@@ -0,0 +1,50 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('../docs-types').ComponentDoc} */++export const docs = {+ name: 'useTableRowIndex',+ 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.',+ props: [+ {+ name: 'data',+ type: 'T[]',+ description:+ 'The data array currently rendered by the table (post sort/filter/page). Numbering follows this order.',+ required: true,+ },+ {+ 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.',+ },+ {+ name: 'label',+ type: 'ReactNode',+ description: 'Header label for the index column.',+ default: "'#'",+ },+ {+ name: 'startFrom',+ type: 'number',+ description: 'First index value.',+ default: '1',+ },+ ],+};++/** @type {import('../docs-types').TranslationDoc} */+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.',+ 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.',+ label: "Header label for the index column. Default '#'.",+ startFrom: 'First index value. Default 1.',+ },+};