An open source design system that's fully customizable and agent ready
TypeScript
fix(Table): guard rowExpansion tree walks against cyclic data (#4070)
AKe24b07080398
diff --git a/.changeset/row-expansion-cycle-guard.md b/.changeset/row-expansion-cycle-guard.mdnew file mode 100644index 0000000000..156caad88b--- /dev/null+++ b/.changeset/row-expansion-cycle-guard.md@@ -0,0 +1,9 @@+---+'@astryxdesign/core': patch+---++[fix] Guard useTableRowExpansionState tree walks against cyclic data (#3971)++The `depthMap`, flattened `data`, and `allExpandableKeys` walks now track the ancestor keys on the current path and skip edges that point back at an ancestor, so self-referential or cyclic row data terminates instead of overflowing the stack.++@AKnassadiff --git a/packages/core/src/Table/plugins/rowExpansion/useTableRowExpansion.test.tsx b/packages/core/src/Table/plugins/rowExpansion/useTableRowExpansion.test.tsxindex 07e8b0e236..7c4b707f7f 100644--- a/packages/core/src/Table/plugins/rowExpansion/useTableRowExpansion.test.tsx+++ b/packages/core/src/Table/plugins/rowExpansion/useTableRowExpansion.test.tsx@@ -1,7 +1,7 @@// Copyright (c) Meta Platforms, Inc. and affiliates.import {describe, it, expect, vi, beforeEach} from 'vitest';-import {render, screen, fireEvent} from '@testing-library/react';+import {render, renderHook, screen, fireEvent} from '@testing-library/react';import {useState} from 'react';import {Table} from '../../Table';import type {TableColumn} from '../../types';@@ -153,3 +153,92 @@ describe('useTableRowExpansion', () => {expect(screen.queryByText('File B1')).not.toBeInTheDocument();});});++describe('useTableRowExpansionState cycle guard', () => {+ /** A row whose children array contains the row itself (plus a real child). */+ function makeSelfReferential(): TreeItem[] {+ const x: TreeItem = {id: 'x', name: 'Self', children: []};+ const y: TreeItem = {id: 'y', name: 'Leaf Y', children: []};+ x.children.push(x, y);+ return [x];+ }++ /** root -> child -> grand, where grand's children point back at root. */+ function makeDeepCycle(): TreeItem[] {+ const root: TreeItem = {id: 'root', name: 'Root', children: []};+ const child: TreeItem = {id: 'child', name: 'Child', children: []};+ const grand: TreeItem = {id: 'grand', name: 'Grand', children: []};+ root.children.push(child);+ child.children.push(grand);+ grand.children.push(root);+ return [root];+ }++ function renderState(baseData: TreeItem[], expandedKeys: Set<string>) {+ const setExpandedKeys = vi.fn();+ const hook = renderHook(() =>+ useTableRowExpansionState<TreeItem>({+ baseData,+ getChildren: item => item.children,+ getRowKey: item => item.id,+ expandedKeys,+ setExpandedKeys,+ }),+ );+ return {hook, setExpandedKeys};+ }++ it('terminates on a self-referential expanded row and flattens each key once', () => {+ const {hook} = renderState(makeSelfReferential(), new Set(['x']));+ const {data, expansionConfig} = hook.result.current;+ expect(data.map(item => item.id)).toEqual(['x', 'y']);+ expect(expansionConfig.getDepth?.(data[0])).toBe(0);+ expect(expansionConfig.getDepth?.(data[1])).toBe(1);+ });++ it('terminates on a deeper cycle back to the root and flattens each key once', () => {+ const {hook} = renderState(+ makeDeepCycle(),+ new Set(['root', 'child', 'grand']),+ );+ const {data, expansionConfig} = hook.result.current;+ expect(data.map(item => item.id)).toEqual(['root', 'child', 'grand']);+ expect(expansionConfig.getDepth?.(data[0])).toBe(0);+ expect(expansionConfig.getDepth?.(data[1])).toBe(1);+ expect(expansionConfig.getDepth?.(data[2])).toBe(2);+ // The cycle guard keeps isAllExpanded computable — true, not a crash.+ expect(expansionConfig.isAllExpanded).toBe(true);+ });++ it('terminates when collecting allExpandableKeys on cyclic data with nothing expanded', () => {+ const {hook, setExpandedKeys} = renderState(+ makeDeepCycle(),+ new Set<string>(),+ );+ const {data, expansionConfig} = hook.result.current;+ expect(data.map(item => item.id)).toEqual(['root']);+ expansionConfig.onToggleExpandAll?.(true);+ const nextKeys = setExpandedKeys.mock.calls[0][0] as Set<string>;+ expect(Array.from(nextKeys)).toEqual(['root', 'child', 'grand']);+ });++ it('re-walks a shared child under each expanded parent (ancestor-path, not visited-set, semantics)', () => {+ const leaf: TreeItem = {id: 'leaf', name: 'Leaf', children: []};+ const shared: TreeItem = {id: 's', name: 'Shared', children: [leaf]};+ const p1: TreeItem = {id: 'p1', name: 'Parent 1', children: [shared]};+ const p2: TreeItem = {id: 'p2', name: 'Parent 2', children: [shared]};+ const {hook} = renderState([p1, p2], new Set(['p1', 'p2', 's']));+ // 's' is on neither parent's ancestor path, so it must flatten under+ // both — the guard only skips true cycles, matching pre-guard behavior+ // for acyclic (DAG-shaped) data.+ const {data} = hook.result.current;+ expect(data.map(item => item.id)).toEqual([+ 'p1',+ 's',+ 'leaf',+ 'p2',+ 's',+ 'leaf',+ ]);+ });+});diff --git a/packages/core/src/Table/plugins/rowExpansion/useTableRowExpansion.tsx b/packages/core/src/Table/plugins/rowExpansion/useTableRowExpansion.tsxindex 858d4edc2e..e5ac94258b 100644--- a/packages/core/src/Table/plugins/rowExpansion/useTableRowExpansion.tsx+++ b/packages/core/src/Table/plugins/rowExpansion/useTableRowExpansion.tsx@@ -141,12 +141,19 @@ export function useTableRowExpansionState<T extends Record<string, unknown>>({const depthMap = useMemo(() => {const map = new Map<string, number>();+ // Ancestor keys on the current walk path — guards against cyclic data.+ const path = new Set<string>();function walk(items: T[], depth: number) {for (const item of items) {const key = getRowKey(item);+ if (path.has(key)) {+ continue; // cyclic edge — skip+ }map.set(key, depth);if (expandedKeys.has(key)) {+ path.add(key);walk(getChildren(item), depth + 1);+ path.delete(key);}}}@@ -156,12 +163,19 @@ export function useTableRowExpansionState<T extends Record<string, unknown>>({const data = useMemo(() => {const result: T[] = [];+ // Ancestor keys on the current walk path — guards against cyclic data.+ const path = new Set<string>();function walk(items: T[]) {for (const item of items) {- result.push(item);const key = getRowKey(item);+ if (path.has(key)) {+ continue; // cyclic edge — skip+ }+ result.push(item);if (expandedKeys.has(key)) {+ path.add(key);walk(getChildren(item));+ path.delete(key);}}}@@ -172,11 +186,19 @@ export function useTableRowExpansionState<T extends Record<string, unknown>>({// Every expandable key across the whole tree (drives expand-all).const allExpandableKeys = useMemo(() => {const keys: string[] = [];+ // Ancestor keys on the current walk path — guards against cyclic data.+ const path = new Set<string>();function walk(items: T[]) {for (const item of items) {+ const key = getRowKey(item);+ if (path.has(key)) {+ continue; // cyclic edge — skip+ }if (isExpandable(item)) {- keys.push(getRowKey(item));+ keys.push(key);+ path.add(key);walk(getChildren(item));+ path.delete(key);}}}@@ -399,7 +421,11 @@ export function useTableRowExpansion<T extends Record<string, unknown>>(<ExpansionChevronisExpanded={isExpanded}onToggle={() => onToggle(key)}- ariaLabel={isExpanded ? t('@astryx.tableRowExpansion.collapseRow') : t('@astryx.tableRowExpansion.expandRow')}+ ariaLabel={+ isExpanded+ ? t('@astryx.tableRowExpansion.collapseRow')+ : t('@astryx.tableRowExpansion.expandRow')+ }/>);},@@ -457,7 +483,11 @@ export function useTableRowExpansion<T extends Record<string, unknown>>(<ExpansionChevronisExpanded={isExpanded}onToggle={() => onToggle(key)}- ariaLabel={isExpanded ? t('@astryx.tableRowExpansion.collapseRow') : t('@astryx.tableRowExpansion.expandRow')}+ ariaLabel={+ isExpanded+ ? t('@astryx.tableRowExpansion.collapseRow')+ : t('@astryx.tableRowExpansion.expandRow')+ }/>) : (<span {...stylex.props(expansionStyles.placeholder)} />@@ -499,7 +529,9 @@ export function useTableRowExpansion<T extends Record<string, unknown>>({...stylex.props(expansionStyles.chevronButton)}onClick={() => onToggleExpandAll(!allExpanded)}aria-label={- allExpanded ? t('@astryx.tableRowExpansion.collapseAllRows') : t('@astryx.tableRowExpansion.expandAllRows')+ allExpanded+ ? t('@astryx.tableRowExpansion.collapseAllRows')+ : t('@astryx.tableRowExpansion.expandAllRows')}><span{...stylex.props(