An open source design system that's fully customizable and agent ready
TypeScript
fix(Table): the state hooks' latest-value refs are written at commit (#10176)
Christopher Chedeau6fc74f94a1dc
diff --git a/.changeset/table-state-hooks-committed-refs.md b/.changeset/table-state-hooks-committed-refs.mdnew file mode 100644index 0000000000..44fd88d05c--- /dev/null+++ b/.changeset/table-state-hooks-committed-refs.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[fix] `useTableSelectionState`, `useTableTreeState`, `useTableColumnSettingsState` and `useTableColumnResize` read their latest values as last committed. A render that React discards, as a suspended transition does, no longer reaches their handlers. "Select all rows" now selects the rows on screen, not those of a page still loading. A row's expand toggle, a column toggle and a keyboard resize also start from what is on screen.++@vjeuxdiff --git a/packages/core/src/Table/plugins/columnResize/useTableColumnResize.test.tsx b/packages/core/src/Table/plugins/columnResize/useTableColumnResize.test.tsxindex 694bfa4af4..8e567d9b08 100644--- a/packages/core/src/Table/plugins/columnResize/useTableColumnResize.test.tsx+++ b/packages/core/src/Table/plugins/columnResize/useTableColumnResize.test.tsx@@ -8,8 +8,8 @@*/import {describe, it, expect, vi, beforeAll} from 'vitest';-import {useState} from 'react';-import {render, screen, within, fireEvent} from '@testing-library/react';+import {Suspense, startTransition, use, useState} from 'react';+import {act, render, screen, within, fireEvent} from '@testing-library/react';import userEvent from '@testing-library/user-event';import {Table} from '../../Table';import {useTableColumnResize} from './useTableColumnResize';@@ -954,3 +954,77 @@ describe('useTableColumnResize', () => {});});});++// A render that reads this promise suspends for good.+const pending = new Promise<never>(() => {});+function Pending(): null {+ use(pending);+ return null;+}++interface ResizeState {+ columnWidths: Record<string, number>;+ onColumnResizeEnd: (updates: Record<string, number>) => void;+}++function PixelResizeTable({columnWidths, onColumnResizeEnd}: ResizeState) {+ const resize = useTableColumnResize<TestItem>({+ columnWidths,+ onColumnResizeEnd,+ columns: pixelColumns as TableColumn<Record<string, unknown>>[],+ });+ return (+ <Table+ data={testData}+ columns={pixelColumns}+ idKey="id"+ plugins={{resize}}+ />+ );+}++function ControlledResizeTable({+ isPending,+ ...state+}: ResizeState & {isPending: boolean}) {+ return (+ <Suspense fallback={null}>+ <PixelResizeTable {...state} />+ {isPending ? <Pending /> : null}+ </Suspense>+ );+}++describe('useTableColumnResize after a render React discards', () => {+ it('a keyboard resize starts from the widths on screen and reports to the committed callback', async () => {+ const committed: Record<string, number>[] = [];+ const discarded: Record<string, number>[] = [];+ const {rerender} = render(+ <ControlledResizeTable+ columnWidths={{name: 200}}+ onColumnResizeEnd={updates => committed.push(updates)}+ isPending={false}+ />,+ );+ // The next props render in a transition, then suspend for good, so React+ // keeps the committed tree and never commits that render.+ await act(async () => {+ startTransition(() => {+ rerender(+ <ControlledResizeTable+ columnWidths={{name: 300}}+ onColumnResizeEnd={updates => discarded.push(updates)}+ isPending+ />,+ );+ });+ });+ const handle = getResizeHandles()[0];+ handle.focus();++ fireEvent.keyDown(handle, {key: 'ArrowRight'});++ expect(discarded).toEqual([]);+ expect(committed).toEqual([{name: 210}]);+ });+});diff --git a/packages/core/src/Table/plugins/columnResize/useTableColumnResize.tsx b/packages/core/src/Table/plugins/columnResize/useTableColumnResize.tsxindex f86f41ec24..40f92efb91 100644--- a/packages/core/src/Table/plugins/columnResize/useTableColumnResize.tsx+++ b/packages/core/src/Table/plugins/columnResize/useTableColumnResize.tsx@@ -14,6 +14,7 @@*/import {useRef, useMemo, useCallback, useEffect, type ReactNode} from 'react';+import {useIsomorphicLayoutEffect} from '../../../hooks/useIsomorphicLayoutEffect';import * as stylex from '@stylexjs/stylex';import {colorVars} from '../../../theme/tokens.stylex';import type {@@ -787,7 +788,11 @@ export function useTableColumnResize<T extends Record<string, unknown>>(config: UseTableColumnResizeConfig,): TablePlugin<T> {const configRef = useRef(config);- configRef.current = config;+ // Syncs configRef with the committed render. A render that React discards,+ // as a suspended transition does, must not leave its config behind.+ useIsomorphicLayoutEffect(() => {+ configRef.current = config;+ });const dragStateRef = useRef<DragState | null>(null);const isDraggingRef = useRef(false);diff --git a/packages/core/src/Table/plugins/columnSettings/useTableColumnSettingsState.test.tsx b/packages/core/src/Table/plugins/columnSettings/useTableColumnSettingsState.test.tsxindex 9c6aa56254..82f492435a 100644--- a/packages/core/src/Table/plugins/columnSettings/useTableColumnSettingsState.test.tsx+++ b/packages/core/src/Table/plugins/columnSettings/useTableColumnSettingsState.test.tsx@@ -8,7 +8,9 @@*/import {describe, it, expect, vi} from 'vitest';-import {renderHook, act} from '@testing-library/react';+import {Suspense, startTransition, use} from 'react';+import {renderHook, act, render, screen} from '@testing-library/react';+import userEvent from '@testing-library/user-event';import {useTableColumnSettingsState,type UseTableColumnSettingsStateConfig,@@ -294,3 +296,72 @@ describe('useTableColumnSettingsState', () => {});});});++// A render that reads this promise suspends for good.+const pending = new Promise<never>(() => {});+function Pending(): null {+ use(pending);+ return null;+}++type PickerState = Pick<+ UseTableColumnSettingsStateConfig,+ 'activeColumnKeys' | 'onChangeActiveColumnKeys'+>;++function RoleToggle(state: PickerState) {+ const {toggleColumn} = useTableColumnSettingsState({+ columns: columnOptions,+ ...state,+ });+ return (+ <button type="button" onClick={() => toggleColumn('role')}>+ Toggle Role+ </button>+ );+}++function ColumnPicker({+ isPending,+ ...state+}: PickerState & {isPending: boolean}) {+ return (+ <Suspense fallback={null}>+ <RoleToggle {...state} />+ {isPending ? <Pending /> : null}+ </Suspense>+ );+}++describe('useTableColumnSettingsState after a render React discards', () => {+ it('a column toggle starts from the columns on screen and reports to the committed callback', async () => {+ const user = userEvent.setup();+ const committed: string[][] = [];+ const discarded: string[][] = [];+ const {rerender} = render(+ <ColumnPicker+ activeColumnKeys={['name', 'email']}+ onChangeActiveColumnKeys={keys => committed.push([...keys])}+ isPending={false}+ />,+ );+ // The next props render in a transition, then suspend for good, so React+ // keeps the committed tree and never commits that render.+ await act(async () => {+ startTransition(() => {+ rerender(+ <ColumnPicker+ activeColumnKeys={['name', 'email', 'role']}+ onChangeActiveColumnKeys={keys => discarded.push([...keys])}+ isPending+ />,+ );+ });+ });++ await user.click(screen.getByRole('button', {name: 'Toggle Role'}));++ expect(discarded).toEqual([]);+ expect(committed).toEqual([['name', 'email', 'role']]);+ });+});diff --git a/packages/core/src/Table/plugins/columnSettings/useTableColumnSettingsState.tsx b/packages/core/src/Table/plugins/columnSettings/useTableColumnSettingsState.tsxindex de98281b99..327168f21d 100644--- a/packages/core/src/Table/plugins/columnSettings/useTableColumnSettingsState.tsx+++ b/packages/core/src/Table/plugins/columnSettings/useTableColumnSettingsState.tsx@@ -20,6 +20,7 @@*/import {useCallback, useMemo, useRef} from 'react';+import {useIsomorphicLayoutEffect} from '../../../hooks/useIsomorphicLayoutEffect';import type {ColumnSettingsOption} from './useTableColumnSettings';// =============================================================================@@ -169,16 +170,18 @@ export interface UseTableColumnSettingsStateReturn<* <Table data={data} columns={allColumns} plugins={{ columnSettings: plugin }} />* ```*/-export function useTableColumnSettingsState<- TColumnKey extends string = string,->(+export function useTableColumnSettingsState<TColumnKey extends string = string>(config: UseTableColumnSettingsStateConfig<TColumnKey>,): UseTableColumnSettingsStateReturn<TColumnKey> {const {columns, activeColumnKeys} = config;// Keep config in a ref so callbacks always read the latest version.const configRef = useRef(config);- configRef.current = config;+ // Syncs configRef with the committed render. A render that React discards,+ // as a suspended transition does, must not leave its config behind.+ useIsomorphicLayoutEffect(() => {+ configRef.current = config;+ });// Build lookup sets for fast checksconst activeSet = useMemo(diff --git a/packages/core/src/Table/plugins/selection/useTableSelectionState.test.tsx b/packages/core/src/Table/plugins/selection/useTableSelectionState.test.tsxindex eb3c754056..12fe08a9ea 100644--- a/packages/core/src/Table/plugins/selection/useTableSelectionState.test.tsx+++ b/packages/core/src/Table/plugins/selection/useTableSelectionState.test.tsx@@ -8,7 +8,7 @@*/import {describe, it, expect, vi} from 'vitest';-import {useState} from 'react';+import {Suspense, startTransition, use, useState} from 'react';import {act, render, renderHook, screen} from '@testing-library/react';import userEvent from '@testing-library/user-event';import {Table} from '../../Table';@@ -449,3 +449,42 @@ describe('useTableSelectionState with filtered data', () => {expect(rows[4]).not.toHaveAttribute('aria-selected'); // Diana});});++// A render that reads this promise suspends for good.+const pending = new Promise<never>(() => {});+function Pending(): null {+ use(pending);+ return null;+}++function PagedTable({data, isPending}: {data: TestItem[]; isPending: boolean}) {+ return (+ <Suspense fallback={null}>+ <StateHelperTable data={data} />+ {isPending ? <Pending /> : null}+ </Suspense>+ );+}++describe('useTableSelectionState after a render React discards', () => {+ it('select-all selects the rows on screen, not those of a page still loading', async () => {+ const user = userEvent.setup();+ const {rerender} = render(+ <PagedTable data={testData.slice(0, 2)} isPending={false} />,+ );+ // The next props render in a transition, then suspend for good, so React+ // keeps the committed tree and never commits that render.+ await act(async () => {+ startTransition(() => {+ rerender(<PagedTable data={testData.slice(2)} isPending />);+ });+ });+ expect(screen.queryByText('Charlie')).toBeNull();++ await user.click(screen.getByLabelText('Select all rows'));++ const rows = screen.getAllByRole('row');+ expect(rows[1]).toHaveAttribute('aria-selected', 'true'); // Alice+ expect(rows[2]).toHaveAttribute('aria-selected', 'true'); // Bob+ });+});diff --git a/packages/core/src/Table/plugins/selection/useTableSelectionState.tsx b/packages/core/src/Table/plugins/selection/useTableSelectionState.tsxindex 128dfe8fe7..101ee29f28 100644--- a/packages/core/src/Table/plugins/selection/useTableSelectionState.tsx+++ b/packages/core/src/Table/plugins/selection/useTableSelectionState.tsx@@ -19,6 +19,7 @@*/import {useCallback, useMemo, useRef} from 'react';+import {useIsomorphicLayoutEffect} from '../../../hooks/useIsomorphicLayoutEffect';import type {UseTableSelectionConfig} from './useTableSelection';// =============================================================================@@ -152,10 +153,13 @@ export function useTableSelectionState<T extends Record<string, unknown>>(// Use refs to keep onSelectAll stableconst frozenSelectedIDsRef = useRef(frozenSelectedIDs);- frozenSelectedIDsRef.current = frozenSelectedIDs;-const allSelectableIDsRef = useRef(allSelectableIDs);- allSelectableIDsRef.current = allSelectableIDs;+ // Syncs the select-all refs with the committed render. A render that React+ // discards, as a suspended transition does, must not leave its rows behind.+ useIsomorphicLayoutEffect(() => {+ frozenSelectedIDsRef.current = frozenSelectedIDs;+ allSelectableIDsRef.current = allSelectableIDs;+ });const onSelectAll = useCallback(({isAllSelected}: {isAllSelected: boolean}) => {diff --git a/packages/core/src/Table/plugins/tree/useTableTreeState.test.tsx b/packages/core/src/Table/plugins/tree/useTableTreeState.test.tsxindex bfdf987de4..48b7382bde 100644--- a/packages/core/src/Table/plugins/tree/useTableTreeState.test.tsx+++ b/packages/core/src/Table/plugins/tree/useTableTreeState.test.tsx@@ -8,8 +8,14 @@*/import {describe, it, expect, vi} from 'vitest';-import {act, renderHook} from '@testing-library/react';+import {Suspense, startTransition, use} from 'react';+import {act, render, renderHook, screen, within} from '@testing-library/react';+import userEvent from '@testing-library/user-event';+import {Table} from '../../Table';+import type {TableColumn} from '../../types';+import {useTableTreeData} from './useTableTreeData';import {useTableTreeState} from './useTableTreeState';+import type {UseTableTreeStateConfig} from './useTableTreeState';// =============================================================================// Test Data@@ -738,3 +744,84 @@ describe('useTableTreeState: isAllExpanded', () => {expect(result.current.treeConfig.isAllExpanded).toBe(false);});});++// A render that reads this promise suspends for good.+const pending = new Promise<never>(() => {});+function Pending(): null {+ use(pending);+ return null;+}++const nameColumn: TableColumn<FileRow>[] = [{key: 'name', header: 'Name'}];++type FileTreeState = Pick<+ UseTableTreeStateConfig<FileRow>,+ 'expandedIds' | 'onExpandedIdsChange'+>;++function FileTree(state: FileTreeState) {+ const {visibleData, treeConfig} = useTableTreeState<FileRow>({+ data: fileTree,+ idKey: 'id',+ ...state,+ });+ const tree = useTableTreeData(treeConfig);+ return (+ <Table+ data={visibleData}+ columns={nameColumn}+ idKey="id"+ plugins={{tree}}+ />+ );+}++function FileTable({+ isPending,+ ...state+}: FileTreeState & {isPending: boolean}) {+ return (+ <Suspense fallback={null}>+ <FileTree {...state} />+ {isPending ? <Pending /> : null}+ </Suspense>+ );+}++describe('useTableTreeState after a render React discards', () => {+ it('a row toggle starts from the rows on screen and reports to the committed callback', async () => {+ const user = userEvent.setup();+ const committed: string[][] = [];+ const discarded: string[][] = [];+ const {rerender} = render(+ <FileTable+ expandedIds={new Set()}+ onExpandedIdsChange={next => committed.push([...next])}+ isPending={false}+ />,+ );+ // The next props render in a transition, then suspend for good, so React+ // keeps the committed tree and never commits that render.+ await act(async () => {+ startTransition(() => {+ rerender(+ <FileTable+ expandedIds={new Set(['src'])}+ onExpandedIdsChange={next => discarded.push([...next])}+ isPending+ />,+ );+ });+ });+ const srcRow = screen+ .getAllByRole('row')+ .find(row => within(row).queryByText('src') != null);++ await user.click(+ within(srcRow as HTMLElement).getByRole('button', {name: 'Expand row'}),+ );++ expect(discarded).toEqual([]);+ expect(committed).toEqual([['src']]);+ });+});diff --git a/packages/core/src/Table/plugins/tree/useTableTreeState.tsx b/packages/core/src/Table/plugins/tree/useTableTreeState.tsxindex 797eed925d..f8ef086bcf 100644--- a/packages/core/src/Table/plugins/tree/useTableTreeState.tsx+++ b/packages/core/src/Table/plugins/tree/useTableTreeState.tsx@@ -17,6 +17,7 @@*/import {useCallback, useMemo, useRef, useState} from 'react';+import {useIsomorphicLayoutEffect} from '../../../hooks/useIsomorphicLayoutEffect';import type {TableTreeRowMeta,UseTableTreeDataConfig,@@ -139,16 +140,21 @@ export function useTableTreeState<T extends Record<string, unknown>>(// Stable refs so callbacks don't churn on inline-prop identity changesconst expandedIdsRef = useRef(expandedIds);- expandedIdsRef.current = expandedIds;const onExpandedIdsChangeRef = useRef(onExpandedIdsChange);- onExpandedIdsChangeRef.current = onExpandedIdsChange;+ // Syncs the refs with the committed render. A render that React discards,+ // as a suspended transition does, must not leave its rows or callback+ // behind.+ useIsomorphicLayoutEffect(() => {+ expandedIdsRef.current = expandedIds;+ onExpandedIdsChangeRef.current = onExpandedIdsChange;+ });const commitExpandedIds = useCallback((next: ReadonlySet<string>) => {// Advance the ref immediately so a second commit in the same React// batch (e.g. two onToggleItem calls in one event handler) builds// on this one instead of the pre-batch set. The ref re-syncs from- // the resolved state on the next render either way.+ // the resolved state at the next commit either way.expandedIdsRef.current = next;if (!isControlled) {setInternalExpandedIds(next);