Skip to content

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

TypeScript

feat(core): add expand-all header control to Table tree plugin (#4142) (#4172)

Humberto Virtudesca17ee6795ec
diff --git a/.changeset/tree-expand-all-control.md b/.changeset/tree-expand-all-control.md
new file mode 100644
index 0000000000..1d0ba277f8
--- /dev/null
+++ b/.changeset/tree-expand-all-control.md
@@ -0,0 +1,9 @@
+---
+'@astryxdesign/core': patch
+---
+
+[feat] Table tree: add an optional expand-all/collapse-all header control (#4142)
+
+`useTableTreeState` now returns an aggregate `isAllExpanded` state (`true` / `false` / `'indeterminate'`) and threads `expandAll` / `collapseAll` into `treeConfig`. `useTableTreeData` gains a `hasExpandAllControl` prop: when set, it renders an expand-all/collapse-all toggle in the tree column header, wired to that state, so consumers no longer need to hand-roll external buttons. Flat data stays a full no-op. This is the first affordance folded in from `useTableRowExpansion` as part of converging the two tree plugins.
+
+@humbertovirtudes
diff --git a/apps/storybook/stories/TableTree.stories.tsx b/apps/storybook/stories/TableTree.stories.tsx
index 065ec54587..4f060aab67 100644
--- a/apps/storybook/stories/TableTree.stories.tsx
+++ b/apps/storybook/stories/TableTree.stories.tsx
@@ -222,6 +222,33 @@ export const ExpandAndCollapseAll: Story = {
},
};
+/**
+ * `hasExpandAllControl` renders a built-in expand-all/collapse-all toggle in
+ * the tree column header, wired to the state hook. No external buttons needed:
+ * the toggle reads the aggregate `isAllExpanded` state (down chevron only when
+ * every expandable row is expanded) and calls `expandAll`/`collapseAll`.
+ */
+export const HeaderExpandAllControl: Story = {
+ render: () => {
+ const {visibleData, treeConfig} = useTableTreeState<OrgRow>({
+ data: orgChart,
+ idKey: 'id',
+ defaultExpandedIds: ['eng'],
+ });
+ const tree = useTableTreeData({...treeConfig, hasExpandAllControl: true});
+
+ return (
+ <Table
+ data={visibleData}
+ columns={columns}
+ idKey="id"
+ hasHover
+ plugins={{tree}}
+ />
+ );
+ },
+};
+
/**
* The `indent` token controls the step per level: `sm` (spacing-3), `md`
* (spacing-4, the default), and `lg` (spacing-6).
diff --git a/packages/cli/templates/blocks/components/Table/TableTreeTable.doc.mjs b/packages/cli/templates/blocks/components/Table/TableTreeTable.doc.mjs
new file mode 100644
index 0000000000..1fc11d14dd
--- /dev/null
+++ b/packages/cli/templates/blocks/components/Table/TableTreeTable.doc.mjs
@@ -0,0 +1,16 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/** @type {import('../../../../../core/src/docs-types').TemplateDoc} */
+export const doc = {
+ type: 'block',
+ exampleFor: 'useTableTreeData',
+ alsoExampleFor: ['useTableTreeState'],
+ alsoShowcaseFor: ['useTableTreeState'],
+ name: 'useTableTreeData: Tree Table',
+ displayName: 'useTableTreeData: Tree Table',
+ description:
+ 'A file-tree table built from nested data. useTableTreeState flattens the tree into the visible rows and owns the expanded set; useTableTreeData draws the per-level indent and the expand/collapse chevron in the tree column. The two hooks are designed to work together, so this one example covers both. hasExpandAllControl adds the expand-all/collapse-all toggle to the tree column header. Collapsed branches are unmounted, not hidden.',
+ isReady: true,
+ aspectRatio: 16 / 9,
+ componentsUsed: ['Table'],
+};
diff --git a/packages/cli/templates/blocks/components/Table/TableTreeTable.tsx b/packages/cli/templates/blocks/components/Table/TableTreeTable.tsx
new file mode 100644
index 0000000000..5b7d855086
--- /dev/null
+++ b/packages/cli/templates/blocks/components/Table/TableTreeTable.tsx
@@ -0,0 +1,81 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+'use client';
+
+import {
+ Table,
+ useTableTreeData,
+ useTableTreeState,
+ proportional,
+ pixel,
+} from '@astryxdesign/core/Table';
+
+interface FileNode extends Record<string, unknown> {
+ id: string;
+ name: string;
+ kind: 'folder' | 'file';
+ size: string;
+ children?: FileNode[];
+}
+
+const fileTree: FileNode[] = [
+ {
+ id: 'src',
+ name: 'src',
+ kind: 'folder',
+ size: '',
+ children: [
+ {
+ id: 'src/components',
+ name: 'components',
+ kind: 'folder',
+ size: '',
+ children: [
+ {
+ id: 'src/components/Button.tsx',
+ name: 'Button.tsx',
+ kind: 'file',
+ size: '4.2 KB',
+ },
+ {
+ id: 'src/components/Table.tsx',
+ name: 'Table.tsx',
+ kind: 'file',
+ size: '12.8 KB',
+ },
+ ],
+ },
+ {id: 'src/index.ts', name: 'index.ts', kind: 'file', size: '0.4 KB'},
+ ],
+ },
+ {id: 'package.json', name: 'package.json', kind: 'file', size: '1.8 KB'},
+];
+
+const columns = [
+ {key: 'name', header: 'Name', width: proportional(2)},
+ {key: 'kind', header: 'Kind', width: pixel(90)},
+ {key: 'size', header: 'Size', width: pixel(90)},
+];
+
+export default function TableTreeTable() {
+ // useTableTreeState owns the expanded set and flattens the nested data into
+ // the visible rows; useTableTreeData draws the indent + expander in the tree
+ // column. hasExpandAllControl adds the expand-all toggle to the header.
+ const {visibleData, treeConfig} = useTableTreeState<FileNode>({
+ data: fileTree,
+ idKey: 'id',
+ defaultExpandedIds: ['src'],
+ });
+
+ const tree = useTableTreeData({...treeConfig, hasExpandAllControl: true});
+
+ return (
+ <Table
+ data={visibleData}
+ columns={columns}
+ idKey="id"
+ hasHover
+ plugins={{tree}}
+ />
+ );
+}
diff --git a/packages/core/locales/en.json b/packages/core/locales/en.json
index 885653efc1..acb303cef7 100644
--- a/packages/core/locales/en.json
+++ b/packages/core/locales/en.json
@@ -763,6 +763,14 @@
"defaultMessage": "Expand row",
"description": "Aria label for the Table tree-data expander chevron when the row is currently collapsed."
},
+ "@astryx.tableTree.collapseAllRows": {
+ "defaultMessage": "Collapse all rows",
+ "description": "Aria label for the Table tree-data header toggle when all rows are expanded and clicking it collapses them."
+ },
+ "@astryx.tableTree.expandAllRows": {
+ "defaultMessage": "Expand all rows",
+ "description": "Aria label for the Table tree-data header toggle when rows are collapsed and clicking it expands them."
+ },
"@astryx.textInput.clearLabel": {
"defaultMessage": "Clear {label}",
"description": "Screen-reader-only label on the X that clears the value from a TextInput. Example: `Clear Email`, `Clear Name`."
diff --git a/packages/core/src/Table/plugins/tree/useTableTreeData.test.tsx b/packages/core/src/Table/plugins/tree/useTableTreeData.test.tsx
index c3dccc4bb8..dcf1bfe7cf 100644
--- a/packages/core/src/Table/plugins/tree/useTableTreeData.test.tsx
+++ b/packages/core/src/Table/plugins/tree/useTableTreeData.test.tsx
@@ -55,14 +55,18 @@ const columns: TableColumn<FileRow>[] = [
];
function TreeTable(
- props: Partial<UseTableTreeStateConfig<FileRow>> & {data?: FileRow[]},
+ props: Partial<UseTableTreeStateConfig<FileRow>> & {
+ data?: FileRow[];
+ hasExpandAllControl?: boolean;
+ },
) {
+ const {hasExpandAllControl, ...stateProps} = props;
const {visibleData, treeConfig} = useTableTreeState<FileRow>({
data: props.data ?? fileTree,
idKey: 'id',
- ...props,
+ ...stateProps,
});
- const tree = useTableTreeData(treeConfig);
+ const tree = useTableTreeData({...treeConfig, hasExpandAllControl});
return (
<Table data={visibleData} columns={columns} idKey="id" plugins={{tree}} />
@@ -592,3 +596,131 @@ describe('useTableTreeData — composition with sorting', () => {
expect(names).toEqual(['src', 'utils.ts', 'components', 'README.md']);
});
});
+
+// =============================================================================
+// header expand-all control
+// =============================================================================
+
+describe('useTableTreeData: expand-all header control', () => {
+ /** The header row is the first row; return its expand-all toggle if present. */
+ function queryExpandAllButton(): HTMLElement | null {
+ const headerRow = screen.getAllByRole('row')[0];
+ return (
+ within(headerRow).queryByRole('button', {name: /expand all/i}) ??
+ within(headerRow).queryByRole('button', {name: /collapse all/i})
+ );
+ }
+
+ it('renders no expand-all control by default', () => {
+ render(<TreeTable defaultExpandedIds={['src']} />);
+ expect(queryExpandAllButton()).toBeNull();
+ });
+
+ it('renders an "Expand all" toggle in the tree column header when enabled and collapsed', () => {
+ render(<TreeTable hasExpandAllControl />);
+ const headerRow = screen.getAllByRole('row')[0];
+ expect(
+ within(headerRow).getByRole('button', {name: /expand all/i}),
+ ).toBeInTheDocument();
+ });
+
+ it('expands every row when the collapsed toggle is clicked', async () => {
+ const user = userEvent.setup();
+ render(<TreeTable hasExpandAllControl />);
+
+ // Collapsed: only roots are visible.
+ expect(getBodyRows()).toHaveLength(2);
+
+ await user.click(
+ within(screen.getAllByRole('row')[0]).getByRole('button', {
+ name: /expand all/i,
+ }),
+ );
+
+ // Every level is now visible.
+ expect(
+ getBodyRows().map(r => within(r).getByText(/.+/, {selector: 'td *'})),
+ ).not.toHaveLength(2);
+ expect(screen.getByText('Button.tsx')).toBeInTheDocument();
+ });
+
+ it('relabels the toggle "Collapse all" once everything is expanded', () => {
+ render(
+ <TreeTable
+ hasExpandAllControl
+ defaultExpandedIds={['src', 'components']}
+ />,
+ );
+ const headerRow = screen.getAllByRole('row')[0];
+ expect(
+ within(headerRow).getByRole('button', {name: /collapse all/i}),
+ ).toBeInTheDocument();
+ });
+
+ it('collapses back to roots when the expanded toggle is clicked', async () => {
+ const user = userEvent.setup();
+ render(
+ <TreeTable
+ hasExpandAllControl
+ defaultExpandedIds={['src', 'components']}
+ />,
+ );
+ expect(screen.getByText('Button.tsx')).toBeInTheDocument();
+
+ await user.click(
+ within(screen.getAllByRole('row')[0]).getByRole('button', {
+ name: /collapse all/i,
+ }),
+ );
+
+ expect(getBodyRows()).toHaveLength(2);
+ expect(screen.queryByText('Button.tsx')).not.toBeInTheDocument();
+ });
+
+ it('marks the toggle aria-expanded=false in the indeterminate (partial) state', () => {
+ // 'src' expanded but 'components' not: partially expanded.
+ render(<TreeTable hasExpandAllControl defaultExpandedIds={['src']} />);
+ const headerRow = screen.getAllByRole('row')[0];
+ const toggle = within(headerRow).getByRole('button', {
+ name: /expand all/i,
+ });
+ expect(toggle).toHaveAttribute('aria-expanded', 'false');
+ });
+
+ it('does not render the control for flat data even when enabled', () => {
+ const flat: FileRow[] = [
+ {id: 'a', name: 'A', size: 1},
+ {id: 'b', name: 'B', size: 2},
+ ];
+ render(<TreeTable data={flat} hasExpandAllControl />);
+ expect(queryExpandAllButton()).toBeNull();
+ });
+
+ it('renders the toggle inline with the header label, not stacked above it', () => {
+ render(<TreeTable hasExpandAllControl />);
+ const headerRow = screen.getAllByRole('row')[0];
+ const toggle = within(headerRow).getByRole('button', {
+ name: /expand all/i,
+ });
+ // The tree column's <th> holds the label text ('Name'). The bug was that
+ // the toggle went into the `before` slot, which BaseTable renders as a
+ // block sibling of the label, stacking the chevron ABOVE the title. The
+ // fix wraps the label + toggle in one inline-flex container, so they must
+ // share the same immediate parent (the toggle is a sibling of the label,
+ // not in a separate stacked slot).
+ const th = toggle.closest('th');
+ expect(th).not.toBeNull();
+ const label = within(th as HTMLElement).getByText('Name');
+ const wrapper = label.parentElement as HTMLElement;
+ expect(wrapper).toContainElement(toggle);
+ // The toggle precedes the label within that shared wrapper (chevron sits
+ // to the LEFT of the title). StyleX compiles the inline-flex layout to a
+ // class on this wrapper; assert the class is present (real CSS is not
+ // applied in jsdom, so we check the class hook, not computed display).
+ expect(wrapper.className).not.toBe('');
+ const kids = Array.from(wrapper.childNodes);
+ expect(kids.indexOf(toggle)).toBeLessThan(
+ kids.findIndex(n => n.textContent === 'Name' || n.contains(label)),
+ );
+ });
+});
diff --git a/packages/core/src/Table/plugins/tree/useTableTreeData.tsx b/packages/core/src/Table/plugins/tree/useTableTreeData.tsx
index 4e33164b54..abb797f699 100644
--- a/packages/core/src/Table/plugins/tree/useTableTreeData.tsx
+++ b/packages/core/src/Table/plugins/tree/useTableTreeData.tsx
@@ -43,7 +43,12 @@ 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';
+import type {
+ TablePlugin,
+ TableColumn,
+ BodyRowRenderProps,
+ HeaderCellRenderProps,
+} from '../../types';
import {useTranslator} from '../../../i18n';
// =============================================================================
@@ -78,6 +83,22 @@ export interface UseTableTreeDataConfig<T extends Record<string, unknown>> {
* identically to a Table without the plugin.
*/
hasExpandableRows: boolean;
+ /**
+ * Aggregate expansion state across every expandable row. When provided
+ * together with `onExpandAll`/`onCollapseAll`, the tree column header shows
+ * an expand-all toggle. `useTableTreeState` supplies all three.
+ */
+ isAllExpanded?: boolean | 'indeterminate';
+ /** Expand every expandable row. Wired to the header expand-all control. */
+ onExpandAll?: () => void;
+ /** Collapse every row. Wired to the header expand-all control. */
+ onCollapseAll?: () => void;
+ /**
+ * Show the expand-all/collapse-all toggle in the tree column header. Needs
+ * `isAllExpanded` and `onExpandAll`/`onCollapseAll` to be present.
+ * @default false
+ */
+ hasExpandAllControl?: boolean;
/**
* Indent step per level, as spacing tokens.
* @default 'md'
@@ -243,6 +264,13 @@ const treeStyles = stylex.create({
height: '24px',
flexShrink: '0',
},
+ /** Header expand-all toggle: same affordance as a row expander. */
+ headerCell: {
+ display: 'inline-flex',
+ alignItems: 'center',
+ gap: spacingVars['--spacing-1'],
+ minWidth: 0,
+ },
});
// =============================================================================
@@ -282,6 +310,53 @@ function TreeExpander({
);
}
+/**
+ * Header expand-all/collapse-all toggle. Rendered in the tree column header
+ * when `hasExpandAllControl` is set and the state hook supplies the aggregate
+ * `isAllExpanded` plus `onExpandAll`/`onCollapseAll`. Shares the chevron
+ * affordance with the per-row expander; the chevron points down (expanded)
+ * only when every expandable row is expanded, matching the row expander.
+ */
+function TreeExpandAllToggle({
+ isAllExpanded,
+ onExpandAll,
+ onCollapseAll,
+}: {
+ isAllExpanded: boolean | 'indeterminate';
+ onExpandAll: () => void;
+ onCollapseAll: () => void;
+}) {
+ const t = useTranslator();
+ const allExpanded = isAllExpanded === true;
+ return (
+ <button
+ type="button"
+ {...stylex.props(treeStyles.expanderButton)}
+ onClick={e => {
+ e.stopPropagation();
+ if (allExpanded) {
+ onCollapseAll();
+ } else {
+ onExpandAll();
+ }
+ }}
+ aria-label={
+ allExpanded
+ ? t('@astryx.tableTree.collapseAllRows')
+ : t('@astryx.tableTree.expandAllRows')
+ }
+ aria-expanded={allExpanded}>
+ <span
+ {...stylex.props(
+ treeStyles.chevron,
+ allExpanded && treeStyles.chevronExpanded,
+ )}>
+ <Icon icon="chevronRight" size="xsm" />
+ </span>
+ </button>
+ );
+}
+
function TreeCellContent<T extends Record<string, unknown>>({
item,
children,
@@ -380,6 +455,11 @@ export function useTableTreeData<T extends Record<string, unknown>>(
output: TableColumn<T>[];
} | null>(null);
+ // The resolved tree column key, written by transformColumns (pipeline step 1)
+ // and read by transformHeaderCell (step 4) to place the expand-all toggle on
+ // the same column that carries the row expanders.
+ const treeKeyRef = useRef<string | undefined>(undefined);
+
// 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
@@ -426,6 +506,7 @@ export function useTableTreeData<T extends Record<string, unknown>>(
? treeColumnKey
: (columns.find(c => !c.key.startsWith('__'))?.key ??
columns[0]?.key);
+ treeKeyRef.current = treeKey;
// Migration guarantee: flat data renders identically to a Table
// without the plugin.
@@ -459,6 +540,52 @@ export function useTableTreeData<T extends Record<string, unknown>>(
return output;
},
+ transformHeaderCell(
+ props: HeaderCellRenderProps,
+ column: TableColumn<T>,
+ ): HeaderCellRenderProps {
+ const {
+ hasExpandableRows,
+ hasExpandAllControl,
+ isAllExpanded,
+ onExpandAll,
+ onCollapseAll,
+ } = store.getConfig();
+
+ // Only the tree column carries the toggle, and only when the control
+ // is enabled, the data is actually hierarchical, and the state hook
+ // supplied the aggregate state plus both handlers. Otherwise this is a
+ // pass-through (flat data stays a no-op).
+ if (
+ !hasExpandAllControl ||
+ !hasExpandableRows ||
+ column.key !== treeKeyRef.current ||
+ isAllExpanded === undefined ||
+ !onExpandAll ||
+ !onCollapseAll
+ ) {
+ return props;
+ }
+
+ // Wrap the header label + the toggle in one inline-flex row so the
+ // chevron sits to the LEFT of the title on the same line. BaseTable
+ // only applies its own flex row for the `after` slot, so a bare
+ // `before` would stack above the label in the block-level <th>.
+ return {
+ ...props,
+ content: (
+ <span {...stylex.props(treeStyles.headerCell)}>
+ <TreeExpandAllToggle
+ isAllExpanded={isAllExpanded}
+ onExpandAll={onExpandAll}
+ onCollapseAll={onCollapseAll}
+ />
+ {props.content}
+ </span>
+ ),
+ };
+ },
+
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
diff --git a/packages/core/src/Table/plugins/tree/useTableTreeState.test.tsx b/packages/core/src/Table/plugins/tree/useTableTreeState.test.tsx
index 459dc44349..bfdf987de4 100644
--- a/packages/core/src/Table/plugins/tree/useTableTreeState.test.tsx
+++ b/packages/core/src/Table/plugins/tree/useTableTreeState.test.tsx
@@ -634,3 +634,107 @@ describe('useTableTreeState — semantics edges', () => {
expect(ids(result.current.visibleData)).toEqual(['src', 'readme']);
});
});
+
+// =============================================================================
+// isAllExpanded (drives the header expand-all control)
+// =============================================================================
+
+describe('useTableTreeState: isAllExpanded', () => {
+ it('reports false when nothing is expanded', () => {
+ const {result} = renderHook(() =>
+ useTableTreeState({data: fileTree, idKey: 'id'}),
+ );
+
+ expect(result.current.isAllExpanded).toBe(false);
+ });
+
+ it('reports true only when every expandable row is expanded', () => {
+ const {result} = renderHook(() =>
+ useTableTreeState({data: fileTree, idKey: 'id'}),
+ );
+
+ act(() => {
+ result.current.expandAll();
+ });
+
+ expect(result.current.isAllExpanded).toBe(true);
+ });
+
+ it("reports 'indeterminate' when some but not all expandable rows are expanded", () => {
+ const {result} = renderHook(() =>
+ useTableTreeState({
+ data: fileTree,
+ idKey: 'id',
+ defaultExpandedIds: ['src'],
+ }),
+ );
+
+ // 'src' and 'components' are both expandable; only 'src' is expanded.
+ expect(result.current.isAllExpanded).toBe('indeterminate');
+ });
+
+ it('returns to false after collapseAll', () => {
+ const {result} = renderHook(() =>
+ useTableTreeState({
+ data: fileTree,
+ idKey: 'id',
+ defaultExpandedIds: ['src', 'components'],
+ }),
+ );
+
+ act(() => {
+ result.current.collapseAll();
+ });
+
+ expect(result.current.isAllExpanded).toBe(false);
+ });
+
+ it('reports false for flat data (no expandable rows)', () => {
+ 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.isAllExpanded).toBe(false);
+ });
+
+ it('ignores expanded ids that match no expandable row when aggregating', () => {
+ // 'readme' is a leaf (not expandable) and 'ghost' matches nothing; neither
+ // should count toward the expandable total, so an all-expandable set that
+ // omits them still reads as fully expanded.
+ const {result} = renderHook(() =>
+ useTableTreeState({
+ data: fileTree,
+ idKey: 'id',
+ defaultExpandedIds: ['src', 'components', 'readme', 'ghost'],
+ }),
+ );
+
+ expect(result.current.isAllExpanded).toBe(true);
+ });
+
+ it('exposes the aggregate state and expand/collapse handlers through treeConfig', () => {
+ const {result} = renderHook(() =>
+ useTableTreeState({data: fileTree, idKey: 'id'}),
+ );
+
+ // The headless plugin reads everything it needs to render the header
+ // expand-all control from treeConfig, not from the state hook directly.
+ expect(result.current.treeConfig.isAllExpanded).toBe(false);
+
+ act(() => {
+ result.current.treeConfig.onExpandAll?.();
+ });
+ expect(result.current.isAllExpanded).toBe(true);
+ expect(result.current.treeConfig.isAllExpanded).toBe(true);
+
+ act(() => {
+ result.current.treeConfig.onCollapseAll?.();
+ });
+ expect(result.current.isAllExpanded).toBe(false);
+ expect(result.current.treeConfig.isAllExpanded).toBe(false);
+ });
+});
diff --git a/packages/core/src/Table/plugins/tree/useTableTreeState.tsx b/packages/core/src/Table/plugins/tree/useTableTreeState.tsx
index dffeedc1d9..797eed925d 100644
--- a/packages/core/src/Table/plugins/tree/useTableTreeState.tsx
+++ b/packages/core/src/Table/plugins/tree/useTableTreeState.tsx
@@ -74,6 +74,12 @@ export interface UseTableTreeStateResult<T extends Record<string, unknown>> {
treeConfig: UseTableTreeDataConfig<T>;
/** The current expanded row ids. */
expandedIds: ReadonlySet<string>;
+ /**
+ * Aggregate expansion state across every expandable row: `true` when all are
+ * expanded, `false` when none are, `'indeterminate'` when some but not all
+ * are. Drives the header expand-all control. Reports `false` for flat data.
+ */
+ isAllExpanded: boolean | 'indeterminate';
/** Expand every expandable row in the tree. */
expandAll: () => void;
/** Collapse every row. */
@@ -211,6 +217,25 @@ export function useTableTreeState<T extends Record<string, unknown>>(
const hasExpandableRows = allExpandableIds.length > 0;
+ // Aggregate state for the header expand-all control. Only expandable ids
+ // count toward the total, so expanded ids that match a leaf or no row at
+ // all never skew the tally.
+ const isAllExpanded: boolean | 'indeterminate' = useMemo(() => {
+ if (!hasExpandableRows) {
+ return false;
+ }
+ const expandedCount = allExpandableIds.filter(id =>
+ expandedIds.has(id),
+ ).length;
+ if (expandedCount === 0) {
+ return false;
+ }
+ if (expandedCount === allExpandableIds.length) {
+ return true;
+ }
+ return 'indeterminate';
+ }, [hasExpandableRows, allExpandableIds, expandedIds]);
+
const onToggleItem = useCallback(
(item: T) => {
const id = getId(item);
@@ -243,11 +268,30 @@ export function useTableTreeState<T extends Record<string, unknown>>(
getRowMeta,
onToggleItem,
hasExpandableRows,
+ isAllExpanded,
+ onExpandAll: expandAll,
+ onCollapseAll: collapseAll,
indent,
treeColumnKey,
}),
- [getRowMeta, onToggleItem, hasExpandableRows, indent, treeColumnKey],
+ [
+ getRowMeta,
+ onToggleItem,
+ hasExpandableRows,
+ isAllExpanded,
+ expandAll,
+ collapseAll,
+ indent,
+ treeColumnKey,
+ ],
);
- return {visibleData, treeConfig, expandedIds, expandAll, collapseAll};
+ return {
+ visibleData,
+ treeConfig,
+ expandedIds,
+ isAllExpanded,
+ expandAll,
+ collapseAll,
+ };
}
diff --git a/packages/core/src/Table/useTableTreeData.doc.mjs b/packages/core/src/Table/useTableTreeData.doc.mjs
index 85ad0d103f..321bfde7be 100644
--- a/packages/core/src/Table/useTableTreeData.doc.mjs
+++ b/packages/core/src/Table/useTableTreeData.doc.mjs
@@ -29,6 +29,29 @@ export const docs = {
'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: 'hasExpandAllControl',
+ type: 'boolean',
+ description:
+ 'Show an expand-all/collapse-all toggle in the tree column header. Requires isAllExpanded plus onExpandAll/onCollapseAll (all supplied by useTableTreeState).',
+ default: 'false',
+ },
+ {
+ name: 'isAllExpanded',
+ type: "boolean | 'indeterminate'",
+ description:
+ 'Aggregate expansion state across every expandable row, driving the header expand-all toggle. true when all are expanded, false when none are, indeterminate when some are.',
+ },
+ {
+ name: 'onExpandAll',
+ type: '() => void',
+ description: 'Expand every expandable row. Wired to the header control.',
+ },
+ {
+ name: 'onCollapseAll',
+ type: '() => void',
+ description: 'Collapse every row. Wired to the header control.',
+ },
{
name: 'indent',
type: "'sm' | 'md' | 'lg'",
@@ -71,5 +94,11 @@ export const docsDense = {
indent:
"indent step per level: 'sm' | 'md' | 'lg' (spacing-3/4/6). Defaults to 'md'.",
treeColumnKey: 'column carrying indent + expander. Defaults to first column.',
+ hasExpandAllControl:
+ 'show expand-all/collapse-all toggle in tree column header. Needs isAllExpanded + onExpandAll/onCollapseAll (from useTableTreeState). Defaults to false.',
+ isAllExpanded:
+ "aggregate state driving the header toggle: true (all) | false (none) | 'indeterminate' (some).",
+ onExpandAll: 'expand every expandable row (header control)',
+ onCollapseAll: 'collapse every row (header control)',
},
};
diff --git a/packages/core/src/Table/useTableTreeState.doc.mjs b/packages/core/src/Table/useTableTreeState.doc.mjs
index 1110a5aa68..09f2a29c15 100644
--- a/packages/core/src/Table/useTableTreeState.doc.mjs
+++ b/packages/core/src/Table/useTableTreeState.doc.mjs
@@ -7,7 +7,7 @@ export const docs = {
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.',
+ '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, the aggregate isAllExpanded state (true/false/indeterminate) for a header expand-all control, 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',
@@ -79,7 +79,7 @@ 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.',
+ '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, isAllExpanded, expandAll, collapseAll} (isAllExpanded = true/false/indeterminate for a header expand-all control). 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',