An open source design system that's fully customizable and agent ready
TypeScript
fix(Table): keep column settings' active keys in state (#10911)
Christopher Chedeau6c5c460d7f63
diff --git a/.changeset/table-column-settings-keys-in-state.md b/.changeset/table-column-settings-keys-in-state.mdnew file mode 100644index 0000000000..8c37b0b876--- /dev/null+++ b/.changeset/table-column-settings-keys-in-state.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[fix] Table's column settings plugin keeps its active columns in state. When the table re-renders on its own after a render React discards, such as a suspended transition, it shows the committed columns.++@vjeuxdiff --git a/packages/core/src/Table/plugins/columnSettings/useTableColumnSettings.test.tsx b/packages/core/src/Table/plugins/columnSettings/useTableColumnSettings.test.tsxindex 71e150cf69..df3952722b 100644--- a/packages/core/src/Table/plugins/columnSettings/useTableColumnSettings.test.tsx+++ b/packages/core/src/Table/plugins/columnSettings/useTableColumnSettings.test.tsx@@ -8,8 +8,8 @@*/import {describe, it, expect, vi} from 'vitest';-import {useState} from 'react';-import {render, screen} from '@testing-library/react';+import {Suspense, memo, startTransition, use, useState} from 'react';+import {act, render, screen} from '@testing-library/react';import {renderHook} from '@testing-library/react';import {Table} from '../../Table';import {@@ -18,6 +18,7 @@ import {type ColumnSettingsOption,} from './useTableColumnSettings';import {useTableColumnSettingsState} from './useTableColumnSettingsState';+import {InternationalizationProvider} from '../../../i18n/InternationalizationProvider';import type {TableColumn} from '../../types';// =============================================================================@@ -173,3 +174,72 @@ describe('integration with Table', () => {expect(headers[2]).toHaveTextContent('Email');});});++describe('after a render React discards', () => {+ it('renders the committed columns when the table re-renders on its own', async () => {+ // A transition that suspends for good: React renders it, then keeps the+ // committed tree and never commits that render.+ const forever = new Promise<never>(() => {});+ function Forever(): null {+ use(forever);+ return null;+ }+ const onChangeActiveColumnKeys = () => {};+ const Owner = memo(function Owner({+ activeKeys,+ }: {+ activeKeys: ReadonlyArray<string>;+ }) {+ const plugin = useTableColumnSettings<User>({+ columns: columnOptions,+ activeColumnKeys: activeKeys,+ onChangeActiveColumnKeys,+ });+ return (+ <Table+ data={testUsers}+ columns={allTableColumns}+ plugins={{columnSettings: plugin}}+ idKey="id"+ />+ );+ });+ function Screen({+ locale,+ activeKeys,+ isPending = false,+ }: {+ locale: string;+ activeKeys: ReadonlyArray<string>;+ isPending?: boolean;+ }) {+ return (+ <InternationalizationProvider locale={locale}>+ <Suspense fallback={null}>+ <Owner activeKeys={activeKeys} />+ {isPending ? <Forever /> : null}+ </Suspense>+ </InternationalizationProvider>+ );+ }+ const committedKeys = ['name', 'email'];+ const {rerender} = render(+ <Screen locale="en-US" activeKeys={committedKeys} />,+ );+ await act(async () => {+ startTransition(() => {+ rerender(+ <Screen locale="en-US" activeKeys={['name', 'role']} isPending />,+ );+ });+ });++ // The locale changes and the owner does not, so the table re-renders on+ // its own and applies the plugin again.+ rerender(<Screen locale="en-GB" activeKeys={committedKeys} />);++ expect(+ screen.getAllByRole('columnheader').map(header => header.textContent),+ ).toEqual(['Name', 'Email']);+ });+});diff --git a/packages/core/src/Table/plugins/columnSettings/useTableColumnSettings.tsx b/packages/core/src/Table/plugins/columnSettings/useTableColumnSettings.tsxindex 77ef60c814..08e4cc4c68 100644--- a/packages/core/src/Table/plugins/columnSettings/useTableColumnSettings.tsx+++ b/packages/core/src/Table/plugins/columnSettings/useTableColumnSettings.tsx@@ -19,7 +19,7 @@* - /packages/core/src/Table/index.ts (exports)*/-import {useMemo, useRef} from 'react';+import {useMemo, useState} from 'react';import type {TablePlugin, TableColumn} from '../../types';import type {UseTableColumnSettingsStateConfig} from './useTableColumnSettingsState';@@ -61,9 +61,8 @@ export interface ColumnSettingsOption<TColumnKey extends string = string> {** @template TColumnKey - String literal union of column keys*/-export type UseTableColumnSettingsConfig<- TColumnKey extends string = string,-> = UseTableColumnSettingsStateConfig<TColumnKey>;+export type UseTableColumnSettingsConfig<TColumnKey extends string = string> =+ UseTableColumnSettingsStateConfig<TColumnKey>;// =============================================================================// Plugin Hook@@ -87,20 +86,25 @@ export function useTableColumnSettings<T extends Record<string, unknown>,TColumnKey extends string = string,>(config: UseTableColumnSettingsConfig<TColumnKey>): TablePlugin<T> {- // Keep config in a ref so the plugin reads the latest values- // without changing plugin identity.- const configRef = useRef(config);- configRef.current = config;+ // The active keys the plugin reads, kept in state while their entries stay+ // the same. The plugin's identity follows them, and a render React discards+ // takes its update with it.+ const [activeColumnKeys, setActiveColumnKeys] = useState(+ config.activeColumnKeys,+ );+ const nextKeys = areKeysEqual(activeColumnKeys, config.activeColumnKeys)+ ? activeColumnKeys+ : config.activeColumnKeys;+ if (nextKeys !== activeColumnKeys) {+ setActiveColumnKeys(nextKeys);+ }return useMemo((): TablePlugin<T> => ({transformColumns(columns: TableColumn<T>[]): TableColumn<T>[] {- const cfg = configRef.current;- const activeSet = new Set(cfg.activeColumnKeys);+ const activeSet = new Set(nextKeys);// Build a map for ordering by activeColumnKeys position- const orderMap = new Map(- cfg.activeColumnKeys.map((key, index) => [key, index]),- );+ const orderMap = new Map(nextKeys.map((key, index) => [key, index]));return columns.filter(col => activeSet.has(col.key as TColumnKey)).sort((a, b) => {@@ -110,6 +114,15 @@ export function useTableColumnSettings<});},}),- [],+ [nextKeys],+ );+}++function areKeysEqual<TColumnKey extends string>(+ a: ReadonlyArray<TColumnKey>,+ b: ReadonlyArray<TColumnKey>,+): boolean {+ return (+ a === b || (a.length === b.length && a.every((key, i) => key === b[i])));}