Skip to content

An open source design system that's fully customizable and agent ready

TypeScript

feat(table): tree data plugin — useTableTreeState + useTableTreeData (#3789)

AK9da0792516e4
diff --git a/apps/storybook/stories/TableTree.stories.tsx b/apps/storybook/stories/TableTree.stories.tsx
new file mode 100644
index 0000000000..065ec54587
--- /dev/null
+++ b/apps/storybook/stories/TableTree.stories.tsx
@@ -0,0 +1,449 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+import {useState} from 'react';
+import type {Meta, StoryObj} from '@storybook/react';
+import {
+ Table,
+ useTableTreeData,
+ useTableTreeState,
+ useTableSelection,
+ useTableSelectionState,
+ useTableSortable,
+ useTableSortableState,
+ pixel,
+ proportional,
+} from '@astryxdesign/core/Table';
+import type {TableColumn} from '@astryxdesign/core/Table';
+
+// =============================================================================
+// Sample Data — an org chart (hierarchical records with columns)
+// =============================================================================
+
+interface OrgRow extends Record<string, unknown> {
+ id: string;
+ name: string;
+ title: string;
+ team: string;
+ headcount: number;
+ children?: OrgRow[];
+}
+
+const orgChart: OrgRow[] = [
+ {
+ id: 'eng',
+ name: 'Engineering',
+ title: 'VP Engineering',
+ team: 'Engineering',
+ headcount: 48,
+ children: [
+ {
+ id: 'eng-platform',
+ name: 'Platform',
+ title: 'Director',
+ team: 'Engineering',
+ headcount: 22,
+ children: [
+ {
+ id: 'eng-platform-core',
+ name: 'Core Services',
+ title: 'Manager',
+ team: 'Platform',
+ headcount: 12,
+ children: [
+ {
+ id: 'eng-platform-core-api',
+ name: 'API Gateway',
+ title: 'Tech Lead',
+ team: 'Core Services',
+ headcount: 5,
+ },
+ {
+ id: 'eng-platform-core-data',
+ name: 'Data Pipeline',
+ title: 'Tech Lead',
+ team: 'Core Services',
+ headcount: 7,
+ },
+ ],
+ },
+ {
+ id: 'eng-platform-infra',
+ name: 'Infrastructure',
+ title: 'Manager',
+ team: 'Platform',
+ headcount: 10,
+ },
+ ],
+ },
+ {
+ id: 'eng-product',
+ name: 'Product Engineering',
+ title: 'Director',
+ team: 'Engineering',
+ headcount: 26,
+ children: [
+ {
+ id: 'eng-product-web',
+ name: 'Web',
+ title: 'Manager',
+ team: 'Product Engineering',
+ headcount: 14,
+ },
+ {
+ id: 'eng-product-mobile',
+ name: 'Mobile',
+ title: 'Manager',
+ team: 'Product Engineering',
+ headcount: 12,
+ },
+ ],
+ },
+ ],
+ },
+ {
+ id: 'design',
+ name: 'Design',
+ title: 'VP Design',
+ team: 'Design',
+ headcount: 11,
+ children: [
+ {
+ id: 'design-systems',
+ name: 'Design Systems',
+ title: 'Manager',
+ team: 'Design',
+ headcount: 4,
+ },
+ {
+ id: 'design-research',
+ name: 'Research',
+ title: 'Manager',
+ team: 'Design',
+ headcount: 7,
+ },
+ ],
+ },
+ {
+ id: 'ops',
+ name: 'Operations',
+ title: 'VP Operations',
+ team: 'Operations',
+ headcount: 6,
+ },
+];
+
+const columns: TableColumn<OrgRow>[] = [
+ {key: 'name', header: 'Group', width: proportional(2)},
+ {key: 'title', header: 'Lead', width: proportional(1)},
+ {key: 'team', header: 'Parent team', width: proportional(1)},
+ {key: 'headcount', header: 'Headcount', width: pixel(110), align: 'end'},
+];
+
+const sortableColumns: TableColumn<OrgRow>[] = columns.map(col =>
+ col.key === 'name' || col.key === 'headcount'
+ ? {...col, sortable: true, sortKey: col.key}
+ : col,
+);
+
+// =============================================================================
+// Stories
+// =============================================================================
+
+const meta: Meta = {
+ title: 'Core/TableTree',
+ tags: ['autodocs'],
+};
+
+export default meta;
+type Story = StoryObj;
+
+/**
+ * Hierarchical records rendered as a table. `useTableTreeState` flattens the
+ * nested data into the visible rows and owns the expanded set;
+ * `useTableTreeData` draws the indent + expander in the first column.
+ *
+ * Collapsed branches are unmounted, not hidden — the `<tbody>` holds exactly
+ * the visible rows.
+ */
+export const Default: Story = {
+ render: () => {
+ const {visibleData, treeConfig} = useTableTreeState<OrgRow>({
+ data: orgChart,
+ idKey: 'id',
+ defaultExpandedIds: ['eng'],
+ });
+ const tree = useTableTreeData(treeConfig);
+
+ return (
+ <Table
+ data={visibleData}
+ columns={columns}
+ idKey="id"
+ hasHover
+ plugins={{tree}}
+ />
+ );
+ },
+};
+
+/**
+ * `expandAll` / `collapseAll` from the state hook, driving a deep hierarchy.
+ * Indentation is `calc(level * token)` — there is no depth cap.
+ */
+export const ExpandAndCollapseAll: Story = {
+ render: () => {
+ const {visibleData, treeConfig, expandAll, collapseAll} =
+ useTableTreeState<OrgRow>({
+ data: orgChart,
+ idKey: 'id',
+ defaultExpandedIds: ['eng', 'eng-platform', 'eng-platform-core'],
+ });
+ const tree = useTableTreeData(treeConfig);
+
+ return (
+ <div style={{display: 'flex', flexDirection: 'column', gap: 12}}>
+ <div style={{display: 'flex', gap: 8}}>
+ <button type="button" onClick={expandAll}>
+ Expand all
+ </button>
+ <button type="button" onClick={collapseAll}>
+ Collapse all
+ </button>
+ </div>
+ <Table
+ data={visibleData}
+ columns={columns}
+ idKey="id"
+ hasHover
+ plugins={{tree}}
+ />
+ </div>
+ );
+ },
+};
+
+/**
+ * The `indent` token controls the step per level: `sm` (spacing-3), `md`
+ * (spacing-4, the default), and `lg` (spacing-6).
+ */
+export const IndentSizes: Story = {
+ render: () => {
+ const indents = ['sm', 'md', 'lg'] as const;
+
+ return (
+ <div style={{display: 'flex', flexDirection: 'column', gap: 32}}>
+ {indents.map(indent => (
+ <IndentExample key={indent} indent={indent} />
+ ))}
+ </div>
+ );
+ },
+};
+
+function IndentExample({indent}: {indent: 'sm' | 'md' | 'lg'}) {
+ const {visibleData, treeConfig} = useTableTreeState<OrgRow>({
+ data: orgChart,
+ idKey: 'id',
+ indent,
+ defaultExpandedIds: ['eng', 'eng-platform', 'eng-platform-core'],
+ });
+ const tree = useTableTreeData(treeConfig);
+
+ return (
+ <div>
+ <p style={{marginBlockEnd: 8, fontWeight: 600}}>
+ indent=&quot;{indent}&quot;
+ </p>
+ <Table data={visibleData} columns={columns} idKey="id" plugins={{tree}} />
+ </div>
+ );
+}
+
+/**
+ * Composed with selection. The canonical plugin order puts `tree` before
+ * `selection`, so the checkbox column lands to the left of the indented
+ * tree column, and selection operates on the visible (flattened) rows.
+ */
+export const WithSelection: Story = {
+ render: () => {
+ const [selectedKeys, setSelectedKeys] = useState<Set<string>>(
+ () => new Set(['design-systems']),
+ );
+
+ const {visibleData, treeConfig} = useTableTreeState<OrgRow>({
+ data: orgChart,
+ idKey: 'id',
+ defaultExpandedIds: ['eng', 'design'],
+ });
+
+ const {selectionConfig} = useTableSelectionState<OrgRow>({
+ data: visibleData,
+ idKey: 'id',
+ selectedKeys,
+ setSelectedKeys,
+ });
+
+ const tree = useTableTreeData(treeConfig);
+ const selection = useTableSelection(selectionConfig);
+
+ return (
+ <Table
+ data={visibleData}
+ columns={columns}
+ idKey="id"
+ hasHover
+ plugins={{tree, selection}}
+ />
+ );
+ },
+};
+
+/**
+ * Composed with sorting. `applySort` is passed as `sortSiblings`, so each
+ * sibling group sorts independently — children always stay directly under
+ * their parent and levels never interleave. Sort by Group or Headcount.
+ */
+export const WithSiblingSorting: Story = {
+ render: () => {
+ const {sortConfig, applySort} = useTableSortableState<OrgRow>({
+ data: orgChart,
+ defaultSort: [{sortKey: 'headcount', direction: 'descending'}],
+ });
+
+ const {visibleData, treeConfig} = useTableTreeState<OrgRow>({
+ data: orgChart,
+ idKey: 'id',
+ defaultExpandedIds: ['eng', 'eng-platform'],
+ sortSiblings: applySort,
+ });
+
+ const tree = useTableTreeData(treeConfig);
+ // T can't be inferred from the sort config (it only carries the sort key).
+ const sort = useTableSortable<OrgRow>(sortConfig);
+
+ return (
+ <Table
+ data={visibleData}
+ columns={sortableColumns}
+ idKey="id"
+ hasHover
+ plugins={{sort, tree}}
+ />
+ );
+ },
+};
+
+/**
+ * Lazy loading. `isItemExpandable` shows an expander before the children
+ * exist; `onExpandedIdsChange` triggers the fetch, and the rows appear when
+ * the data arrives.
+ */
+export const LazyLoadedChildren: Story = {
+ render: () => {
+ const [data, setData] = useState<OrgRow[]>([
+ {
+ id: 'remote',
+ name: 'Remote team',
+ title: 'Director',
+ team: '—',
+ headcount: 9,
+ },
+ ]);
+ const [loadingIds, setLoadingIds] = useState<Set<string>>(() => new Set());
+
+ const {visibleData, treeConfig} = useTableTreeState<OrgRow>({
+ data,
+ idKey: 'id',
+ // Expandable before children exist.
+ isItemExpandable: item => item.id === 'remote',
+ onExpandedIdsChange: ids => {
+ if (!ids.has('remote') || data[0].children) {
+ return;
+ }
+ setLoadingIds(new Set(['remote']));
+ window.setTimeout(() => {
+ setData([
+ {
+ ...data[0],
+ children: [
+ {
+ id: 'remote-emea',
+ name: 'EMEA',
+ title: 'Manager',
+ team: 'Remote team',
+ headcount: 5,
+ },
+ {
+ id: 'remote-apac',
+ name: 'APAC',
+ title: 'Manager',
+ team: 'Remote team',
+ headcount: 4,
+ },
+ ],
+ },
+ ]);
+ setLoadingIds(new Set());
+ }, 600);
+ },
+ });
+
+ const tree = useTableTreeData(treeConfig);
+
+ return (
+ <div style={{display: 'flex', flexDirection: 'column', gap: 8}}>
+ <Table
+ data={visibleData}
+ columns={columns}
+ idKey="id"
+ hasHover
+ plugins={{tree}}
+ />
+ {loadingIds.size > 0 && <p>Loading children…</p>}
+ </div>
+ );
+ },
+};
+
+/**
+ * Migration case: the same plugin on flat data (no `children` anywhere) is a
+ * no-op — no expanders, no indent spacers, no tree ARIA. Adopting the plugin
+ * before the data becomes hierarchical changes nothing.
+ */
+export const FlatDataIsANoOp: Story = {
+ render: () => {
+ const flat: OrgRow[] = [
+ {
+ id: 'a',
+ name: 'Engineering',
+ title: 'VP Engineering',
+ team: '—',
+ headcount: 48,
+ },
+ {id: 'b', name: 'Design', title: 'VP Design', team: '—', headcount: 11},
+ {
+ id: 'c',
+ name: 'Operations',
+ title: 'VP Operations',
+ team: '—',
+ headcount: 6,
+ },
+ ];
+
+ const {visibleData, treeConfig} = useTableTreeState<OrgRow>({
+ data: flat,
+ idKey: 'id',
+ });
+ const tree = useTableTreeData(treeConfig);
+
+ return (
+ <Table
+ data={visibleData}
+ columns={columns}
+ idKey="id"
+ hasHover
+ plugins={{tree}}
+ />
+ );
+ },
+};
diff --git a/packages/core/src/Table/Table.doc.mjs b/packages/core/src/Table/Table.doc.mjs
index f98c7a64c3..0e67708ef6 100644
--- a/packages/core/src/Table/Table.doc.mjs
+++ b/packages/core/src/Table/Table.doc.mjs
@@ -111,6 +111,8 @@ export const docs = {
{name: 'useTableSelection'},
{name: 'useTableSelectionState'},
{name: 'useTableSortable'},
+ {name: 'useTableTreeData'},
+ {name: 'useTableTreeState'},
{name: 'useTablePagination'},
{name: 'useTableColumnSettings'},
{name: 'useTableFiltering'},
diff --git a/packages/core/src/Table/index.ts b/packages/core/src/Table/index.ts
index b3cca024c7..62956d41ab 100644
--- a/packages/core/src/Table/index.ts
+++ b/packages/core/src/Table/index.ts
@@ -32,6 +32,7 @@ export {
useTableRowExpansion,
useTableRowExpansionState,
} from './plugins/rowExpansion';
+export {useTableTreeData, useTableTreeState} from './plugins/tree';
export {resolveContextActions} from './tableContextMenu';
export {
useTableFiltering,
@@ -109,6 +110,12 @@ export type {
UseTableGroupedRowsConfig,
UseTableGroupedRowsResult,
} from './plugins/groupedRows';
+export type {
+ TableTreeRowMeta,
+ UseTableTreeDataConfig,
+ UseTableTreeStateConfig,
+ UseTableTreeStateResult,
+} from './plugins/tree';
export type {
UseTableFilteringConfig,
TableFilterState,
diff --git a/packages/core/src/Table/plugins/tree/index.ts b/packages/core/src/Table/plugins/tree/index.ts
new file mode 100644
index 0000000000..ea0c851d85
--- /dev/null
+++ b/packages/core/src/Table/plugins/tree/index.ts
@@ -0,0 +1,12 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+export {useTableTreeData} from './useTableTreeData';
+export type {
+ TableTreeRowMeta,
+ UseTableTreeDataConfig,
+} from './useTableTreeData';
+export {useTableTreeState} from './useTableTreeState';
+export type {
+ UseTableTreeStateConfig,
+ UseTableTreeStateResult,
+} from './useTableTreeState';
diff --git a/packages/core/src/Table/plugins/tree/useTableTreeData-perf.test.tsx b/packages/core/src/Table/plugins/tree/useTableTreeData-perf.test.tsx
new file mode 100644
index 0000000000..9cea04ff94
--- /dev/null
+++ b/packages/core/src/Table/plugins/tree/useTableTreeData-perf.test.tsx
@@ -0,0 +1,163 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file useTableTreeData-perf.test.tsx
+ * @input Table, useTableTreeData, useTableTreeState, React testing utilities
+ * @output Performance tests for tree plugin render behavior
+ * @position Test file; validates toggle render efficiency and DOM cost
+ *
+ * The tree plugin uses an external store so a toggle re-renders only the
+ * affected cells — not the whole table body. Note: expanding inserts rows,
+ * which shifts the rowIndex of every row *after* the insertion point (the
+ * row memo comparator includes rowIndex by design), so the guarantee is
+ * scoped to rows before the toggled row.
+ */
+
+import {describe, it, expect} from 'vitest';
+import {render, screen, act} from '@testing-library/react';
+import {useMemo} from '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';
+
+interface TreeRow extends Record<string, unknown> {
+ id: string;
+ name: string;
+ children?: TreeRow[];
+}
+
+/** 5 roots; the last root has 2 children. */
+const roots: TreeRow[] = [
+ ...Array.from({length: 4}, (_, i) => ({
+ id: `root-${i}`,
+ name: `Root ${i}`,
+ })),
+ {
+ id: 'root-4',
+ name: 'Root 4',
+ children: [
+ {id: 'child-0', name: 'Child 0'},
+ {id: 'child-1', name: 'Child 1'},
+ ],
+ },
+];
+
+function TreeRenderCountTable({
+ renderCounts,
+}: {
+ renderCounts: Record<string, number>;
+}) {
+ const columns = useMemo<TableColumn<TreeRow>[]>(
+ () => [
+ {
+ key: 'name',
+ header: 'Name',
+ renderCell: (item: TreeRow) => {
+ renderCounts[item.id] = (renderCounts[item.id] ?? 0) + 1;
+ return item.name;
+ },
+ },
+ ],
+ [renderCounts],
+ );
+
+ const {visibleData, treeConfig} = useTableTreeState<TreeRow>({
+ data: roots,
+ idKey: 'id',
+ });
+ const tree = useTableTreeData(treeConfig);
+
+ return (
+ <Table data={visibleData} columns={columns} idKey="id" plugins={{tree}} />
+ );
+}
+
+describe('Tree plugin render performance', () => {
+ it('expanding the last root does not re-render preceding rows', async () => {
+ const user = userEvent.setup();
+ const renderCounts: Record<string, number> = {};
+
+ render(<TreeRenderCountTable renderCounts={renderCounts} />);
+
+ const initialCounts = {...renderCounts};
+ expect(Object.keys(initialCounts)).toHaveLength(5);
+
+ await act(async () => {
+ await user.click(screen.getByRole('button', {name: 'Expand row'}));
+ });
+
+ for (let i = 0; i < 4; i++) {
+ expect(renderCounts[`root-${i}`]).toBe(initialCounts[`root-${i}`]);
+ }
+ // The children mounted exactly once.
+ expect(renderCounts['child-0']).toBe(1);
+ expect(renderCounts['child-1']).toBe(1);
+ });
+
+ it('collapsing unmounts the subtree rows entirely', async () => {
+ const user = userEvent.setup();
+ const renderCounts: Record<string, number> = {};
+
+ render(<TreeRenderCountTable renderCounts={renderCounts} />);
+
+ await act(async () => {
+ await user.click(screen.getByRole('button', {name: 'Expand row'}));
+ });
+ expect(screen.getAllByRole('row')).toHaveLength(8); // header + 5 roots + 2 children
+
+ await act(async () => {
+ await user.click(screen.getByRole('button', {name: 'Collapse row'}));
+ });
+ expect(screen.getAllByRole('row')).toHaveLength(6); // header + 5 roots
+ });
+
+ it('adds at most one wrapper, one expander/spacer to the tree column and zero DOM to other columns', () => {
+ const {container} = render(
+ <Table
+ data={
+ [{id: 'a', name: 'a', children: [{id: 'b', name: 'b'}]}] as TreeRow[]
+ }
+ columns={[
+ {key: 'name', header: 'Name'},
+ {key: 'id', header: 'Id'},
+ ]}
+ idKey="id"
+ plugins={{}}
+ />,
+ );
+ const plainSecondCellHTML =
+ container.querySelectorAll('tbody td')[1].innerHTML;
+
+ function DomBudgetTable() {
+ const {visibleData, treeConfig} = useTableTreeState<TreeRow>({
+ data: [{id: 'a', name: 'a', children: [{id: 'b', name: 'b'}]}],
+ idKey: 'id',
+ });
+ const tree = useTableTreeData(treeConfig);
+ return (
+ <Table
+ data={visibleData}
+ columns={[
+ {key: 'name', header: 'Name'},
+ {key: 'id', header: 'Id'},
+ ]}
+ idKey="id"
+ plugins={{tree}}
+ />
+ );
+ }
+ const {container: treeContainer} = render(<DomBudgetTable />);
+ const cells = treeContainer.querySelectorAll('tbody td');
+
+ // Tree column: one flex wrapper containing one expander button + text.
+ const wrapper = cells[0].firstElementChild as HTMLElement;
+ expect(wrapper.tagName).toBe('DIV');
+ expect(wrapper.children).toHaveLength(1);
+ expect(wrapper.querySelector('button')).not.toBeNull();
+
+ // Other columns: byte-identical to the plugin-free render.
+ expect(cells[1].innerHTML).toBe(plainSecondCellHTML);
+ });
+});
diff --git a/packages/core/src/Table/plugins/tree/useTableTreeData.test.tsx b/packages/core/src/Table/plugins/tree/useTableTreeData.test.tsx
new file mode 100644
index 0000000000..c3dccc4bb8
--- /dev/null
+++ b/packages/core/src/Table/plugins/tree/useTableTreeData.test.tsx
@@ -0,0 +1,594 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file useTableTreeData.test.tsx
+ * @input Uses vitest, @testing-library/react, Table components
+ * @output Unit tests for the useTableTreeData plugin
+ * @position Testing; validates tree column decoration, expander behavior,
+ * row ARIA, and the flat-data migration no-op
+ */
+
+import {describe, it, expect, vi} from 'vitest';
+import {render, screen, within} from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+import {useState} from 'react';
+import {Table} from '../../Table';
+import type {TableColumn} from '../../types';
+import {useTableSelection, useTableSelectionState} from '../selection';
+import {useTableSortableState} from '../sortable';
+import {useTableTreeData} from './useTableTreeData';
+import {useTableTreeState} from './useTableTreeState';
+import type {UseTableTreeStateConfig} from './useTableTreeState';
+
+// =============================================================================
+// Test Data
+// =============================================================================
+
+interface FileRow extends Record<string, unknown> {
+ id: string;
+ name: string;
+ size: number;
+ children?: FileRow[];
+}
+
+const fileTree: FileRow[] = [
+ {
+ id: 'src',
+ name: 'src',
+ size: 0,
+ children: [
+ {
+ id: 'components',
+ name: 'components',
+ size: 0,
+ children: [{id: 'button', name: 'Button.tsx', size: 120}],
+ },
+ {id: 'utils', name: 'utils.ts', size: 40},
+ ],
+ },
+ {id: 'readme', name: 'README.md', size: 10},
+];
+
+const columns: TableColumn<FileRow>[] = [
+ {key: 'name', header: 'Name'},
+ {key: 'size', header: 'Size'},
+];
+
+function TreeTable(
+ props: Partial<UseTableTreeStateConfig<FileRow>> & {data?: FileRow[]},
+) {
+ const {visibleData, treeConfig} = useTableTreeState<FileRow>({
+ data: props.data ?? fileTree,
+ idKey: 'id',
+ ...props,
+ });
+ const tree = useTableTreeData(treeConfig);
+
+ return (
+ <Table data={visibleData} columns={columns} idKey="id" plugins={{tree}} />
+ );
+}
+
+/** All body rows (skips the header row). */
+function getBodyRows(): HTMLElement[] {
+ return screen.getAllByRole('row').slice(1);
+}
+
+function getRowByText(text: string): HTMLElement {
+ const row = getBodyRows().find(r => within(r).queryByText(text));
+ if (!row) {
+ throw new Error(`no row containing "${text}"`);
+ }
+ return row;
+}
+
+// =============================================================================
+// Expander button
+// =============================================================================
+
+describe('useTableTreeData — expander', () => {
+ it('renders an "Expand row" button on collapsed expandable rows only', () => {
+ render(<TreeTable />);
+
+ const srcRow = getRowByText('src');
+ expect(
+ within(srcRow).getByRole('button', {name: 'Expand row'}),
+ ).toBeInTheDocument();
+
+ const readmeRow = getRowByText('README.md');
+ expect(within(readmeRow).queryByRole('button')).toBeNull();
+ });
+
+ it('expands children on click and relabels the button "Collapse row"', async () => {
+ const user = userEvent.setup();
+ render(<TreeTable />);
+
+ expect(screen.queryByText('components')).toBeNull();
+
+ await user.click(
+ within(getRowByText('src')).getByRole('button', {name: 'Expand row'}),
+ );
+
+ expect(screen.getByText('components')).toBeInTheDocument();
+ expect(screen.getByText('utils.ts')).toBeInTheDocument();
+ expect(
+ within(getRowByText('src')).getByRole('button', {name: 'Collapse row'}),
+ ).toBeInTheDocument();
+ });
+
+ it('collapses an expanded row on click, unmounting the subtree', async () => {
+ const user = userEvent.setup();
+ render(<TreeTable defaultExpandedIds={['src', 'components']} />);
+
+ expect(screen.getByText('Button.tsx')).toBeInTheDocument();
+
+ await user.click(
+ within(getRowByText('src')).getByRole('button', {name: 'Collapse row'}),
+ );
+
+ expect(screen.queryByText('components')).toBeNull();
+ expect(screen.queryByText('Button.tsx')).toBeNull();
+ // Unmounted, not hidden: only roots + header remain.
+ expect(screen.getAllByRole('row')).toHaveLength(3);
+ });
+
+ it('sets aria-expanded on the expander button', async () => {
+ const user = userEvent.setup();
+ render(<TreeTable />);
+
+ const button = within(getRowByText('src')).getByRole('button', {
+ name: 'Expand row',
+ });
+ expect(button).toHaveAttribute('aria-expanded', 'false');
+
+ await user.click(button);
+
+ expect(
+ within(getRowByText('src')).getByRole('button', {name: 'Collapse row'}),
+ ).toHaveAttribute('aria-expanded', 'true');
+ });
+});
+
+// =============================================================================
+// Row ARIA
+// =============================================================================
+
+describe('useTableTreeData — row ARIA', () => {
+ it('sets 1-based aria-level on every body row', () => {
+ render(<TreeTable defaultExpandedIds={['src', 'components']} />);
+
+ expect(getRowByText('src')).toHaveAttribute('aria-level', '1');
+ expect(getRowByText('components')).toHaveAttribute('aria-level', '2');
+ expect(getRowByText('Button.tsx')).toHaveAttribute('aria-level', '3');
+ expect(getRowByText('README.md')).toHaveAttribute('aria-level', '1');
+ });
+
+ it('sets aria-expanded on expandable rows and omits it on leaves', () => {
+ render(<TreeTable defaultExpandedIds={['src']} />);
+
+ expect(getRowByText('src')).toHaveAttribute('aria-expanded', 'true');
+ expect(getRowByText('components')).toHaveAttribute(
+ 'aria-expanded',
+ 'false',
+ );
+ expect(getRowByText('utils.ts')).not.toHaveAttribute('aria-expanded');
+ expect(getRowByText('README.md')).not.toHaveAttribute('aria-expanded');
+ });
+});
+
+// =============================================================================
+// Migration no-op (flat data)
+// =============================================================================
+
+describe('useTableTreeData — flat data is a no-op', () => {
+ const flat: FileRow[] = [
+ {id: 'a', name: 'alpha', size: 1},
+ {id: 'b', name: 'beta', size: 2},
+ ];
+
+ it('renders no expanders, spacers, or tree ARIA for flat data', () => {
+ render(<TreeTable data={flat} />);
+
+ expect(screen.queryByRole('button')).toBeNull();
+ for (const row of getBodyRows()) {
+ expect(row).not.toHaveAttribute('aria-level');
+ expect(row).not.toHaveAttribute('aria-expanded');
+ }
+ });
+
+ it('renders first-column cell content identically to a plugin-free Table', () => {
+ const {container: withPlugin} = render(<TreeTable data={flat} />);
+ const pluginCell = withPlugin.querySelector('tbody td');
+
+ const {container: without} = render(
+ <Table data={flat} columns={columns} idKey="id" />,
+ );
+ const plainCell = without.querySelector('tbody td');
+
+ expect(pluginCell).toBeTruthy();
+ expect(plainCell).toBeTruthy();
+ expect(pluginCell?.innerHTML).toBe(plainCell?.innerHTML);
+ });
+});
+
+// =============================================================================
+// Stability across data-shape changes
+// =============================================================================
+
+describe('useTableTreeData — stability when the data shape changes', () => {
+ const flat: FileRow[] = [
+ {id: 'a', name: 'alpha', size: 1},
+ {id: 'b', name: 'beta', size: 2},
+ ];
+
+ it('does not remount the table when flat data becomes nested', () => {
+ const {container, rerender} = render(<TreeTable data={flat} />);
+ const tableBefore = container.querySelector('table');
+
+ rerender(<TreeTable data={fileTree} />);
+
+ expect(container.querySelector('table')).toBe(tableBefore);
+ // The tree affordance appears without a remount.
+ expect(
+ screen.getAllByRole('button', {name: 'Expand row'}).length,
+ ).toBeGreaterThan(0);
+ });
+
+ it('does not warn about an empty plugin for flat data', () => {
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ try {
+ render(<TreeTable data={flat} />);
+ const pluginWarnings = warn.mock.calls.filter(args =>
+ String(args[0]).includes('no transform methods'),
+ );
+ expect(pluginWarnings).toHaveLength(0);
+ } finally {
+ warn.mockRestore();
+ }
+ });
+
+ it('removes tree ARIA from rows when nested data becomes flat', () => {
+ const {rerender} = render(
+ <TreeTable data={fileTree} defaultExpandedIds={['src']} />,
+ );
+ expect(getRowByText('src')).toHaveAttribute('aria-level', '1');
+
+ rerender(<TreeTable data={flat} />);
+
+ for (const row of getBodyRows()) {
+ expect(row).not.toHaveAttribute('aria-level');
+ expect(row).not.toHaveAttribute('aria-expanded');
+ }
+ });
+});
+
+// =============================================================================
+// Toggle batching
+// =============================================================================
+
+describe('useTableTreeState — batched toggles', () => {
+ it('applies two different toggles landing in the same React batch', async () => {
+ const user = userEvent.setup();
+
+ function TwoTogglesTable() {
+ const {visibleData, treeConfig, expandAll} = useTableTreeState<FileRow>({
+ data: fileTree,
+ idKey: 'id',
+ });
+ const tree = useTableTreeData(treeConfig);
+ return (
+ <>
+ <button
+ type="button"
+ onClick={() => {
+ // Two commits in one event handler — one React batch.
+ treeConfig.onToggleItem(fileTree[0]); // expand 'src'
+ treeConfig.onToggleItem(fileTree[0].children![0]); // expand 'components'
+ }}>
+ expand two
+ </button>
+ <Table
+ data={visibleData}
+ columns={columns}
+ idKey="id"
+ plugins={{tree}}
+ />
+ <button type="button" onClick={expandAll}>
+ noop
+ </button>
+ </>
+ );
+ }
+
+ render(<TwoTogglesTable />);
+
+ await user.click(screen.getByRole('button', {name: 'expand two'}));
+
+ // Both toggles must survive the batch.
+ expect(screen.getByText('components')).toBeInTheDocument();
+ expect(screen.getByText('Button.tsx')).toBeInTheDocument();
+ });
+});
+
+// =============================================================================
+// Indentation
+// =============================================================================
+
+describe('useTableTreeData — indentation', () => {
+ it('indents nested rows by calc(level * step) and leaves roots unindented', () => {
+ render(<TreeTable defaultExpandedIds={['src', 'components']} />);
+
+ const cellWrapper = (text: string) =>
+ within(getRowByText(text)).getByText(text).closest('td')
+ ?.firstElementChild as HTMLElement;
+
+ expect(cellWrapper('src').getAttribute('style') ?? '').not.toContain(
+ 'calc',
+ );
+ expect(cellWrapper('components').getAttribute('style')).toContain(
+ 'calc(1 *',
+ );
+ expect(cellWrapper('Button.tsx').getAttribute('style')).toContain(
+ 'calc(2 *',
+ );
+ });
+
+ it('respects the indent token size', () => {
+ render(<TreeTable defaultExpandedIds={['src']} indent="lg" />);
+
+ const wrapper = within(getRowByText('utils.ts'))
+ .getByText('utils.ts')
+ .closest('td')?.firstElementChild as HTMLElement;
+ // lg maps to the --spacing-6 token
+ expect(wrapper.getAttribute('style')).toContain('--spacing-6');
+ });
+
+ it('never indents with a physical inline padding (logical property lives in the StyleX class)', () => {
+ // The indent is a StyleX dynamic style: the inline style carries only
+ // the CSS variable with the calc value; the paddingInlineStart property
+ // itself is compiled into the class. Guard against a regression to
+ // physical inline padding, which would not mirror in RTL.
+ render(<TreeTable defaultExpandedIds={['src']} />);
+
+ const wrapper = within(getRowByText('utils.ts'))
+ .getByText('utils.ts')
+ .closest('td')?.firstElementChild as HTMLElement;
+ const style = wrapper.getAttribute('style') ?? '';
+ expect(style).toContain('calc(1 *');
+ expect(style).not.toContain('padding-left');
+ expect(style).not.toContain('margin-left');
+ });
+
+ it('supports deep nesting with no depth cap', () => {
+ // a > b > c > d > e (levels 0..4)
+ let node: FileRow = {id: 'e', name: 'leaf-e', size: 0};
+ for (const id of ['d', 'c', 'b', 'a']) {
+ node = {id, name: `node-${id}`, size: 0, children: [node]};
+ }
+ render(
+ <TreeTable data={[node]} defaultExpandedIds={['a', 'b', 'c', 'd']} />,
+ );
+
+ const leafRow = getRowByText('leaf-e');
+ expect(leafRow).toHaveAttribute('aria-level', '5');
+ const wrapper = within(leafRow).getByText('leaf-e').closest('td')
+ ?.firstElementChild as HTMLElement;
+ expect(wrapper.getAttribute('style')).toContain('calc(4 *');
+ });
+});
+
+// =============================================================================
+// treeColumnKey
+// =============================================================================
+
+describe('useTableTreeData — treeColumnKey', () => {
+ it('moves the expander into the configured column', () => {
+ render(<TreeTable treeColumnKey="size" />);
+
+ const srcRow = getRowByText('src');
+ const cells = within(srcRow).getAllByRole('cell');
+ // name column carries no expander; size column does
+ expect(within(cells[0]).queryByRole('button')).toBeNull();
+ expect(
+ within(cells[1]).getByRole('button', {name: 'Expand row'}),
+ ).toBeInTheDocument();
+ });
+
+ it('falls back to the first column when the configured column is absent', () => {
+ // e.g. columnSettings hid the configured tree column — the expander
+ // must not vanish while rows still announce aria-expanded.
+ render(<TreeTable treeColumnKey="not-a-column" />);
+
+ const srcRow = getRowByText('src');
+ const cells = within(srcRow).getAllByRole('cell');
+ expect(
+ within(cells[0]).getByRole('button', {name: 'Expand row'}),
+ ).toBeInTheDocument();
+ });
+});
+
+// =============================================================================
+// Lazy loading
+// =============================================================================
+
+describe('useTableTreeData — lazy loading', () => {
+ it('shows an expander before children exist and reveals them once loaded', async () => {
+ const user = userEvent.setup();
+
+ function LazyTable() {
+ const [data, setData] = useState<FileRow[]>([
+ {id: 'folder', name: 'folder', size: 0},
+ ]);
+ const {visibleData, treeConfig} = useTableTreeState<FileRow>({
+ data,
+ idKey: 'id',
+ isItemExpandable: item => item.id === 'folder',
+ onExpandedIdsChange: ids => {
+ if (ids.has('folder')) {
+ // Simulated fetch: children arrive after expansion.
+ setData([
+ {
+ id: 'folder',
+ name: 'folder',
+ size: 0,
+ children: [{id: 'lazy-child', name: 'lazy-child', size: 3}],
+ },
+ ]);
+ }
+ },
+ });
+ const tree = useTableTreeData(treeConfig);
+ return (
+ <Table
+ data={visibleData}
+ columns={columns}
+ idKey="id"
+ plugins={{tree}}
+ />
+ );
+ }
+
+ render(<LazyTable />);
+
+ await user.click(screen.getByRole('button', {name: 'Expand row'}));
+
+ expect(screen.getByText('lazy-child')).toBeInTheDocument();
+ });
+});
+
+// =============================================================================
+// Degenerate configurations
+// =============================================================================
+
+describe('useTableTreeData — degenerate configurations', () => {
+ it('renders without crashing when the table has zero columns', () => {
+ function ZeroColumnsTable() {
+ const {visibleData, treeConfig} = useTableTreeState<FileRow>({
+ data: fileTree,
+ idKey: 'id',
+ });
+ const tree = useTableTreeData(treeConfig);
+ return (
+ <Table data={visibleData} columns={[]} idKey="id" plugins={{tree}} />
+ );
+ }
+
+ expect(() => render(<ZeroColumnsTable />)).not.toThrow();
+ });
+
+ it('updates aria-level in place when a row is reparented deeper', () => {
+ const flat: FileRow[] = [
+ {
+ id: 'a',
+ name: 'alpha',
+ size: 0,
+ children: [{id: 'k', name: 'kid', size: 1}],
+ },
+ {id: 'm', name: 'mover', size: 2},
+ ];
+ const nested: FileRow[] = [
+ {
+ id: 'a',
+ name: 'alpha',
+ size: 0,
+ children: [
+ {id: 'k', name: 'kid', size: 1},
+ {id: 'm', name: 'mover', size: 2},
+ ],
+ },
+ ];
+
+ const {rerender} = render(
+ <TreeTable data={flat} defaultExpandedIds={['a']} />,
+ );
+ expect(getRowByText('mover')).toHaveAttribute('aria-level', '1');
+
+ rerender(<TreeTable data={nested} defaultExpandedIds={['a']} />);
+
+ expect(getRowByText('mover')).toHaveAttribute('aria-level', '2');
+ });
+});
+
+// =============================================================================
+// Composition with selection
+// =============================================================================
+
+describe('useTableTreeData — composition with selection', () => {
+ it('prepends the selection checkbox column before the tree column', () => {
+ function ComposedTable() {
+ const [selectedKeys, setSelectedKeys] = useState<Set<string>>(
+ () => new Set(),
+ );
+ const {visibleData, treeConfig} = useTableTreeState<FileRow>({
+ data: fileTree,
+ idKey: 'id',
+ defaultExpandedIds: ['src'],
+ });
+ const {selectionConfig} = useTableSelectionState({
+ data: visibleData,
+ idKey: 'id',
+ selectedKeys,
+ setSelectedKeys,
+ });
+ const tree = useTableTreeData(treeConfig);
+ const selection = useTableSelection(selectionConfig);
+ return (
+ <Table
+ data={visibleData}
+ columns={columns}
+ idKey="id"
+ plugins={{tree, selection}}
+ />
+ );
+ }
+
+ render(<ComposedTable />);
+
+ const srcRow = getRowByText('src');
+ const cells = within(srcRow).getAllByRole('cell');
+ // Checkbox column first, then the tree (name) column with the expander.
+ expect(within(cells[0]).getByRole('checkbox')).toBeInTheDocument();
+ expect(
+ within(cells[1]).getByRole('button', {name: 'Collapse row'}),
+ ).toBeInTheDocument();
+ });
+});
+
+// =============================================================================
+// Composition with sorting
+// =============================================================================
+
+describe('useTableTreeData — composition with sorting', () => {
+ it('sorts sibling groups via applySort without interleaving levels', () => {
+ function SortedTree() {
+ const {applySort} = useTableSortableState<FileRow>({
+ data: fileTree,
+ defaultSort: [{sortKey: 'name', direction: 'descending'}],
+ });
+ const {visibleData, treeConfig} = useTableTreeState<FileRow>({
+ data: fileTree,
+ idKey: 'id',
+ defaultExpandedIds: ['src'],
+ sortSiblings: applySort,
+ });
+ const tree = useTableTreeData(treeConfig);
+ return (
+ <Table
+ data={visibleData}
+ columns={columns}
+ idKey="id"
+ plugins={{tree}}
+ />
+ );
+ }
+
+ render(<SortedTree />);
+
+ const names = getBodyRows().map(
+ row => within(row).getAllByRole('cell')[0].textContent,
+ );
+ // Roots desc: src > README.md; src's children desc: utils.ts > components.
+ // Children stay directly under their parent.
+ expect(names).toEqual(['src', 'utils.ts', 'components', 'README.md']);
+ });
+});
diff --git a/packages/core/src/Table/plugins/tree/useTableTreeData.tsx b/packages/core/src/Table/plugins/tree/useTableTreeData.tsx
new file mode 100644
index 0000000000..3d7acc1458
--- /dev/null
+++ b/packages/core/src/Table/plugins/tree/useTableTreeData.tsx
@@ -0,0 +1,489 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+'use client';
+
+/**
+ * @file useTableTreeData.tsx
+ * @input React, StyleX, Icon, Table types, theme tokens
+ * @output Exports useTableTreeData hook + config/meta types
+ * @position Tree plugin; consumed by Table via plugins prop.
+ * Pairs with useTableTreeState (owns expansion state + flattening).
+ *
+ * ## Architecture (mirrors useTableSelection)
+ *
+ * The tree affordance decorates the tree column's cells in place — no
+ * synthetic column. `transformColumns` wraps the tree column's renderCell
+ * with a flex wrapper carrying per-level indentation and an expander
+ * button (or a fixed-width spacer on leaves). Other columns get zero
+ * extra DOM.
+ *
+ * Expansion state flows through an external store (TreeStore) so each
+ * row's expander subscribes independently — a toggle re-renders only the
+ * affected cells, not the whole body. Row ARIA (aria-level,
+ * aria-expanded) is applied imperatively via a ref callback on each
+ * <tr>, exactly like selection's row styling; each subscription
+ * self-cleans when the row disconnects.
+ *
+ * When `hasExpandableRows` is false (flat data), every transform is a
+ * pass-through: adopting the plugin ahead of hierarchical data is a
+ * no-op.
+ */
+
+import {
+ createContext,
+ use,
+ useCallback,
+ useEffect,
+ useMemo,
+ useRef,
+ useSyncExternalStore,
+ type ReactNode,
+} from 'react';
+import * as stylex from '@stylexjs/stylex';
+import {colorVars, radiusVars, spacingVars} from '../../../theme/tokens.stylex';
+import {Icon} from '../../../Icon';
+import {mergeRefs} from '../../../utils';
+import type {TablePlugin, TableColumn, BodyRowRenderProps} from '../../types';
+
+// =============================================================================
+// Types
+// =============================================================================
+
+/** Structural position of one visible row within the tree. */
+export interface TableTreeRowMeta {
+ /** The row's id (from `idKey`). */
+ id: string;
+ /** 0-based depth: roots are level 0. */
+ level: number;
+ /** Whether the row shows an expander. */
+ hasChildren: boolean;
+ /** Whether the row is currently expanded. */
+ isExpanded: boolean;
+}
+
+/**
+ * Configuration for useTableTreeData. `useTableTreeState` returns a
+ * ready-made value (`treeConfig`); consumers with server-driven or
+ * pre-flattened trees can construct one directly.
+ */
+export interface UseTableTreeDataConfig<T extends Record<string, unknown>> {
+ /** Structural meta for a visible row; undefined for unknown rows. */
+ getRowMeta: (item: T) => TableTreeRowMeta | undefined;
+ /** Toggle a row's expansion. */
+ onToggleItem: (item: T) => void;
+ /**
+ * Whether any row in the dataset is expandable. When false the plugin is
+ * a no-op: no expanders, no indent, no tree ARIA — flat data renders
+ * identically to a Table without the plugin.
+ */
+ hasExpandableRows: boolean;
+ /**
+ * Indent step per level, as spacing tokens.
+ * @default 'md'
+ */
+ indent?: 'sm' | 'md' | 'lg';
+ /** Column that carries the indent + expander. @default the first column */
+ treeColumnKey?: string;
+}
+
+// =============================================================================
+// Tree Store (external store for fine-grained row subscriptions)
+// =============================================================================
+
+interface TreeStore<T extends Record<string, unknown>> {
+ subscribe: (listener: () => void) => () => void;
+ notify: () => void;
+ getConfig: () => UseTableTreeDataConfig<T>;
+}
+
+function createTreeStore<T extends Record<string, unknown>>(
+ configRef: React.RefObject<UseTableTreeDataConfig<T>>,
+): TreeStore<T> {
+ const listeners = new Set<() => void>();
+
+ return {
+ subscribe(listener: () => void) {
+ listeners.add(listener);
+ return () => listeners.delete(listener);
+ },
+ notify() {
+ for (const listener of listeners) {
+ listener();
+ }
+ },
+ getConfig() {
+ return configRef.current;
+ },
+ };
+}
+
+// eslint-disable-next-line @typescript-eslint/no-explicit-any
+const TreeStoreContext = createContext<TreeStore<any> | null>(null);
+TreeStoreContext.displayName = 'TreeStoreContext';
+
+/** Indent token -> index, for the numeric row snapshot. */
+const INDENT_INDEX = {sm: 0, md: 1, lg: 2} as const;
+
+/**
+ * Encode a row's tree meta as a primitive for useSyncExternalStore —
+ * object snapshots would tear. The indent token participates so a
+ * runtime `indent` change re-renders the affected cells.
+ * Encoding: level * 16 + indentIndex * 4 + hasChildren * 2 + isExpanded;
+ * -1 = no meta.
+ */
+function encodeRowMeta<T extends Record<string, unknown>>(
+ config: UseTableTreeDataConfig<T>,
+ item: T,
+): number {
+ const meta = config.getRowMeta(item);
+ if (!meta) {
+ return -1;
+ }
+ return (
+ meta.level * 16 +
+ INDENT_INDEX[config.indent ?? 'md'] * 4 +
+ (meta.hasChildren ? 2 : 0) +
+ (meta.isExpanded ? 1 : 0)
+ );
+}
+
+function useRowMetaSnapshot<T extends Record<string, unknown>>(
+ store: TreeStore<T>,
+ item: T,
+): number {
+ const getSnapshot = useCallback(
+ () => encodeRowMeta(store.getConfig(), item),
+ [store, item],
+ );
+
+ return useSyncExternalStore(store.subscribe, getSnapshot, getSnapshot);
+}
+
+// =============================================================================
+// Row ARIA (imperative, mirrors selection's row styling)
+// =============================================================================
+
+function applyRowTreeAria(
+ el: HTMLTableRowElement,
+ meta: TableTreeRowMeta | undefined,
+): void {
+ if (!meta) {
+ el.removeAttribute('aria-level');
+ el.removeAttribute('aria-expanded');
+ return;
+ }
+ el.setAttribute('aria-level', String(meta.level + 1));
+ if (meta.hasChildren) {
+ el.setAttribute('aria-expanded', String(meta.isExpanded));
+ } else {
+ el.removeAttribute('aria-expanded');
+ }
+}
+
+// =============================================================================
+// Styles
+// =============================================================================
+
+/** Indent step per level, by the `indent` config token. */
+const INDENT_STEP = {
+ sm: spacingVars['--spacing-3'],
+ md: spacingVars['--spacing-4'],
+ lg: spacingVars['--spacing-6'],
+} as const;
+
+const treeStyles = stylex.create({
+ cell: {
+ display: 'flex',
+ alignItems: 'center',
+ gap: spacingVars['--spacing-1'],
+ },
+ indent: (paddingInlineStart: string) => ({
+ paddingInlineStart,
+ }),
+ expanderButton: {
+ display: 'inline-flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ width: '24px',
+ height: '24px',
+ background: 'transparent',
+ border: 'none',
+ borderRadius: radiusVars['--radius-inner'],
+ cursor: 'pointer',
+ color: colorVars['--color-icon-secondary'],
+ transitionProperty: 'color, background-color',
+ transitionDuration: '150ms',
+ padding: 0,
+ flexShrink: '0',
+ // Match IconButton ghost hover: subtle overlay background
+ backgroundImage: {
+ default: null,
+ ':hover': {
+ '@media (hover: hover)': `linear-gradient(${colorVars['--color-overlay-hover']}, ${colorVars['--color-overlay-hover']})`,
+ },
+ },
+ ':hover': {
+ color: colorVars['--color-icon-primary'],
+ },
+ },
+ chevron: {
+ display: 'inline-flex',
+ transitionProperty: 'transform',
+ transitionDuration: '150ms',
+ transform: 'rotate(0deg)',
+ },
+ chevronExpanded: {
+ transform: 'rotate(90deg)',
+ },
+ /** Keeps leaf content aligned with expandable siblings. */
+ leafSpacer: {
+ display: 'inline-block',
+ width: '24px',
+ height: '24px',
+ flexShrink: '0',
+ },
+});
+
+// =============================================================================
+// Cell content
+// =============================================================================
+
+function TreeExpander({
+ isExpanded,
+ onToggle,
+}: {
+ isExpanded: boolean;
+ onToggle: () => void;
+}) {
+ return (
+ <button
+ type="button"
+ {...stylex.props(treeStyles.expanderButton)}
+ onClick={e => {
+ e.stopPropagation();
+ onToggle();
+ }}
+ aria-label={isExpanded ? 'Collapse row' : 'Expand row'}
+ aria-expanded={isExpanded}>
+ <span
+ {...stylex.props(
+ treeStyles.chevron,
+ isExpanded && treeStyles.chevronExpanded,
+ )}>
+ <Icon icon="chevronRight" size="xsm" />
+ </span>
+ </button>
+ );
+}
+
+function TreeCellContent<T extends Record<string, unknown>>({
+ item,
+ children,
+}: {
+ item: T;
+ children: ReactNode;
+}) {
+ const store = use(TreeStoreContext);
+ if (!store) {
+ return <>{children}</>;
+ }
+
+ return (
+ <TreeCellContentInner store={store} item={item}>
+ {children}
+ </TreeCellContentInner>
+ );
+}
+
+function TreeCellContentInner<T extends Record<string, unknown>>({
+ store,
+ item,
+ children,
+}: {
+ store: TreeStore<T>;
+ item: T;
+ children: ReactNode;
+}) {
+ // Subscribe to this row's structural meta so a toggle re-renders only
+ // the affected cells.
+ useRowMetaSnapshot(store, item);
+
+ const config = store.getConfig();
+ const meta = config.getRowMeta(item);
+ if (!meta) {
+ return <>{children}</>;
+ }
+
+ const step = INDENT_STEP[config.indent ?? 'md'];
+ const indent = `calc(${meta.level} * ${step})`;
+
+ return (
+ <div
+ {...stylex.props(
+ treeStyles.cell,
+ meta.level > 0 && treeStyles.indent(indent),
+ )}>
+ {meta.hasChildren ? (
+ <TreeExpander
+ isExpanded={meta.isExpanded}
+ onToggle={() => store.getConfig().onToggleItem(item)}
+ />
+ ) : (
+ <span {...stylex.props(treeStyles.leafSpacer)} />
+ )}
+ {children}
+ </div>
+ );
+}
+
+// =============================================================================
+// Hook
+// =============================================================================
+
+export function useTableTreeData<T extends Record<string, unknown>>(
+ config: UseTableTreeDataConfig<T>,
+): TablePlugin<T> {
+ const configRef = useRef(config);
+ configRef.current = config;
+
+ const storeRef = useRef<TreeStore<T> | null>(null);
+ if (storeRef.current == null) {
+ storeRef.current = createTreeStore(configRef);
+ }
+ const store = storeRef.current;
+
+ // Notify subscribers on every render — useSyncExternalStore only
+ // re-renders cells whose snapshot actually changed. Row ref subscribers
+ // apply imperative ARIA independently.
+ useEffect(() => {
+ store.notify();
+ });
+
+ // transformColumns runs on every table render; wrapped column objects
+ // must keep their identity across renders or the per-row memo breaks
+ // and a toggle re-renders the whole body. Earlier plugins may rebuild
+ // structurally-identical arrays each render, so the cache compares
+ // input columns by shallow equality, not array identity. Held in a ref
+ // (like rowExpansion's column tracking) — transforms run during
+ // BaseTable's render, where a closure variable reassignment trips the
+ // react-compiler lint.
+ const columnsCacheRef = useRef<{
+ input: TableColumn<T>[];
+ treeKey: string | undefined;
+ wrapped: boolean;
+ output: TableColumn<T>[];
+ } | null>(null);
+
+ // The plugin object is created once per store and never changes shape:
+ // every transform reads the live config through the store, and
+ // internally no-ops when hasExpandableRows is false. Swapping between
+ // an empty and a context-wrapping plugin would change the element tree
+ // and remount the whole table when flat data turns nested.
+ return useMemo((): TablePlugin<T> => {
+ const getCachedColumns = (
+ columns: TableColumn<T>[],
+ treeKey: string | undefined,
+ wrapped: boolean,
+ ): TableColumn<T>[] | null => {
+ const cache = columnsCacheRef.current;
+ if (!cache || cache.treeKey !== treeKey || cache.wrapped !== wrapped) {
+ return null;
+ }
+ const prev = cache.input;
+ if (prev !== columns) {
+ if (prev.length !== columns.length) {
+ return null;
+ }
+ for (let i = 0; i < prev.length; i++) {
+ if (prev[i] !== columns[i]) {
+ return null;
+ }
+ }
+ }
+ return cache.output;
+ };
+
+ return {
+ transformTableContext(children: ReactNode) {
+ return <TreeStoreContext value={store}>{children}</TreeStoreContext>;
+ },
+
+ transformColumns(columns: TableColumn<T>[]) {
+ const {hasExpandableRows, treeColumnKey} = store.getConfig();
+
+ // Resolve the tree column: the configured key when present, else
+ // the first non-synthetic column (a configured column may have
+ // been hidden by columnSettings — the expander must not vanish).
+ const configuredExists =
+ treeColumnKey != null && columns.some(c => c.key === treeColumnKey);
+ const treeKey = configuredExists
+ ? treeColumnKey
+ : (columns.find(c => !c.key.startsWith('__'))?.key ??
+ columns[0]?.key);
+
+ // Migration guarantee: flat data renders identically to a Table
+ // without the plugin.
+ const wrapped = hasExpandableRows;
+ const cached = getCachedColumns(columns, treeKey, wrapped);
+ if (cached) {
+ return cached;
+ }
+ const output = !wrapped
+ ? columns
+ : columns.map(col => {
+ if (col.key !== treeKey) {
+ return col;
+ }
+ const originalRenderCell = col.renderCell;
+ return {
+ ...col,
+ renderCell: (item: T): ReactNode => (
+ <TreeCellContent item={item}>
+ {originalRenderCell
+ ? originalRenderCell(item)
+ : String(
+ (item[col.key] as
+ string | number | null | undefined) ?? '',
+ )}
+ </TreeCellContent>
+ ),
+ };
+ });
+ columnsCacheRef.current = {input: columns, treeKey, wrapped, output};
+ return output;
+ },
+
+ transformBodyRow(props: BodyRowRenderProps, item: T) {
+ // Attach a ref that subscribes to the store for imperative row
+ // ARIA. The ref returns a cleanup so React unsubscribes on
+ // detach — without it, every row re-render would leak one
+ // subscription (toggles shift rowIndex and re-render rows, so
+ // the listener set would grow on every toggle). The ref is
+ // attached even when no row is expandable so tree ARIA is
+ // removed if the data turns flat.
+ const treeRef: React.RefCallback<HTMLTableRowElement> = el => {
+ if (!el) {
+ return;
+ }
+ const apply = () => {
+ const cfg = store.getConfig();
+ applyRowTreeAria(
+ el,
+ cfg.hasExpandableRows ? cfg.getRowMeta(item) : undefined,
+ );
+ };
+ apply();
+ const unsub = store.subscribe(apply);
+ return () => {
+ unsub();
+ };
+ };
+
+ return {
+ ...props,
+ ref: props.ref ? mergeRefs(props.ref, treeRef) : treeRef,
+ };
+ },
+ };
+ }, [store]);
+}
diff --git a/packages/core/src/Table/plugins/tree/useTableTreeState.test.tsx b/packages/core/src/Table/plugins/tree/useTableTreeState.test.tsx
new file mode 100644
index 0000000000..459dc44349
--- /dev/null
+++ b/packages/core/src/Table/plugins/tree/useTableTreeState.test.tsx
@@ -0,0 +1,636 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file useTableTreeState.test.tsx
+ * @input Uses vitest, @testing-library/react
+ * @output Unit tests for useTableTreeState hook
+ * @position Testing; validates tree expansion state + nested-data flattening
+ */
+
+import {describe, it, expect, vi} from 'vitest';
+import {act, renderHook} from '@testing-library/react';
+import {useTableTreeState} from './useTableTreeState';
+
+// =============================================================================
+// Test Data
+// =============================================================================
+
+interface FileRow extends Record<string, unknown> {
+ id: string;
+ name: string;
+ size: number;
+ children?: FileRow[];
+}
+
+/**
+ * src/
+ * components/
+ * Button.tsx
+ * Input.tsx
+ * utils.ts
+ * README.md
+ */
+const fileTree: FileRow[] = [
+ {
+ id: 'src',
+ name: 'src',
+ size: 0,
+ children: [
+ {
+ id: 'components',
+ name: 'components',
+ size: 0,
+ children: [
+ {id: 'button', name: 'Button.tsx', size: 120},
+ {id: 'input', name: 'Input.tsx', size: 80},
+ ],
+ },
+ {id: 'utils', name: 'utils.ts', size: 40},
+ ],
+ },
+ {id: 'readme', name: 'README.md', size: 10},
+];
+
+const ids = (rows: FileRow[]) => rows.map(r => r.id);
+
+// =============================================================================
+// Flattening
+// =============================================================================
+
+describe('useTableTreeState — flattening', () => {
+ it('emits only root rows when nothing is expanded', () => {
+ const {result} = renderHook(() =>
+ useTableTreeState({data: fileTree, idKey: 'id'}),
+ );
+
+ expect(ids(result.current.visibleData)).toEqual(['src', 'readme']);
+ });
+
+ it('reveals children of defaultExpandedIds in depth-first order', () => {
+ const {result} = renderHook(() =>
+ useTableTreeState({
+ data: fileTree,
+ idKey: 'id',
+ defaultExpandedIds: ['src', 'components'],
+ }),
+ );
+
+ expect(ids(result.current.visibleData)).toEqual([
+ 'src',
+ 'components',
+ 'button',
+ 'input',
+ 'utils',
+ 'readme',
+ ]);
+ });
+
+ it('keeps a collapsed subtree unmounted even when its descendants are in the expanded set', () => {
+ // 'components' is expanded but its parent 'src' is not — nothing below
+ // 'src' is visible.
+ const {result} = renderHook(() =>
+ useTableTreeState({
+ data: fileTree,
+ idKey: 'id',
+ defaultExpandedIds: ['components'],
+ }),
+ );
+
+ expect(ids(result.current.visibleData)).toEqual(['src', 'readme']);
+ });
+});
+
+// =============================================================================
+// Toggling (uncontrolled)
+// =============================================================================
+
+describe('useTableTreeState — uncontrolled toggling', () => {
+ it('expands a row via treeConfig.onToggleItem', () => {
+ const {result} = renderHook(() =>
+ useTableTreeState({data: fileTree, idKey: 'id'}),
+ );
+
+ act(() => {
+ result.current.treeConfig.onToggleItem(fileTree[0]);
+ });
+
+ expect(ids(result.current.visibleData)).toEqual([
+ 'src',
+ 'components',
+ 'utils',
+ 'readme',
+ ]);
+ });
+
+ it('collapses an expanded row via treeConfig.onToggleItem', () => {
+ const {result} = renderHook(() =>
+ useTableTreeState({
+ data: fileTree,
+ idKey: 'id',
+ defaultExpandedIds: ['src'],
+ }),
+ );
+
+ act(() => {
+ result.current.treeConfig.onToggleItem(fileTree[0]);
+ });
+
+ expect(ids(result.current.visibleData)).toEqual(['src', 'readme']);
+ });
+});
+
+// =============================================================================
+// Controlled mode
+// =============================================================================
+
+describe('useTableTreeState — controlled mode', () => {
+ it('derives visibility from the controlled expandedIds set', () => {
+ const {result, rerender} = renderHook(
+ ({expanded}: {expanded: ReadonlySet<string>}) =>
+ useTableTreeState({
+ data: fileTree,
+ idKey: 'id',
+ expandedIds: expanded,
+ onExpandedIdsChange: () => {},
+ }),
+ {initialProps: {expanded: new Set<string>()}},
+ );
+
+ expect(ids(result.current.visibleData)).toEqual(['src', 'readme']);
+
+ rerender({expanded: new Set(['src'])});
+ expect(ids(result.current.visibleData)).toEqual([
+ 'src',
+ 'components',
+ 'utils',
+ 'readme',
+ ]);
+ });
+
+ it('reports toggles through onExpandedIdsChange without mutating its own state', () => {
+ const onExpandedIdsChange = vi.fn();
+ const {result} = renderHook(() =>
+ useTableTreeState({
+ data: fileTree,
+ idKey: 'id',
+ expandedIds: new Set<string>(),
+ onExpandedIdsChange,
+ }),
+ );
+
+ act(() => {
+ result.current.treeConfig.onToggleItem(fileTree[0]);
+ });
+
+ expect(onExpandedIdsChange).toHaveBeenCalledWith(new Set(['src']));
+ // Controlled: the visible rows only change when the owner passes a new set.
+ expect(ids(result.current.visibleData)).toEqual(['src', 'readme']);
+ });
+
+ it('fires onExpandedIdsChange in uncontrolled mode too', () => {
+ const onExpandedIdsChange = vi.fn();
+ const {result} = renderHook(() =>
+ useTableTreeState({
+ data: fileTree,
+ idKey: 'id',
+ onExpandedIdsChange,
+ }),
+ );
+
+ act(() => {
+ result.current.treeConfig.onToggleItem(fileTree[0]);
+ });
+
+ expect(onExpandedIdsChange).toHaveBeenCalledWith(new Set(['src']));
+ expect(ids(result.current.visibleData)).toEqual([
+ 'src',
+ 'components',
+ 'utils',
+ 'readme',
+ ]);
+ });
+});
+
+// =============================================================================
+// expandAll / collapseAll
+// =============================================================================
+
+describe('useTableTreeState — expandAll / collapseAll', () => {
+ it('expandAll reveals every level of the tree', () => {
+ const {result} = renderHook(() =>
+ useTableTreeState({data: fileTree, idKey: 'id'}),
+ );
+
+ act(() => {
+ result.current.expandAll();
+ });
+
+ expect(ids(result.current.visibleData)).toEqual([
+ 'src',
+ 'components',
+ 'button',
+ 'input',
+ 'utils',
+ 'readme',
+ ]);
+ });
+
+ it('collapseAll returns to roots only', () => {
+ const {result} = renderHook(() =>
+ useTableTreeState({
+ data: fileTree,
+ idKey: 'id',
+ defaultExpandedIds: ['src', 'components'],
+ }),
+ );
+
+ act(() => {
+ result.current.collapseAll();
+ });
+
+ expect(ids(result.current.visibleData)).toEqual(['src', 'readme']);
+ });
+
+ it('exposes the current expandedIds set', () => {
+ const {result} = renderHook(() =>
+ useTableTreeState({
+ data: fileTree,
+ idKey: 'id',
+ defaultExpandedIds: ['src'],
+ }),
+ );
+
+ expect(result.current.expandedIds).toEqual(new Set(['src']));
+ });
+});
+
+// =============================================================================
+// Row meta
+// =============================================================================
+
+describe('useTableTreeState — row meta', () => {
+ it('reports 0-based level, hasChildren, and isExpanded per row', () => {
+ const {result} = renderHook(() =>
+ useTableTreeState({
+ data: fileTree,
+ idKey: 'id',
+ defaultExpandedIds: ['src', 'components'],
+ }),
+ );
+
+ const meta = (id: string) => {
+ const item = result.current.visibleData.find(r => r.id === id);
+ if (!item) {
+ throw new Error(`row ${id} not visible`);
+ }
+ return result.current.treeConfig.getRowMeta(item);
+ };
+
+ expect(meta('src')).toEqual({
+ id: 'src',
+ level: 0,
+ hasChildren: true,
+ isExpanded: true,
+ });
+ expect(meta('components')).toEqual({
+ id: 'components',
+ level: 1,
+ hasChildren: true,
+ isExpanded: true,
+ });
+ expect(meta('button')).toEqual({
+ id: 'button',
+ level: 2,
+ hasChildren: false,
+ isExpanded: false,
+ });
+ expect(meta('readme')).toEqual({
+ id: 'readme',
+ level: 0,
+ hasChildren: false,
+ isExpanded: false,
+ });
+ });
+
+ it('treats an empty children array as a leaf', () => {
+ const data: FileRow[] = [
+ {id: 'a', name: 'a', size: 0, children: []},
+ {id: 'b', name: 'b', size: 0, children: [{id: 'c', name: 'c', size: 0}]},
+ ];
+ const {result} = renderHook(() => useTableTreeState({data, idKey: 'id'}));
+
+ expect(result.current.treeConfig.getRowMeta(data[0])?.hasChildren).toBe(
+ false,
+ );
+ expect(result.current.treeConfig.getRowMeta(data[1])?.hasChildren).toBe(
+ true,
+ );
+ });
+
+ it('flags hasExpandableRows=false for flat data (migration no-op)', () => {
+ const flat: FileRow[] = [
+ {id: 'a', name: 'a', size: 1},
+ {id: 'b', name: 'b', size: 2},
+ ];
+ const {result} = renderHook(() =>
+ useTableTreeState({data: flat, idKey: 'id'}),
+ );
+
+ expect(result.current.treeConfig.hasExpandableRows).toBe(false);
+ });
+
+ it('flags hasExpandableRows=true when any row has children', () => {
+ const {result} = renderHook(() =>
+ useTableTreeState({data: fileTree, idKey: 'id'}),
+ );
+
+ expect(result.current.treeConfig.hasExpandableRows).toBe(true);
+ });
+});
+
+// =============================================================================
+// Lazy loading (isItemExpandable)
+// =============================================================================
+
+describe('useTableTreeState — isItemExpandable', () => {
+ it('forces an expander on rows whose children have not loaded yet', () => {
+ const lazy: FileRow[] = [
+ {id: 'folder', name: 'folder', size: 0}, // no children yet
+ {id: 'file', name: 'file', size: 5},
+ ];
+ const {result} = renderHook(() =>
+ useTableTreeState({
+ data: lazy,
+ idKey: 'id',
+ isItemExpandable: item => item.id === 'folder',
+ }),
+ );
+
+ expect(result.current.treeConfig.getRowMeta(lazy[0])?.hasChildren).toBe(
+ true,
+ );
+ expect(result.current.treeConfig.getRowMeta(lazy[1])?.hasChildren).toBe(
+ false,
+ );
+ expect(result.current.treeConfig.hasExpandableRows).toBe(true);
+ });
+
+ it('expandAll includes isItemExpandable rows without loaded children', () => {
+ const lazy: FileRow[] = [{id: 'folder', name: 'folder', size: 0}];
+ const onExpandedIdsChange = vi.fn();
+ const {result} = renderHook(() =>
+ useTableTreeState({
+ data: lazy,
+ idKey: 'id',
+ isItemExpandable: () => true,
+ onExpandedIdsChange,
+ }),
+ );
+
+ act(() => {
+ result.current.expandAll();
+ });
+
+ expect(onExpandedIdsChange).toHaveBeenCalledWith(new Set(['folder']));
+ });
+});
+
+// =============================================================================
+// Sibling sorting
+// =============================================================================
+
+describe('useTableTreeState — sortSiblings', () => {
+ it('sorts within sibling groups, never across levels', () => {
+ const byNameDesc = (siblings: FileRow[]) =>
+ [...siblings].sort((a, b) => b.name.localeCompare(a.name));
+
+ const {result} = renderHook(() =>
+ useTableTreeState({
+ data: fileTree,
+ idKey: 'id',
+ defaultExpandedIds: ['src', 'components'],
+ sortSiblings: byNameDesc,
+ }),
+ );
+
+ // Roots sorted desc: src > README.md; src's children desc: utils > components;
+ // components' children desc: Input.tsx > Button.tsx. Children always stay
+ // directly under their parent.
+ expect(ids(result.current.visibleData)).toEqual([
+ 'src',
+ 'utils',
+ 'components',
+ 'input',
+ 'button',
+ 'readme',
+ ]);
+ });
+});
+
+// =============================================================================
+// Accessors
+// =============================================================================
+
+describe('useTableTreeState — accessors', () => {
+ it('supports a custom childrenKey', () => {
+ interface OrgRow extends Record<string, unknown> {
+ id: string;
+ reports?: OrgRow[];
+ }
+ const org: OrgRow[] = [{id: 'ceo', reports: [{id: 'cto'}, {id: 'cfo'}]}];
+ const {result} = renderHook(() =>
+ useTableTreeState({
+ data: org,
+ idKey: 'id',
+ childrenKey: 'reports',
+ defaultExpandedIds: ['ceo'],
+ }),
+ );
+
+ expect(result.current.visibleData.map(r => r.id)).toEqual([
+ 'ceo',
+ 'cto',
+ 'cfo',
+ ]);
+ });
+
+ it('supports a function idKey returning numbers', () => {
+ interface NumRow extends Record<string, unknown> {
+ num: number;
+ children?: NumRow[];
+ }
+ const data: NumRow[] = [{num: 1, children: [{num: 2}]}];
+ const {result} = renderHook(() =>
+ useTableTreeState({
+ data,
+ idKey: item => item.num,
+ defaultExpandedIds: ['1'],
+ }),
+ );
+
+ expect(result.current.visibleData.map(r => r.num)).toEqual([1, 2]);
+ });
+
+ it('passes indent and treeColumnKey through to the tree config', () => {
+ const {result} = renderHook(() =>
+ useTableTreeState({
+ data: fileTree,
+ idKey: 'id',
+ indent: 'lg',
+ treeColumnKey: 'name',
+ }),
+ );
+
+ expect(result.current.treeConfig.indent).toBe('lg');
+ expect(result.current.treeConfig.treeColumnKey).toBe('name');
+ });
+});
+
+// =============================================================================
+// Hostile / degenerate data
+// =============================================================================
+
+describe('useTableTreeState — hostile data', () => {
+ it('does not blow the stack on a self-referencing cycle', () => {
+ const a: FileRow = {id: 'a', name: 'a', size: 0};
+ a.children = [a]; // self-cycle
+ const {result} = renderHook(() =>
+ useTableTreeState({
+ data: [a],
+ idKey: 'id',
+ defaultExpandedIds: ['a'],
+ }),
+ );
+
+ // The cyclic edge is skipped: 'a' renders exactly once.
+ expect(ids(result.current.visibleData)).toEqual(['a']);
+ });
+
+ it('does not blow the stack when a descendant points back at an ancestor', () => {
+ const parent: FileRow = {id: 'p', name: 'p', size: 0};
+ const child: FileRow = {id: 'c', name: 'c', size: 0, children: [parent]};
+ parent.children = [child];
+ const {result} = renderHook(() =>
+ useTableTreeState({
+ data: [parent],
+ idKey: 'id',
+ defaultExpandedIds: ['p', 'c'],
+ }),
+ );
+
+ expect(ids(result.current.visibleData)).toEqual(['p', 'c']);
+ });
+
+ it('renders duplicate ids in different subtrees without crashing (shared expansion state)', () => {
+ const data: FileRow[] = [
+ {
+ id: 'x',
+ name: 'first-x',
+ size: 0,
+ children: [{id: 'dup', name: 'dup-under-x', size: 1}],
+ },
+ {
+ id: 'y',
+ name: 'second-y',
+ size: 0,
+ children: [{id: 'dup', name: 'dup-under-y', size: 2}],
+ },
+ ];
+ const {result} = renderHook(() =>
+ useTableTreeState({
+ data,
+ idKey: 'id',
+ defaultExpandedIds: ['x', 'y'],
+ }),
+ );
+
+ // Both duplicate rows stay visible; ids sharing a key share expansion.
+ expect(ids(result.current.visibleData)).toEqual(['x', 'dup', 'y', 'dup']);
+ });
+
+ it('ignores expanded ids that match no row', () => {
+ const {result} = renderHook(() =>
+ useTableTreeState({
+ data: fileTree,
+ idKey: 'id',
+ defaultExpandedIds: ['ghost', 'src'],
+ }),
+ );
+
+ expect(ids(result.current.visibleData)).toEqual([
+ 'src',
+ 'components',
+ 'utils',
+ 'readme',
+ ]);
+ });
+
+ it('handles empty data', () => {
+ const {result} = renderHook(() =>
+ useTableTreeState<FileRow>({data: [], idKey: 'id'}),
+ );
+
+ expect(result.current.visibleData).toEqual([]);
+ expect(result.current.treeConfig.hasExpandableRows).toBe(false);
+ act(() => {
+ result.current.expandAll(); // must not throw
+ });
+ expect(result.current.expandedIds).toEqual(new Set());
+ });
+
+ it('never mutates the consumer data when sortSiblings sorts in place', () => {
+ const inPlaceSorter = (siblings: FileRow[]) =>
+ siblings.sort((a, b) => b.name.localeCompare(a.name));
+
+ const childOrderBefore = fileTree[0].children!.map(c => c.id);
+ renderHook(() =>
+ useTableTreeState({
+ data: fileTree,
+ idKey: 'id',
+ defaultExpandedIds: ['src'],
+ sortSiblings: inPlaceSorter,
+ }),
+ );
+
+ expect(fileTree[0].children!.map(c => c.id)).toEqual(childOrderBefore);
+ });
+});
+
+// =============================================================================
+// Semantics edge cases
+// =============================================================================
+
+describe('useTableTreeState — semantics edges', () => {
+ it('defaultExpandedIds is ignored when expandedIds is controlled', () => {
+ const {result} = renderHook(() =>
+ useTableTreeState({
+ data: fileTree,
+ idKey: 'id',
+ defaultExpandedIds: ['src'],
+ expandedIds: new Set<string>(),
+ onExpandedIdsChange: () => {},
+ }),
+ );
+
+ expect(ids(result.current.visibleData)).toEqual(['src', 'readme']);
+ });
+
+ it('toggling a leaf never marks it expanded', () => {
+ const {result} = renderHook(() =>
+ useTableTreeState({data: fileTree, idKey: 'id'}),
+ );
+ const readme = fileTree[1];
+
+ act(() => {
+ result.current.treeConfig.onToggleItem(readme);
+ });
+
+ expect(result.current.treeConfig.getRowMeta(readme)).toEqual({
+ id: 'readme',
+ level: 0,
+ hasChildren: false,
+ isExpanded: false,
+ });
+ expect(ids(result.current.visibleData)).toEqual(['src', 'readme']);
+ });
+});
diff --git a/packages/core/src/Table/plugins/tree/useTableTreeState.tsx b/packages/core/src/Table/plugins/tree/useTableTreeState.tsx
new file mode 100644
index 0000000000..dffeedc1d9
--- /dev/null
+++ b/packages/core/src/Table/plugins/tree/useTableTreeState.tsx
@@ -0,0 +1,253 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+'use client';
+
+/**
+ * @file useTableTreeState.tsx
+ * @input React
+ * @output Exports useTableTreeState hook and config/result types
+ * @position Tree state helper; owns the expanded set + flattens nested data.
+ * Pairs with useTableTreeData (the headless tree plugin).
+ *
+ * Modeled after useTableSortableState — a convenience layer that owns state
+ * (controlled or uncontrolled) and produces both the visible flattened rows
+ * and a ready-to-use config for the headless plugin. Data shaping stays
+ * outside the render pipeline: Table always receives exactly the rows it
+ * renders, so collapsed subtrees are unmounted, not hidden.
+ */
+
+import {useCallback, useMemo, useRef, useState} from 'react';
+import type {
+ TableTreeRowMeta,
+ UseTableTreeDataConfig,
+} from './useTableTreeData';
+
+// =============================================================================
+// Config
+// =============================================================================
+
+export interface UseTableTreeStateConfig<T extends Record<string, unknown>> {
+ /** Nested data: rows may carry child rows under `childrenKey`. */
+ data: T[];
+ /** Row ID accessor: property name, or a function returning a unique id. */
+ idKey: (keyof T & string) | ((item: T) => string | number);
+ /**
+ * Property holding each row's children array.
+ * @default 'children'
+ */
+ childrenKey?: string;
+ /** Initial expanded row ids for uncontrolled mode. Ignored when `expandedIds` is provided. */
+ defaultExpandedIds?: Iterable<string>;
+ /**
+ * Controlled set of expanded row ids. When provided, the hook uses this
+ * instead of internal state. Pair with `onExpandedIdsChange`.
+ */
+ expandedIds?: ReadonlySet<string>;
+ /** Called with the next expanded set whenever expansion changes. */
+ onExpandedIdsChange?: (ids: ReadonlySet<string>) => void;
+ /**
+ * Should this row show an expander? Overrides the default
+ * "has a non-empty children array" check — use for lazy loading, where a
+ * row is expandable before its children have been fetched.
+ */
+ isItemExpandable?: (item: T) => boolean;
+ /**
+ * Sort each sibling group independently during flattening. Children always
+ * stay directly under their parent — sorting never crosses levels. Pass
+ * `applySort` from `useTableSortableState` to compose with column sorting.
+ */
+ sortSiblings?: (siblings: T[]) => T[];
+ /** Indent step per level, forwarded to useTableTreeData. */
+ indent?: 'sm' | 'md' | 'lg';
+ /** Column that carries the tree affordance, forwarded to useTableTreeData. */
+ treeColumnKey?: string;
+}
+
+// =============================================================================
+// Result
+// =============================================================================
+
+export interface UseTableTreeStateResult<T extends Record<string, unknown>> {
+ /** The flattened, currently-visible rows. Pass to `<Table data>`. */
+ visibleData: T[];
+ /** Ready-to-use config for useTableTreeData. */
+ treeConfig: UseTableTreeDataConfig<T>;
+ /** The current expanded row ids. */
+ expandedIds: ReadonlySet<string>;
+ /** Expand every expandable row in the tree. */
+ expandAll: () => void;
+ /** Collapse every row. */
+ collapseAll: () => void;
+}
+
+// =============================================================================
+// Hook
+// =============================================================================
+
+export function useTableTreeState<T extends Record<string, unknown>>(
+ config: UseTableTreeStateConfig<T>,
+): UseTableTreeStateResult<T> {
+ const {
+ data,
+ idKey,
+ childrenKey = 'children',
+ defaultExpandedIds,
+ expandedIds: controlledExpandedIds,
+ onExpandedIdsChange,
+ isItemExpandable,
+ sortSiblings,
+ indent,
+ treeColumnKey,
+ } = config;
+
+ const getId = useCallback(
+ (item: T): string =>
+ typeof idKey === 'function' ? String(idKey(item)) : String(item[idKey]),
+ [idKey],
+ );
+
+ const getChildren = useCallback(
+ (item: T): T[] => {
+ const children = item[childrenKey];
+ return Array.isArray(children) ? (children as T[]) : [];
+ },
+ [childrenKey],
+ );
+
+ const getIsExpandable = useCallback(
+ (item: T): boolean =>
+ isItemExpandable ? isItemExpandable(item) : getChildren(item).length > 0,
+ [isItemExpandable, getChildren],
+ );
+
+ // Internal state (used in uncontrolled mode)
+ const [internalExpandedIds, setInternalExpandedIds] = useState<
+ ReadonlySet<string>
+ >(() => new Set(defaultExpandedIds));
+
+ // Resolve controlled vs uncontrolled
+ const isControlled = controlledExpandedIds !== undefined;
+ const expandedIds = isControlled
+ ? controlledExpandedIds
+ : internalExpandedIds;
+
+ // Stable refs so callbacks don't churn on inline-prop identity changes
+ const expandedIdsRef = useRef(expandedIds);
+ expandedIdsRef.current = expandedIds;
+ const onExpandedIdsChangeRef = useRef(onExpandedIdsChange);
+ 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.
+ expandedIdsRef.current = next;
+ if (!isControlled) {
+ setInternalExpandedIds(next);
+ }
+ onExpandedIdsChangeRef.current?.(next);
+ },
+ [isControlled],
+ );
+
+ // Flatten: depth-first walk emitting only visible rows, collecting per-row
+ // meta ({level, hasChildren, isExpanded}) in the same pass. Children mount
+ // only when their parent is expanded, so collapsed subtrees stay unmounted.
+ // `path` holds the ids on the current ancestor chain: an edge pointing back
+ // at an ancestor is skipped instead of recursing forever. Sibling arrays
+ // are copied before sortSiblings so an in-place sorter can't reorder the
+ // consumer's data.
+ const {visibleData, metaMap} = useMemo(() => {
+ const rows: T[] = [];
+ const meta = new Map<string, TableTreeRowMeta>();
+ const path = new Set<string>();
+ const walk = (items: T[], level: number) => {
+ const siblings = sortSiblings ? sortSiblings([...items]) : items;
+ for (const item of siblings) {
+ const id = getId(item);
+ if (path.has(id)) {
+ continue; // cyclic edge — this row is its own ancestor
+ }
+ const hasChildren = getIsExpandable(item);
+ const isExpanded = hasChildren && expandedIds.has(id);
+ rows.push(item);
+ meta.set(id, {id, level, hasChildren, isExpanded});
+ if (isExpanded) {
+ path.add(id);
+ walk(getChildren(item), level + 1);
+ path.delete(id);
+ }
+ }
+ };
+ walk(data, 0);
+ return {visibleData: rows, metaMap: meta};
+ }, [data, expandedIds, getId, getChildren, getIsExpandable, sortSiblings]);
+
+ // Every expandable row id across the whole tree, including collapsed
+ // subtrees (drives expandAll and the migration no-op flag). Same
+ // ancestor-chain guard as the flatten walk.
+ const allExpandableIds = useMemo(() => {
+ const idsAcc: string[] = [];
+ const path = new Set<string>();
+ const walk = (items: T[]) => {
+ for (const item of items) {
+ const id = getId(item);
+ if (path.has(id)) {
+ continue;
+ }
+ if (getIsExpandable(item)) {
+ idsAcc.push(id);
+ }
+ path.add(id);
+ walk(getChildren(item));
+ path.delete(id);
+ }
+ };
+ walk(data);
+ return idsAcc;
+ }, [data, getId, getChildren, getIsExpandable]);
+
+ const hasExpandableRows = allExpandableIds.length > 0;
+
+ const onToggleItem = useCallback(
+ (item: T) => {
+ const id = getId(item);
+ const next = new Set(expandedIdsRef.current);
+ if (next.has(id)) {
+ next.delete(id);
+ } else {
+ next.add(id);
+ }
+ commitExpandedIds(next);
+ },
+ [getId, commitExpandedIds],
+ );
+
+ const expandAll = useCallback(() => {
+ commitExpandedIds(new Set(allExpandableIds));
+ }, [commitExpandedIds, allExpandableIds]);
+
+ const collapseAll = useCallback(() => {
+ commitExpandedIds(new Set());
+ }, [commitExpandedIds]);
+
+ const getRowMeta = useCallback(
+ (item: T): TableTreeRowMeta | undefined => metaMap.get(getId(item)),
+ [metaMap, getId],
+ );
+
+ const treeConfig = useMemo(
+ (): UseTableTreeDataConfig<T> => ({
+ getRowMeta,
+ onToggleItem,
+ hasExpandableRows,
+ indent,
+ treeColumnKey,
+ }),
+ [getRowMeta, onToggleItem, hasExpandableRows, indent, treeColumnKey],
+ );
+
+ return {visibleData, treeConfig, expandedIds, expandAll, collapseAll};
+}
diff --git a/packages/core/src/Table/useBaseTablePlugins.ts b/packages/core/src/Table/useBaseTablePlugins.ts
index 21e13ec7ce..613e67e3a1 100644
--- a/packages/core/src/Table/useBaseTablePlugins.ts
+++ b/packages/core/src/Table/useBaseTablePlugins.ts
@@ -18,12 +18,15 @@
* Canonical order:
* 1. columnSettings — column filtering (future: transformColumns)
* 2. sort — header cell sort controls
- * 3. selection — checkbox column + row selection
- * 4. pagination — pagination controls around the table
+ * 3. tree — indent + expander on the tree column
+ * 4. selection — checkbox column + row selection
+ * 5. pagination — pagination controls around the table
*
* Rationale:
* - columnSettings filters columns before sort/selection see them
* - sort adds header cell UI before selection adds its header column
+ * - tree wraps the first *user* column before selection prepends its
+ * checkbox column, so the expander never lands in the checkbox column
* - selection adds its column after sort so the checkbox header
* doesn't get a sort button
* - pagination wraps the table in context last (outermost provider)
@@ -46,6 +49,7 @@ import type {TablePlugin} from './types';
const PLUGIN_ORDER: ReadonlyArray<string> = [
'columnSettings',
'sort',
+ 'tree',
'selection',
'pagination',
];
diff --git a/packages/core/src/Table/useTableTreeData.doc.mjs b/packages/core/src/Table/useTableTreeData.doc.mjs
new file mode 100644
index 0000000000..b599bf00ad
--- /dev/null
+++ b/packages/core/src/Table/useTableTreeData.doc.mjs
@@ -0,0 +1,75 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/** @type {import('../docs-types').ComponentDoc} */
+
+export const docs = {
+ name: 'useTableTreeData',
+ subComponentOf: 'Table',
+ displayName: 'useTableTreeData',
+ description:
+ 'Headless tree plugin for Table: renders nested rows with per-level indentation and expand/collapse chevrons in the tree column (the first column by default), and reflects hierarchy on body rows via aria-level and aria-expanded. Composable with the other Table plugins: the canonical plugin order places tree before selection, so the checkbox column lands left of the indented tree column. Feed it the treeConfig from useTableTreeState, or construct the config directly for server-driven or pre-flattened trees. When no row is expandable (flat data), every transform is a pass-through and the table renders identically to one without the plugin. Known limitation: the tree column wraps its cell content, so textOverflow="truncate" tooltips do not apply within the tree column.',
+ props: [
+ {
+ name: 'getRowMeta',
+ type: '(item: T) => TableTreeRowMeta | undefined',
+ description:
+ 'Structural meta for a visible row: {id, level (0-based), hasChildren, isExpanded}.',
+ required: true,
+ },
+ {
+ name: 'onToggleItem',
+ type: '(item: T) => void',
+ description: 'Toggle a row’s expansion.',
+ required: true,
+ },
+ {
+ name: 'hasExpandableRows',
+ type: 'boolean',
+ description:
+ 'Whether any row in the dataset is expandable. When false the plugin is a no-op: no expanders, no indent, no tree ARIA.',
+ required: true,
+ },
+ {
+ name: 'indent',
+ type: "'sm' | 'md' | 'lg'",
+ description:
+ 'Indent step per level, mapped to the spacing-3 / spacing-4 / spacing-6 tokens.',
+ default: "'md'",
+ },
+ {
+ name: 'treeColumnKey',
+ type: 'string',
+ description:
+ 'Column that carries the indent + expander. Defaults to the first column.',
+ },
+ ],
+ examples: [
+ {
+ label: 'File tree with expandable folders',
+ code: `const {visibleData, treeConfig} = useTableTreeState({
+ data: files, // rows may nest under 'children'
+ idKey: 'id',
+ defaultExpandedIds: ['src'],
+});
+const tree = useTableTreeData(treeConfig);
+
+<Table data={visibleData} columns={columns} idKey="id" plugins={{tree}} />;`,
+ },
+ ],
+};
+
+export const docsDense = {
+ name: 'useTableTreeData',
+ displayName: 'useTableTreeData',
+ description:
+ 'Headless tree plugin: indent + expander chevron on the tree column (first column by default), aria-level/aria-expanded on body rows. Canonical plugin order puts tree before selection (checkbox column lands left of tree column). Consume treeConfig from useTableTreeState, or construct directly for server-driven trees. hasExpandableRows=false => full no-op (flat-data migration).',
+ propDescriptions: {
+ getRowMeta:
+ 'structural meta per visible row: {id, level (0-based), hasChildren, isExpanded}',
+ onToggleItem: 'toggle row expansion',
+ hasExpandableRows: 'false => plugin is a no-op (no expanders/indent/ARIA)',
+ indent:
+ "indent step per level: 'sm' | 'md' | 'lg' (spacing-3/4/6). Defaults to 'md'.",
+ treeColumnKey: 'column carrying indent + expander. Defaults to first column.',
+ },
+};
diff --git a/packages/core/src/Table/useTableTreeState.doc.mjs b/packages/core/src/Table/useTableTreeState.doc.mjs
new file mode 100644
index 0000000000..7ed0505a74
--- /dev/null
+++ b/packages/core/src/Table/useTableTreeState.doc.mjs
@@ -0,0 +1,98 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/** @type {import('../docs-types').ComponentDoc} */
+
+export const docs = {
+ name: 'useTableTreeState',
+ subComponentOf: 'Table',
+ displayName: 'useTableTreeState',
+ description:
+ 'State management companion for useTableTreeData. Owns the expanded set (controlled or uncontrolled) and flattens nested data into the visible row array — collapsed subtrees are unmounted, not hidden, so the table body contains exactly the visible rows. Returns expandAll/collapseAll helpers and a ready-to-use config for the tree plugin. Note: because collapsed rows unmount, cell-local React state inside collapsed subtrees is lost on collapse; lift state that must survive.',
+ props: [
+ {
+ name: 'data',
+ type: 'T[]',
+ description:
+ 'Nested data: rows may carry child rows under childrenKey. Flat data (no children anywhere) makes the plugin a no-op, so it can be adopted before the data becomes hierarchical.',
+ required: true,
+ },
+ {
+ name: 'idKey',
+ type: '(keyof T & string) | ((item: T) => string | number)',
+ description:
+ 'Row ID accessor: property name or function returning a unique id.',
+ required: true,
+ },
+ {
+ name: 'childrenKey',
+ type: 'string',
+ description: 'Property holding each row’s children array.',
+ default: "'children'",
+ },
+ {
+ name: 'defaultExpandedIds',
+ type: 'Iterable<string>',
+ description:
+ 'Initial expanded row ids for uncontrolled mode. Ignored when expandedIds is provided.',
+ },
+ {
+ name: 'expandedIds',
+ type: 'ReadonlySet<string>',
+ description:
+ 'Controlled set of expanded row ids. Pair with onExpandedIdsChange.',
+ },
+ {
+ name: 'onExpandedIdsChange',
+ type: '(ids: ReadonlySet<string>) => void',
+ description:
+ 'Called with the next expanded set whenever expansion changes (both modes). In lazy-loading setups, trigger the children fetch here.',
+ },
+ {
+ name: 'isItemExpandable',
+ type: '(item: T) => boolean',
+ description:
+ 'Should this row show an expander? Overrides the default non-empty-children check — use for lazy loading, where a row is expandable before its children have been fetched.',
+ },
+ {
+ name: 'sortSiblings',
+ type: '(siblings: T[]) => T[]',
+ description:
+ 'Sort each sibling group independently during flattening; children always stay directly under their parent. Pass applySort from useTableSortableState to compose with column sorting.',
+ },
+ {
+ name: 'indent',
+ type: "'sm' | 'md' | 'lg'",
+ description:
+ 'Indent step per level (spacing-3 / spacing-4 / spacing-6), forwarded to useTableTreeData.',
+ default: "'md'",
+ },
+ {
+ name: 'treeColumnKey',
+ type: 'string',
+ description:
+ 'Column that carries the indent + expander, forwarded to useTableTreeData. Defaults to the first column.',
+ },
+ ],
+};
+
+export const docsDense = {
+ name: 'useTableTreeState',
+ displayName: 'useTableTreeState',
+ description:
+ 'State companion for useTableTreeData. Owns expanded set (controlled or uncontrolled), flattens nested data to visible rows (collapsed subtrees unmounted, not hidden). Returns {visibleData, treeConfig, expandedIds, expandAll, collapseAll}. Cell-local state in collapsed subtrees is lost on collapse; lift state that must survive.',
+ propDescriptions: {
+ data: 'nested data; rows carry child rows under childrenKey. Flat data => plugin is a no-op.',
+ idKey: 'row ID accessor: property name or fn returning unique id',
+ childrenKey: "property holding children array. Defaults to 'children'.",
+ defaultExpandedIds: 'initial expanded ids (uncontrolled)',
+ expandedIds: 'controlled expanded set; pair with onExpandedIdsChange',
+ onExpandedIdsChange:
+ 'called with next expanded set on change (both modes); trigger lazy children fetch here',
+ isItemExpandable:
+ 'overrides non-empty-children expandability check (lazy loading)',
+ sortSiblings:
+ 'sorts each sibling group during flattening; pass applySort from useTableSortableState',
+ indent: "indent step per level: 'sm' | 'md' | 'lg'. Defaults to 'md'.",
+ treeColumnKey: 'column carrying indent + expander. Defaults to first column.',
+ },
+};