Skip to content

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

TypeScript

feat(core): make useTableRowExpansion a detail-panel plugin (#4142) (#4609)

Humberto Virtudes52a0e0e30cc5
diff --git a/.changeset/row-expansion-detail-panel.md b/.changeset/row-expansion-detail-panel.md
new file mode 100644
index 0000000000..953367fd31
--- /dev/null
+++ b/.changeset/row-expansion-detail-panel.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': minor
+---
+
+[breaking] useTableRowExpansion is now a detail-panel plugin: it expands a full-width panel below a row via renderExpanded(item), and useTableRowExpansionState is removed. For hierarchical/tree tables (child rows that reuse the parent columns), migrate to useTableTreeData + useTableTreeState. See the migration example on the useTableRowExpansion docs.
+
+@humbertovirtudes
diff --git a/apps/sandbox/src/app/(sandbox)/pages/table-lab/page.tsx b/apps/sandbox/src/app/(sandbox)/pages/table-lab/page.tsx
index 141f0a5931..7cb8ccae66 100644
--- a/apps/sandbox/src/app/(sandbox)/pages/table-lab/page.tsx
+++ b/apps/sandbox/src/app/(sandbox)/pages/table-lab/page.tsx
@@ -46,7 +46,6 @@ import {
useTableColumnResize,
useTableStickyColumns,
useTableRowExpansion,
- useTableRowExpansionState,
useTableGroupedRows,
useTableRowIndex,
useTableRowStatus,
@@ -205,16 +204,27 @@ function useLabPlugins({
endKeys: ['joined'],
});
- // --- row expansion (flat rows; no real tree in the synthetic data) ---
+ // --- row expansion (detail panel below the row) ---
const [expandedKeys, setExpandedKeys] = useState<Set<string>>(new Set());
- const {expansionConfig} = useTableRowExpansionState<LabRow>({
- baseData: dataAfterPage,
- getChildren: () => [],
- getRowKey: item => item.id,
+ const rowExpansionPlugin = useTableRowExpansion<LabRow>({
expandedKeys,
- setExpandedKeys,
+ onToggle: key =>
+ setExpandedKeys(prev => {
+ const next = new Set(prev);
+ if (next.has(key)) {
+ next.delete(key);
+ } else {
+ next.add(key);
+ }
+ return next;
+ }),
+ getRowKey: item => item.id,
+ renderExpanded: item => (
+ <Text type="body" color="secondary">
+ {`Details for ${item.name}`}
+ </Text>
+ ),
});
- const rowExpansionPlugin = useTableRowExpansion(expansionConfig);
if (enabled.rowExpansion) {
summary.push(`${expandedKeys.size} expanded`);
}
diff --git a/apps/storybook/stories/TableRowExpansion.stories.tsx b/apps/storybook/stories/TableRowExpansion.stories.tsx
index be1f12c54d..93be197c4f 100644
--- a/apps/storybook/stories/TableRowExpansion.stories.tsx
+++ b/apps/storybook/stories/TableRowExpansion.stories.tsx
@@ -5,143 +5,91 @@ import type {Meta, StoryObj} from '@storybook/react';
import {
Table,
useTableRowExpansion,
- useTableRowExpansionState,
pixel,
proportional,
} from '@astryxdesign/core/Table';
import type {TableColumn} from '@astryxdesign/core/Table';
+import {VStack, HStack} from '@astryxdesign/core/Stack';
+import {Text, Heading} from '@astryxdesign/core/Text';
+import {Badge} from '@astryxdesign/core/Badge';
// =============================================================================
-// Sample Data — tree structure (file system)
+// Sample Data: orders with expandable detail panels
// =============================================================================
-interface FileNode extends Record<string, unknown> {
+interface Order extends Record<string, unknown> {
id: string;
- name: string;
- type: 'folder' | 'file';
- size: string;
- modified: string;
- children?: FileNode[];
+ customer: string;
+ status: string;
+ total: string;
+ placed: string;
+ items: {name: string; qty: number; price: string}[];
}
-const fileTree: FileNode[] = [
+const orders: Order[] = [
{
- id: 'src',
- name: 'src',
- type: 'folder',
- size: '—',
- modified: '2026-06-20',
- children: [
- {
- id: 'src/components',
- name: 'components',
- type: 'folder',
- size: '—',
- modified: '2026-06-19',
- children: [
- {
- id: 'src/components/Button.tsx',
- name: 'Button.tsx',
- type: 'file',
- size: '4.2 KB',
- modified: '2026-06-18',
- children: [],
- },
- {
- id: 'src/components/Table.tsx',
- name: 'Table.tsx',
- type: 'file',
- size: '12.8 KB',
- modified: '2026-06-20',
- children: [],
- },
- {
- id: 'src/components/Dialog.tsx',
- name: 'Dialog.tsx',
- type: 'file',
- size: '6.1 KB',
- modified: '2026-06-15',
- children: [],
- },
- ],
- },
- {
- id: 'src/utils',
- name: 'utils',
- type: 'folder',
- size: '—',
- modified: '2026-06-17',
- children: [
- {
- id: 'src/utils/format.ts',
- name: 'format.ts',
- type: 'file',
- size: '1.3 KB',
- modified: '2026-06-17',
- children: [],
- },
- {
- id: 'src/utils/merge.ts',
- name: 'merge.ts',
- type: 'file',
- size: '0.8 KB',
- modified: '2026-06-10',
- children: [],
- },
- ],
- },
- {
- id: 'src/index.ts',
- name: 'index.ts',
- type: 'file',
- size: '0.4 KB',
- modified: '2026-06-20',
- children: [],
- },
+ id: 'ord-1001',
+ customer: 'Ada Lovelace',
+ status: 'Shipped',
+ total: '$248.00',
+ placed: '2026-06-20',
+ items: [
+ {name: 'Mechanical keyboard', qty: 1, price: '$180.00'},
+ {name: 'Wrist rest', qty: 2, price: '$34.00'},
],
},
{
- id: 'public',
- name: 'public',
- type: 'folder',
- size: '—',
- modified: '2026-06-01',
- children: [
- {
- id: 'public/favicon.ico',
- name: 'favicon.ico',
- type: 'file',
- size: '15 KB',
- modified: '2026-05-20',
- children: [],
- },
- ],
- },
- {
- id: 'package.json',
- name: 'package.json',
- type: 'file',
- size: '1.8 KB',
- modified: '2026-06-22',
- children: [],
+ id: 'ord-1002',
+ customer: 'Alan Turing',
+ status: 'Processing',
+ total: '$52.00',
+ placed: '2026-06-21',
+ items: [{name: 'USB-C cable', qty: 4, price: '$13.00'}],
},
{
- id: 'tsconfig.json',
- name: 'tsconfig.json',
- type: 'file',
- size: '0.6 KB',
- modified: '2026-06-01',
- children: [],
+ id: 'ord-1003',
+ customer: 'Grace Hopper',
+ status: 'Delivered',
+ total: '$1,200.00',
+ placed: '2026-06-18',
+ items: [{name: 'Standing desk', qty: 1, price: '$1,200.00'}],
},
];
-const columns: TableColumn<FileNode>[] = [
- {key: 'name', header: 'Name', width: proportional(2)},
- {key: 'type', header: 'Type', width: pixel(80)},
- {key: 'size', header: 'Size', width: pixel(90)},
- {key: 'modified', header: 'Modified', width: pixel(120)},
+const columns: TableColumn<Order>[] = [
+ {key: 'customer', header: 'Customer', width: proportional(2)},
+ {key: 'status', header: 'Status', width: pixel(130)},
+ {key: 'total', header: 'Total', width: pixel(110)},
+ {key: 'placed', header: 'Placed', width: pixel(120)},
];
+function OrderItems({order}: {order: Order}) {
+ return (
+ <VStack gap={2}>
+ <Heading level={4}>Line items</Heading>
+ {order.items.map(line => (
+ <HStack key={line.name} gap={3}>
+ <Badge label={`x${line.qty}`} variant="info" />
+ <Text type="body">{line.name}</Text>
+ <Text type="body" color="secondary">
+ {line.price}
+ </Text>
+ </HStack>
+ ))}
+ </VStack>
+ );
+}
+
+function toggleKey(keys: Set<string>, key: string): Set<string> {
+ const next = new Set(keys);
+ if (next.has(key)) {
+ next.delete(key);
+ } else {
+ next.add(key);
+ }
+ return next;
+}
+
// =============================================================================
// Stories
// =============================================================================
@@ -155,65 +103,30 @@ export default meta;
type Story = StoryObj;
/**
- * A file tree rendered as a table with expandable folder rows. Child rows
- * inherit the parent's columns and are indented based on depth. Click the
- * chevron (or right-click → "Expand/Collapse row") to expand a folder.
+ * Each row expands a full-width detail panel below it, rendered by
+ * `renderExpanded(item)`. Click the chevron (or right-click, then
+ * "Expand/Collapse row") to toggle the panel. The consumer owns the
+ * `expandedKeys` set.
+ *
+ * For hierarchical data (child rows that reuse the parent columns), use
+ * `useTableTreeData` + `useTableTreeState` instead.
*/
-export const InheritedColumns: Story = {
+export const DetailPanel: Story = {
render: () => {
const [expandedKeys, setExpandedKeys] = useState<Set<string>>(
- new Set(['src']),
+ new Set(['ord-1001']),
);
- // The state hook flattens the tree, tracks depth, and derives the
- // expand/collapse + expand-all handlers — no boilerplate in the consumer.
- const {data, expansionConfig} = useTableRowExpansionState<FileNode>({
- baseData: fileTree,
- getChildren: item => item.children ?? [],
- getRowKey: item => item.id,
+ const expansion = useTableRowExpansion<Order>({
expandedKeys,
- setExpandedKeys,
- });
-
- const expansion = useTableRowExpansion(expansionConfig);
-
- return (
- <Table
- data={data}
- columns={columns}
- idKey="id"
- hasHover
- plugins={{expansion}}
- />
- );
- },
-};
-
-/**
- * Only folders are expandable (files have no children). The chevron and
- * context-menu action are hidden for leaf nodes.
- */
-export const LeafNodesNotExpandable: Story = {
- render: () => {
- const [expandedKeys, setExpandedKeys] = useState<Set<string>>(
- new Set(['src', 'src/components']),
- );
-
- // `getIsItemExpandable` restricts expandability (and expand-all) to folders.
- const {data, expansionConfig} = useTableRowExpansionState<FileNode>({
- baseData: fileTree,
- getChildren: item => item.children ?? [],
+ onToggle: key => setExpandedKeys(prev => toggleKey(prev, key)),
getRowKey: item => item.id,
- getIsItemExpandable: item => item.type === 'folder',
- expandedKeys,
- setExpandedKeys,
+ renderExpanded: item => <OrderItems order={item} />,
});
- const expansion = useTableRowExpansion(expansionConfig);
-
return (
<Table
- data={data}
+ data={orders}
columns={columns}
idKey="id"
hasHover
@@ -224,30 +137,25 @@ export const LeafNodesNotExpandable: Story = {
};
/**
- * `hasRowClickExpansion: true` — clicking anywhere on the row toggles expansion
- * (in addition to the chevron). The row shows a pointer cursor.
+ * `getIsItemExpandable` restricts which rows can expand. Here only orders with
+ * more than one line item are expandable; the rest show no chevron and no
+ * context-menu action.
*/
-export const ExpandOnRowClick: Story = {
+export const NotAllRowsExpandable: Story = {
render: () => {
const [expandedKeys, setExpandedKeys] = useState<Set<string>>(new Set());
- const {data, expansionConfig} = useTableRowExpansionState<FileNode>({
- baseData: fileTree,
- getChildren: item => item.children ?? [],
- getRowKey: item => item.id,
+ const expansion = useTableRowExpansion<Order>({
expandedKeys,
- setExpandedKeys,
- });
-
- // Opt into row-click expansion by extending the derived config.
- const expansion = useTableRowExpansion({
- ...expansionConfig,
- hasRowClickExpansion: true,
+ onToggle: key => setExpandedKeys(prev => toggleKey(prev, key)),
+ getRowKey: item => item.id,
+ getIsItemExpandable: item => item.items.length > 1,
+ renderExpanded: item => <OrderItems order={item} />,
});
return (
<Table
- data={data}
+ data={orders}
columns={columns}
idKey="id"
hasHover
diff --git a/packages/cli/assets/templates/blocks/components/Table/TableRowExpansionTable.tsx b/packages/cli/assets/templates/blocks/components/Table/TableRowExpansionTable.tsx
index d404f1c509..39f1b237f3 100644
--- a/packages/cli/assets/templates/blocks/components/Table/TableRowExpansionTable.tsx
+++ b/packages/cli/assets/templates/blocks/components/Table/TableRowExpansionTable.tsx
@@ -6,90 +6,93 @@ import {useState} from 'react';
import {
Table,
useTableRowExpansion,
- useTableRowExpansionState,
proportional,
pixel,
} from '@astryxdesign/core/Table';
+import {VStack, HStack} from '@astryxdesign/core/Stack';
+import {Text, Heading} from '@astryxdesign/core/Text';
+import {Badge} from '@astryxdesign/core/Badge';
-interface FileNode extends Record<string, unknown> {
+interface Order extends Record<string, unknown> {
id: string;
- name: string;
- type: 'folder' | 'file';
- size: string;
- children?: FileNode[];
+ customer: string;
+ status: string;
+ total: string;
+ items: {name: string; qty: number; price: string}[];
}
-const fileTree: FileNode[] = [
+const orders: Order[] = [
{
- id: 'src',
- name: 'src',
- type: 'folder',
- size: '—',
- children: [
- {
- id: 'src/components',
- name: 'components',
- type: 'folder',
- size: '—',
- children: [
- {
- id: 'src/components/Button.tsx',
- name: 'Button.tsx',
- type: 'file',
- size: '4.2 KB',
- children: [],
- },
- {
- id: 'src/components/Table.tsx',
- name: 'Table.tsx',
- type: 'file',
- size: '12.8 KB',
- children: [],
- },
- ],
- },
- {
- id: 'src/index.ts',
- name: 'index.ts',
- type: 'file',
- size: '0.4 KB',
- children: [],
- },
+ id: 'ord-1001',
+ customer: 'Ada Lovelace',
+ status: 'Shipped',
+ total: '$248.00',
+ items: [
+ {name: 'Mechanical keyboard', qty: 1, price: '$180.00'},
+ {name: 'Wrist rest', qty: 2, price: '$34.00'},
],
},
{
- id: 'package.json',
- name: 'package.json',
- type: 'file',
- size: '1.8 KB',
- children: [],
+ id: 'ord-1002',
+ customer: 'Alan Turing',
+ status: 'Processing',
+ total: '$52.00',
+ items: [{name: 'USB-C cable', qty: 4, price: '$13.00'}],
+ },
+ {
+ id: 'ord-1003',
+ customer: 'Grace Hopper',
+ status: 'Delivered',
+ total: '$1,200.00',
+ items: [{name: 'Standing desk', qty: 1, price: '$1,200.00'}],
},
];
const columns = [
- {key: 'name', header: 'Name', width: proportional(2)},
- {key: 'type', header: 'Type', width: pixel(80)},
- {key: 'size', header: 'Size', width: pixel(90)},
+ {key: 'customer', header: 'Customer', width: proportional(2)},
+ {key: 'status', header: 'Status', width: pixel(130)},
+ {key: 'total', header: 'Total', width: pixel(110)},
];
export default function TableRowExpansionTable() {
const [expandedKeys, setExpandedKeys] = useState<Set<string>>(
- new Set(['src']),
+ new Set(['ord-1001']),
);
- const {data, expansionConfig} = useTableRowExpansionState<FileNode>({
- baseData: fileTree,
- getChildren: item => item.children ?? [],
- getRowKey: item => item.id,
+ const expansion = useTableRowExpansion<Order>({
expandedKeys,
- setExpandedKeys,
+ onToggle: key =>
+ setExpandedKeys(prev => {
+ const next = new Set(prev);
+ if (next.has(key)) {
+ next.delete(key);
+ } else {
+ next.add(key);
+ }
+ return next;
+ }),
+ getRowKey: item => item.id,
+ // The detail panel renders arbitrary content below the row: here, the
+ // order's line items. Any component composes here (charts, forms, tables).
+ renderExpanded: item => (
+ <VStack gap={2}>
+ <Heading level={4}>Line items</Heading>
+ {item.items.map(line => (
+ <HStack key={line.name} gap={3}>
+ <Badge label={`x${line.qty}`} variant="info" />
+ <Text type="body">{line.name}</Text>
+ <Text type="body" color="secondary">
+ {line.price}
+ </Text>
+ </HStack>
+ ))}
+ </VStack>
+ ),
});
- const expansion = useTableRowExpansion(expansionConfig);
-
return (
<Table
- data={data}
+ data={orders}
columns={columns}
idKey="id"
hasHover
diff --git a/packages/core/src/Table/BaseTable.tsx b/packages/core/src/Table/BaseTable.tsx
index fb18469f5c..2420413be5 100644
--- a/packages/core/src/Table/BaseTable.tsx
+++ b/packages/core/src/Table/BaseTable.tsx
@@ -243,6 +243,17 @@ function TableRowInner<T extends Record<string, unknown>>({
</RowComponent>
);
+ // afterRow: plugins (e.g. row expansion) can append a full-width detail
+ // panel `<tr>` after the row. Rendered as a sibling fragment.
+ if (rowRenderProps.afterRow) {
+ return (
+ <>
+ {row}
+ {rowRenderProps.afterRow}
+ </>
+ );
+ }
+
return row;
}
diff --git a/packages/core/src/Table/index.ts b/packages/core/src/Table/index.ts
index 9f9f731121..20e6b4c743 100644
--- a/packages/core/src/Table/index.ts
+++ b/packages/core/src/Table/index.ts
@@ -28,11 +28,8 @@ export {useTableColumnResize} from './plugins/columnResize';
export {useTableStickyColumns} from './plugins/stickyColumns';
export {useTableGroupedRows} from './plugins/groupedRows';
export {useTableRowIndex} from './plugins/rowIndex';
-export {
- useTableRowExpansion,
- useTableRowExpansionState,
-} from './plugins/rowExpansion';
export {useTableRowStatus} from './plugins/rowStatus';
+export {useTableRowExpansion} from './plugins/rowExpansion';
export {useTableTreeData, useTableTreeState} from './plugins/tree';
export {resolveContextActions} from './tableContextMenu';
export {
diff --git a/packages/core/src/Table/plugins/groupedRows/useTableGroupedRows.tsx b/packages/core/src/Table/plugins/groupedRows/useTableGroupedRows.tsx
index 28c37600f9..6c1b4a5e14 100644
--- a/packages/core/src/Table/plugins/groupedRows/useTableGroupedRows.tsx
+++ b/packages/core/src/Table/plugins/groupedRows/useTableGroupedRows.tsx
@@ -190,7 +190,7 @@ const styles = stylex.create({
* data rows while keeping the header visible.
*
* Mirrors other controlled Table state helpers: the consumer owns the
- * `collapsedGroups` set and this hook returns `{data, plugin, idKey}` —
+ * `collapsedGroups` set and this hook returns `{data, plugin, idKey}`:
* pass all three to `<Table>`.
*
* @example
diff --git a/packages/core/src/Table/plugins/rowExpansion/index.ts b/packages/core/src/Table/plugins/rowExpansion/index.ts
index ec9f08a7bf..c1b34fd2b3 100644
--- a/packages/core/src/Table/plugins/rowExpansion/index.ts
+++ b/packages/core/src/Table/plugins/rowExpansion/index.ts
@@ -1,7 +1,4 @@
// Copyright (c) Meta Platforms, Inc. and affiliates.
-export {
- useTableRowExpansion,
- useTableRowExpansionState,
-} from './useTableRowExpansion';
+export {useTableRowExpansion} from './useTableRowExpansion';
export type {UseTableRowExpansionConfig} from './useTableRowExpansion';
diff --git a/packages/core/src/Table/plugins/rowExpansion/useTableRowExpansion.test.tsx b/packages/core/src/Table/plugins/rowExpansion/useTableRowExpansion.test.tsx
index 2c040a8e28..a6f4befd9d 100644
--- a/packages/core/src/Table/plugins/rowExpansion/useTableRowExpansion.test.tsx
+++ b/packages/core/src/Table/plugins/rowExpansion/useTableRowExpansion.test.tsx
@@ -1,14 +1,11 @@
// Copyright (c) Meta Platforms, Inc. and affiliates.
import {describe, it, expect, vi, beforeEach} from 'vitest';
-import {render, renderHook, screen, fireEvent} from '@testing-library/react';
+import {render, screen, fireEvent} from '@testing-library/react';
import {useState} from 'react';
import {Table} from '../../Table';
import type {TableColumn} from '../../types';
-import {
- useTableRowExpansion,
- useTableRowExpansionState,
-} from './useTableRowExpansion';
+import {useTableRowExpansion} from './useTableRowExpansion';
import {InternationalizationProvider} from '../../../i18n';
// popover mock for context-menu tests
@@ -37,227 +34,180 @@ beforeEach(() => {
};
});
-interface TreeItem extends Record<string, unknown> {
+interface Row extends Record<string, unknown> {
id: string;
name: string;
- children: TreeItem[];
+ bio: string;
}
-const treeData: TreeItem[] = [
- {
- id: 'a',
- name: 'Folder A',
- children: [
- {id: 'a1', name: 'File A1', children: []},
- {id: 'a2', name: 'File A2', children: []},
- ],
- },
- {
- id: 'b',
- name: 'Folder B',
- children: [{id: 'b1', name: 'File B1', children: []}],
- },
- {id: 'c', name: 'Leaf C', children: []},
+const rows: Row[] = [
+ {id: 'a', name: 'Ada', bio: 'Ada bio'},
+ {id: 'b', name: 'Bo', bio: 'Bo bio'},
+ {id: 'c', name: 'Cy', bio: 'Cy bio'},
];
-const columns: TableColumn<TreeItem>[] = [{key: 'name', header: 'Name'}];
+const columns: TableColumn<Row>[] = [{key: 'name', header: 'Name'}];
const EMPTY_KEYS = new Set<string>();
+const defaultRenderExpanded = (item: Row) => (
+ <div data-testid="panel">{`${item.name}: ${item.bio}`}</div>
+);
+
function Harness({
initialExpanded = EMPTY_KEYS,
+ isItemExpandable,
+ renderExpanded = defaultRenderExpanded,
}: {
initialExpanded?: Set<string>;
+ isItemExpandable?: (item: Row) => boolean;
+ renderExpanded?: (item: Row) => React.ReactNode;
}) {
const [expandedKeys, setExpandedKeys] = useState(initialExpanded);
- const {data, expansionConfig} = useTableRowExpansionState<TreeItem>({
- baseData: treeData,
- getChildren: item => item.children,
- getRowKey: item => item.id,
+ const expansion = useTableRowExpansion<Row>({
expandedKeys,
- setExpandedKeys,
+ onToggle: key =>
+ setExpandedKeys(prev => {
+ const next = new Set(prev);
+ if (next.has(key)) {
+ next.delete(key);
+ } else {
+ next.add(key);
+ }
+ return next;
+ }),
+ getRowKey: item => item.id,
+ renderExpanded,
+ getIsItemExpandable: isItemExpandable,
});
- const expansion = useTableRowExpansion(expansionConfig);
return (
- <Table data={data} columns={columns} idKey="id" plugins={{expansion}} />
+ <Table data={rows} columns={columns} idKey="id" plugins={{expansion}} />
);
}
-describe('useTableRowExpansion', () => {
- it('renders a chevron button for expandable rows', () => {
+describe('useTableRowExpansion (detail panel)', () => {
+ it('renders an "Expand row" chevron button for every expandable row', () => {
render(<Harness />);
- const buttons = screen.getAllByRole('button', {name: /expand row/i});
- // Folder A and Folder B are expandable (top-level with children)
- expect(buttons.length).toBe(2);
- });
-
- it('shows child rows when expanded', () => {
- render(<Harness initialExpanded={new Set(['a'])} />);
- expect(screen.getByText('File A1')).toBeInTheDocument();
- expect(screen.getByText('File A2')).toBeInTheDocument();
- });
-
- it('hides child rows when collapsed', () => {
- render(<Harness />);
- expect(screen.queryByText('File A1')).not.toBeInTheDocument();
+ expect(screen.getAllByRole('button', {name: /expand row/i})).toHaveLength(
+ 3,
+ );
});
- it('toggles expansion on chevron click', () => {
+ it('does not render the detail panel while collapsed', () => {
render(<Harness />);
- expect(screen.queryByText('File A1')).not.toBeInTheDocument();
- fireEvent.click(screen.getAllByRole('button', {name: /expand row/i})[0]);
- expect(screen.getByText('File A1')).toBeInTheDocument();
+ expect(screen.queryByTestId('panel')).not.toBeInTheDocument();
});
- it('contributes a context-menu action on expandable rows', () => {
- render(<Harness />);
- fireEvent.contextMenu(screen.getByText('Folder A'));
- const items = screen.getAllByRole('menuitem', {
- name: /expand row/i,
- hidden: true,
- });
- expect(items.length).toBeGreaterThan(0);
+ it('renders the detail panel below the row when expanded', () => {
+ render(<Harness initialExpanded={new Set(['a'])} />);
+ const panel = screen.getByTestId('panel');
+ expect(panel).toBeInTheDocument();
+ expect(panel).toHaveTextContent('Ada: Ada bio');
});
- it('localizes the context-menu action label through the i18n catalog', () => {
+ it('renders renderExpanded content with the row item', () => {
render(
- <InternationalizationProvider
- locale="fr"
- overrides={{
- fr: {'@astryx.tableRowExpansion.expandRow': 'Développer la ligne'},
- }}>
- <Harness />
- </InternationalizationProvider>,
+ <Harness
+ initialExpanded={new Set(['b'])}
+ renderExpanded={item => <span data-testid="panel">bio={item.bio}</span>}
+ />,
);
- fireEvent.contextMenu(screen.getByText('Folder A'));
- const items = screen.getAllByRole('menuitem', {
- name: /Développer la ligne/,
- hidden: true,
- });
- expect(items.length).toBeGreaterThan(0);
+ expect(screen.getByTestId('panel')).toHaveTextContent('bio=Bo bio');
});
- it('does not show chevron for leaf nodes', () => {
+ it('toggles the panel open on chevron click', () => {
render(<Harness />);
- // Leaf C has no children
- expect(screen.getByText('Leaf C')).toBeInTheDocument();
- // only 2 expand buttons (Folder A, Folder B), not 3
- expect(
- screen.getAllByRole('button', {name: /expand row|collapse row/i}).length,
- ).toBe(2);
+ expect(screen.queryByTestId('panel')).not.toBeInTheDocument();
+ fireEvent.click(screen.getAllByRole('button', {name: /expand row/i})[0]);
+ expect(screen.getByTestId('panel')).toBeInTheDocument();
});
- it('renders an expand-all toggle in the header', () => {
- render(<Harness />);
- expect(
- screen.getByRole('button', {name: /expand all rows/i}),
- ).toBeInTheDocument();
+ it('relabels the chevron "Collapse row" and sets aria-expanded when open', () => {
+ render(<Harness initialExpanded={new Set(['a'])} />);
+ const collapse = screen.getByRole('button', {name: /collapse row/i});
+ expect(collapse).toHaveAttribute('aria-expanded', 'true');
});
- it('expand-all toggle expands every expandable row', () => {
+ it('marks the chevron aria-expanded=false when collapsed', () => {
render(<Harness />);
- expect(screen.queryByText('File A1')).not.toBeInTheDocument();
- fireEvent.click(screen.getByRole('button', {name: /expand all rows/i}));
- // Both folders' children become visible.
- expect(screen.getByText('File A1')).toBeInTheDocument();
- expect(screen.getByText('File A2')).toBeInTheDocument();
- expect(screen.getByText('File B1')).toBeInTheDocument();
+ expect(
+ screen.getAllByRole('button', {name: /expand row/i})[0],
+ ).toHaveAttribute('aria-expanded', 'false');
});
- it('collapse-all toggle collapses every row', () => {
- render(<Harness initialExpanded={new Set(['a', 'b'])} />);
- expect(screen.getByText('File A1')).toBeInTheDocument();
- fireEvent.click(screen.getByRole('button', {name: /collapse all rows/i}));
- expect(screen.queryByText('File A1')).not.toBeInTheDocument();
- expect(screen.queryByText('File B1')).not.toBeInTheDocument();
+ it('renders one detail panel per expanded row', () => {
+ render(<Harness initialExpanded={new Set(['a', 'c'])} />);
+ expect(screen.getAllByTestId('panel')).toHaveLength(2);
});
-});
-
-describe('useTableRowExpansionState cycle guard', () => {
- /** A row whose children array contains the row itself (plus a real child). */
- function makeSelfReferential(): TreeItem[] {
- const x: TreeItem = {id: 'x', name: 'Self', children: []};
- const y: TreeItem = {id: 'y', name: 'Leaf Y', children: []};
- x.children.push(x, y);
- return [x];
- }
-
- /** root -> child -> grand, where grand's children point back at root. */
- function makeDeepCycle(): TreeItem[] {
- const root: TreeItem = {id: 'root', name: 'Root', children: []};
- const child: TreeItem = {id: 'child', name: 'Child', children: []};
- const grand: TreeItem = {id: 'grand', name: 'Grand', children: []};
- root.children.push(child);
- child.children.push(grand);
- grand.children.push(root);
- return [root];
- }
- function renderState(baseData: TreeItem[], expandedKeys: Set<string>) {
- const setExpandedKeys = vi.fn();
- const hook = renderHook(() =>
- useTableRowExpansionState<TreeItem>({
- baseData,
- getChildren: item => item.children,
+ it('renders the expanded panel as a full-width cell spanning all columns', () => {
+ const multiCol: TableColumn<Row>[] = [
+ {key: 'name', header: 'Name'},
+ {key: 'bio', header: 'Bio'},
+ ];
+ function H() {
+ const [keys, setKeys] = useState(new Set(['a']));
+ const expansion = useTableRowExpansion<Row>({
+ expandedKeys: keys,
+ onToggle: () => setKeys(keys),
getRowKey: item => item.id,
- expandedKeys,
- setExpandedKeys,
- }),
+ renderExpanded: item => <div data-testid="panel">{item.bio}</div>,
+ });
+ return (
+ <Table
+ data={rows}
+ columns={multiCol}
+ idKey="id"
+ plugins={{expansion}}
+ />
+ );
+ }
+ render(<H />);
+ const panelCell = screen.getByTestId('panel').closest('td');
+ expect(panelCell).not.toBeNull();
+ // 2 user columns + 1 injected chevron column = colSpan 3
+ expect(panelCell).toHaveAttribute('colspan', '3');
+ });
+
+ it('hides the chevron for non-expandable rows and never shows their panel', () => {
+ render(<Harness isItemExpandable={item => item.id !== 'b'} />);
+ // Only a and c are expandable
+ expect(screen.getAllByRole('button', {name: /expand row/i})).toHaveLength(
+ 2,
);
- return {hook, setExpandedKeys};
- }
-
- it('terminates on a self-referential expanded row and flattens each key once', () => {
- const {hook} = renderState(makeSelfReferential(), new Set(['x']));
- const {data, expansionConfig} = hook.result.current;
- expect(data.map(item => item.id)).toEqual(['x', 'y']);
- expect(expansionConfig.getDepth?.(data[0])).toBe(0);
- expect(expansionConfig.getDepth?.(data[1])).toBe(1);
});
- it('terminates on a deeper cycle back to the root and flattens each key once', () => {
- const {hook} = renderState(
- makeDeepCycle(),
- new Set(['root', 'child', 'grand']),
+ it('does not render a panel for a non-expandable row even if its key is in expandedKeys', () => {
+ render(
+ <Harness
+ initialExpanded={new Set(['b'])}
+ isItemExpandable={item => item.id !== 'b'}
+ />,
);
- const {data, expansionConfig} = hook.result.current;
- expect(data.map(item => item.id)).toEqual(['root', 'child', 'grand']);
- expect(expansionConfig.getDepth?.(data[0])).toBe(0);
- expect(expansionConfig.getDepth?.(data[1])).toBe(1);
- expect(expansionConfig.getDepth?.(data[2])).toBe(2);
- // The cycle guard keeps isAllExpanded computable — true, not a crash.
- expect(expansionConfig.isAllExpanded).toBe(true);
+ expect(screen.queryByTestId('panel')).not.toBeInTheDocument();
});
- it('terminates when collecting allExpandableKeys on cyclic data with nothing expanded', () => {
- const {hook, setExpandedKeys} = renderState(
- makeDeepCycle(),
- new Set<string>(),
- );
- const {data, expansionConfig} = hook.result.current;
- expect(data.map(item => item.id)).toEqual(['root']);
- expansionConfig.onToggleExpandAll?.(true);
- const nextKeys = setExpandedKeys.mock.calls[0][0] as Set<string>;
- expect(Array.from(nextKeys)).toEqual(['root', 'child', 'grand']);
+ it('contributes a context-menu action on expandable rows', () => {
+ render(<Harness />);
+ fireEvent.contextMenu(screen.getByText('Ada'));
+ expect(
+ screen.getAllByRole('menuitem', {name: /expand row/i, hidden: true})
+ .length,
+ ).toBeGreaterThan(0);
});
- it('re-walks a shared child under each expanded parent (ancestor-path, not visited-set, semantics)', () => {
- const leaf: TreeItem = {id: 'leaf', name: 'Leaf', children: []};
- const shared: TreeItem = {id: 's', name: 'Shared', children: [leaf]};
- const p1: TreeItem = {id: 'p1', name: 'Parent 1', children: [shared]};
- const p2: TreeItem = {id: 'p2', name: 'Parent 2', children: [shared]};
- const {hook} = renderState([p1, p2], new Set(['p1', 'p2', 's']));
- // 's' is on neither parent's ancestor path, so it must flatten under
- // both — the guard only skips true cycles, matching pre-guard behavior
- // for acyclic (DAG-shaped) data.
- const {data} = hook.result.current;
- expect(data.map(item => item.id)).toEqual([
- 'p1',
- 's',
- 'leaf',
- 'p2',
- 's',
- 'leaf',
- ]);
+ it('localizes the chevron aria-label through the i18n catalog', () => {
+ render(
+ <InternationalizationProvider
+ locale="fr"
+ overrides={{
+ fr: {'@astryx.tableRowExpansion.expandRow': 'Développer la ligne'},
+ }}>
+ <Harness />
+ </InternationalizationProvider>,
+ );
+ expect(
+ screen.getAllByRole('button', {name: 'Développer la ligne'}).length,
+ ).toBeGreaterThan(0);
});
});
diff --git a/packages/core/src/Table/plugins/rowExpansion/useTableRowExpansion.tsx b/packages/core/src/Table/plugins/rowExpansion/useTableRowExpansion.tsx
index da6a7eb82c..aecfe2c1a7 100644
--- a/packages/core/src/Table/plugins/rowExpansion/useTableRowExpansion.tsx
+++ b/packages/core/src/Table/plugins/rowExpansion/useTableRowExpansion.tsx
@@ -4,30 +4,30 @@
/**
* @file useTableRowExpansion.tsx
- * @input React, StyleX, Icon, Table types
- * @output Exports useTableRowExpansion hook + config/state types
- * @position Row-expansion plugin; consumed by Table via plugins prop
- * @deprecated Superseded by the tree plugin (useTableTreeData +
- * useTableTreeState). Kept for back-compat; new tree tables should use the
- * tree plugin. See the migration guide on useTableRowExpansion.
+ * @input React, StyleX, Icon, Table types, i18n (useTranslator)
+ * @output Exports useTableRowExpansion hook + config type
+ * @position Row-expansion plugin (detail panel); consumed by Table via plugins prop
+ *
+ * Expands a full-width detail panel below a row, rendered by the consumer's
+ * `renderExpanded(item)`. For hierarchical/tree tables (child rows that reuse
+ * the parent columns) use `useTableTreeData` + `useTableTreeState` instead.
*
* SYNC: When modified, update these files to stay in sync:
* - /packages/core/src/Table/index.ts (exports)
+ * - /packages/core/src/Table/useTableRowExpansion.doc.mjs
*/
-import {useCallback, useMemo, useRef, type ReactNode} from 'react';
+import {useMemo, useRef, type ReactNode} from 'react';
import * as stylex from '@stylexjs/stylex';
import {spacingVars, colorVars, radiusVars} from '../../../theme/tokens.stylex';
import {Icon} from '../../../Icon';
-import {rtlStyles} from '../../../utils';
import {resolveContextActions} from '../../tableContextMenu';
import {useTranslator} from '../../../i18n';
import type {
TablePlugin,
TableColumn,
- BodyCellRenderProps,
BodyRowRenderProps,
- HeaderCellRenderProps,
+ BodyCellRenderProps,
} from '../../types';
// =============================================================================
@@ -35,253 +35,29 @@ import type {
// =============================================================================
/**
- * Configuration for useTableRowExpansion (inherited-columns mode).
+ * Configuration for useTableRowExpansion (detail-panel mode).
*
- * Child rows use the same columns as their parents, with indentation on the
- * first content column. The consumer provides a **flat** data array (use
- * {@link useTableRowExpansionState} to flatten a tree) and a `getDepth`
- * function so the plugin knows each row's nesting level.
+ * The consumer owns expansion state; the plugin provides the chevron UI, the
+ * full-width detail panel rendered below an expanded row, and a right-click
+ * "Expand/Collapse row" action.
*/
export interface UseTableRowExpansionConfig<T extends Record<string, unknown>> {
/** Set of currently-expanded row keys. */
expandedKeys: Set<string>;
- /** Called when a row's expansion is toggled. */
+ /** Called with a row key when its expansion is toggled. */
onToggle: (key: string) => void;
/** Derive a stable unique key from a row item. */
getRowKey: (item: T) => string;
- /** Return the children of a row (used to determine expandability). */
- getChildren: (item: T) => T[];
- /** Return the depth of a row in the hierarchy (0 = top-level). */
- getDepth?: (item: T) => number;
- /** Optionally control which rows are expandable. @default checks getChildren length */
- getIsItemExpandable?: (item: T) => boolean;
/**
- * When true, clicking anywhere on the row toggles expansion (in addition to
- * the chevron button). @default false — only the chevron triggers expansion.
+ * Render the detail content shown in a full-width panel below the row when
+ * it is expanded. Receives the row's item.
*/
- hasRowClickExpansion?: boolean;
- /**
- * State of the expand-all toggle in the header. `true` = all expanded,
- * `false` = all collapsed, `'indeterminate'` = mixed. When provided
- * (together with `onToggleExpandAll`), the header cell shows a toggle button.
- */
- isAllExpanded?: boolean | 'indeterminate';
- /** Called when the expand-all header toggle is clicked. */
- onToggleExpandAll?: (expand: boolean) => void;
-}
-
-/**
- * Configuration for {@link useTableRowExpansionState}.
- *
- * Mirrors the shape of {@link useTableSelectionState}: you own the
- * `expandedKeys` set (via `useState`), and the hook derives everything the
- * plugin needs — the flattened `data`, per-row depth, expand/collapse
- * handlers, and the expand-all toggle state.
- */
-export interface UseTableRowExpansionStateConfig<
- T extends Record<string, unknown>,
-> {
- /** The full, un-flattened tree. */
- baseData: T[];
- /** Return the children of a row. Leaf rows return an empty array. */
- getChildren: (item: T) => T[];
- /** Derive a stable unique key from a row item. */
- getRowKey: (item: T) => string;
+ renderExpanded: (item: T) => ReactNode;
/**
- * Should this row be expandable? Rows that return `false` never show a
- * chevron and are skipped by expand-all. @default rows with children
+ * Control which rows are expandable. Non-expandable rows show no chevron, no
+ * context-menu action, and never render a panel. @default all rows expandable
*/
getIsItemExpandable?: (item: T) => boolean;
- /** Controlled set of currently-expanded row keys. */
- expandedKeys: Set<string>;
- /** Setter for the controlled expanded keys. */
- setExpandedKeys: React.Dispatch<React.SetStateAction<Set<string>>>;
-}
-
-export interface UseTableRowExpansionStateResult<
- T extends Record<string, unknown>,
-> {
- /** The flattened, currently-visible rows. Pass to `<Table data>`. */
- data: T[];
- /** Ready-to-use config for {@link useTableRowExpansion}. */
- expansionConfig: UseTableRowExpansionConfig<T>;
-}
-
-/**
- * Manages row-expansion state and derives the config for
- * {@link useTableRowExpansion}.
- *
- * @deprecated Use `useTableTreeState` (with `useTableTreeData`) instead. The
- * tree plugin covers the same affordances (expand-all header control,
- * whole-row click) with a cycle guard and per-row fine-grained re-render. See
- * the migration guide on `useTableRowExpansion` (`astryx component
- * useTableRowExpansion --detail full`) for the before/after and config
- * mapping.
- *
- * @example
- * ```
- * const [expandedKeys, setExpandedKeys] = useState<Set<string>>(new Set());
- * const {data, expansionConfig} = useTableRowExpansionState({
- * baseData: tree,
- * getChildren: item => item.children ?? [],
- * getRowKey: item => item.id,
- * expandedKeys,
- * setExpandedKeys,
- * });
- * const expansion = useTableRowExpansion(expansionConfig);
- * <Table data={data} columns={columns} idKey="id" plugins={{expansion}} />;
- * ```
- */
-export function useTableRowExpansionState<T extends Record<string, unknown>>({
- baseData,
- getChildren,
- getRowKey,
- getIsItemExpandable,
- expandedKeys,
- setExpandedKeys,
-}: UseTableRowExpansionStateConfig<T>): UseTableRowExpansionStateResult<T> {
- const isExpandable = useCallback(
- (item: T): boolean =>
- getIsItemExpandable
- ? getIsItemExpandable(item)
- : getChildren(item).length > 0,
- [getIsItemExpandable, getChildren],
- );
-
- const depthMap = useMemo(() => {
- const map = new Map<string, number>();
- // Ancestor keys on the current walk path — guards against cyclic data.
- const path = new Set<string>();
- function walk(items: T[], depth: number) {
- for (const item of items) {
- const key = getRowKey(item);
- if (path.has(key)) {
- continue; // cyclic edge — skip
- }
- map.set(key, depth);
- if (expandedKeys.has(key)) {
- path.add(key);
- walk(getChildren(item), depth + 1);
- path.delete(key);
- }
- }
- }
- walk(baseData, 0);
- return map;
- }, [baseData, getChildren, getRowKey, expandedKeys]);
-
- const data = useMemo(() => {
- const result: T[] = [];
- // Ancestor keys on the current walk path — guards against cyclic data.
- const path = new Set<string>();
- function walk(items: T[]) {
- for (const item of items) {
- const key = getRowKey(item);
- if (path.has(key)) {
- continue; // cyclic edge — skip
- }
- result.push(item);
- if (expandedKeys.has(key)) {
- path.add(key);
- walk(getChildren(item));
- path.delete(key);
- }
- }
- }
- walk(baseData);
- return result;
- }, [baseData, getChildren, getRowKey, expandedKeys]);
-
- // Every expandable key across the whole tree (drives expand-all).
- const allExpandableKeys = useMemo(() => {
- const keys: string[] = [];
- // Ancestor keys on the current walk path — guards against cyclic data.
- const path = new Set<string>();
- function walk(items: T[]) {
- for (const item of items) {
- const key = getRowKey(item);
- if (path.has(key)) {
- continue; // cyclic edge — skip
- }
- if (isExpandable(item)) {
- keys.push(key);
- path.add(key);
- walk(getChildren(item));
- path.delete(key);
- }
- }
- }
- walk(baseData);
- return keys;
- }, [baseData, getChildren, getRowKey, isExpandable]);
-
- const getDepth = useCallback(
- (item: T) => depthMap.get(getRowKey(item)) ?? 0,
- [depthMap, getRowKey],
- );
-
- const onToggle = useCallback(
- (key: string) => {
- setExpandedKeys(prev => {
- const next = new Set(prev);
- if (next.has(key)) {
- next.delete(key);
- } else {
- next.add(key);
- }
- return next;
- });
- },
- [setExpandedKeys],
- );
-
- const isAllExpanded: boolean | 'indeterminate' = useMemo(() => {
- if (allExpandableKeys.length === 0) {
- return false;
- }
- const expandedCount = allExpandableKeys.filter(k =>
- expandedKeys.has(k),
- ).length;
- if (expandedCount === 0) {
- return false;
- }
- if (expandedCount === allExpandableKeys.length) {
- return true;
- }
- return 'indeterminate';
- }, [allExpandableKeys, expandedKeys]);
-
- const onToggleExpandAll = useCallback(
- (expand: boolean) => {
- setExpandedKeys(expand ? new Set(allExpandableKeys) : new Set());
- },
- [setExpandedKeys, allExpandableKeys],
- );
-
- const expansionConfig = useMemo(
- (): UseTableRowExpansionConfig<T> => ({
- expandedKeys,
- onToggle,
- getRowKey,
- getChildren,
- getDepth,
- getIsItemExpandable,
- isAllExpanded,
- onToggleExpandAll,
- }),
- [
- expandedKeys,
- onToggle,
- getRowKey,
- getChildren,
- getDepth,
- getIsItemExpandable,
- isAllExpanded,
- onToggleExpandAll,
- ],
- );
-
- return {data, expansionConfig};
}
// =============================================================================
@@ -290,26 +66,22 @@ export function useTableRowExpansionState<T extends Record<string, unknown>>({
const EXPANSION_COLUMN_WIDTH = {type: 'pixel' as const, value: 40};
-/** Indentation applied per depth level, in pixels. */
-const INDENT_PER_DEPTH = 24;
-
const expansionStyles = stylex.create({
chevronButton: {
display: 'inline-flex',
alignItems: 'center',
justifyContent: 'center',
- width: '24px',
- height: '24px',
+ width: spacingVars['--spacing-6'],
+ height: spacingVars['--spacing-6'],
background: 'transparent',
border: 'none',
borderRadius: radiusVars['--radius-inner'],
cursor: 'pointer',
color: colorVars['--color-icon-secondary'],
- transitionProperty: 'transform, color, background-color',
+ transitionProperty: 'transform, color',
transitionDuration: '150ms',
padding: 0,
- flexShrink: '0',
- // Match IconButton ghost hover: subtle overlay background
+ // Match IconButton ghost hover: subtle overlay background.
backgroundImage: {
default: null,
':hover': {
@@ -320,82 +92,48 @@ const expansionStyles = stylex.create({
color: colorVars['--color-icon-primary'],
},
},
- chevronIcon: {
- transitionProperty: 'transform',
- transitionDuration: '150ms',
- },
- // The RTL mirror is folded into each state's transform rather than living on
- // a parent span. Both are `transform`, so on one element the later value
- // would win — spelling out `scaleX(-1) rotate(...)` per state composes them
- // exactly as the nested elements did, while leaving a single element to
- // carry the glyph's theme target.
- chevronIconCollapsed: {
- transform: {
- default: 'rotate(0deg)',
- ':is([dir="rtl"] *)': 'scaleX(-1) rotate(0deg)',
- },
- },
- chevronIconExpanded: {
- transform: {
- default: 'rotate(90deg)',
- ':is([dir="rtl"] *)': 'scaleX(-1) rotate(90deg)',
- },
- },
- indentedCell: {
- display: 'flex',
- alignItems: 'center',
- gap: spacingVars['--spacing-1'],
+ chevronExpanded: {
+ transform: 'rotate(90deg)',
},
- indent: (px: number) => ({
- paddingInlineStart: `${px}px`,
- }),
- placeholder: {
- display: 'inline-block',
- width: '24px',
- height: '24px',
- flexShrink: '0',
+ expandedRow: {
+ backgroundColor: colorVars['--color-background-muted'],
},
- clickableRow: {
- cursor: 'pointer',
+ expandedCell: {
+ paddingBlock: spacingVars['--spacing-4'],
+ paddingInline: spacingVars['--spacing-5'],
},
});
// =============================================================================
-// Chevron
+// Chevron Cell
// =============================================================================
function ExpansionChevron({
isExpanded,
onToggle,
- ariaLabel,
}: {
isExpanded: boolean;
onToggle: () => void;
- ariaLabel: string;
}) {
+ const t = useTranslator();
return (
<button
type="button"
- {...stylex.props(expansionStyles.chevronButton)}
+ {...stylex.props(
+ expansionStyles.chevronButton,
+ isExpanded && expansionStyles.chevronExpanded,
+ )}
onClick={e => {
e.stopPropagation();
onToggle();
}}
- aria-label={ariaLabel}
+ aria-label={
+ isExpanded
+ ? t('@astryx.tableRowExpansion.collapseRow')
+ : t('@astryx.tableRowExpansion.expandRow')
+ }
aria-expanded={isExpanded}>
- <Icon
- icon="chevronRight"
- size="xsm"
- // The rotation rides on the glyph rather than a wrapper span so the
- // theme target below reaches both the mark and its open/closed
- // transform.
- xstyle={[
- expansionStyles.chevronIcon,
- isExpanded
- ? expansionStyles.chevronIconExpanded
- : expansionStyles.chevronIconCollapsed,
- ]}
- />
+ <Icon icon="chevronRight" size="xsm" />
</button>
);
}
@@ -405,33 +143,48 @@ function ExpansionChevron({
// =============================================================================
/**
- * Returns a TablePlugin implementing expandable rows with inherited columns.
+ * Returns a TablePlugin that expands a full-width detail panel below a row.
+ *
+ * The consumer owns the `expandedKeys` set (via `useState`); the plugin adds
+ * a leading chevron column, a right-click expand/collapse action, and renders
+ * `renderExpanded(item)` in a full-width panel below each expanded row.
+ *
+ * For hierarchical data (child rows sharing the parent columns) use
+ * `useTableTreeData` + `useTableTreeState` instead.
*
- * @deprecated Use `useTableTreeData` (with `useTableTreeState`) instead. The
- * tree plugin covers the same affordances (expand-all header control,
- * whole-row click) with a cycle guard and per-row fine-grained re-render. See
- * the migration guide on this hook's docs (`astryx component
- * useTableRowExpansion --detail full`) for the before/after and config
- * mapping.
+ * @example
+ * ```
+ * const [expandedKeys, setExpandedKeys] = useState<Set<string>>(new Set());
+ * const expansion = useTableRowExpansion({
+ * expandedKeys,
+ * onToggle: key =>
+ * setExpandedKeys(prev => {
+ * const next = new Set(prev);
+ * next.has(key) ? next.delete(key) : next.add(key);
+ * return next;
+ * }),
+ * getRowKey: item => item.id,
+ * renderExpanded: item => <OrderDetails order={item} />,
+ * });
+ * <Table data={data} columns={columns} idKey="id" plugins={{expansion}} />;
+ * ```
*/
export function useTableRowExpansion<T extends Record<string, unknown>>(
config: UseTableRowExpansionConfig<T>,
): TablePlugin<T> {
- const t = useTranslator();
const {
expandedKeys,
onToggle,
getRowKey,
- getChildren,
- getDepth,
+ renderExpanded,
getIsItemExpandable,
- hasRowClickExpansion = false,
- isAllExpanded,
- onToggleExpandAll,
} = config;
- // Track the first non-plugin column key for indentation.
- const firstUserColumnKeyRef = useRef<string | null>(null);
+ const t = useTranslator();
+
+ // Final rendered column count, captured in transformColumns (pipeline step
+ // 1) and read in transformBodyRow for the detail panel's colSpan.
+ const columnCountRef = useRef(1);
const expansionColumn = useMemo(
(): TableColumn<T> => ({
@@ -440,171 +193,45 @@ export function useTableRowExpansion<T extends Record<string, unknown>>(
width: EXPANSION_COLUMN_WIDTH,
resizable: false,
renderCell: (item: T) => {
- // Child rows (depth > 0) show their chevron inline in the first user
- // column instead — don't double up here.
- const depth = getDepth ? getDepth(item) : 0;
- if (depth > 0) {
- return null;
- }
-
- const key = getRowKey(item);
const expandable = getIsItemExpandable
? getIsItemExpandable(item)
- : getChildren(item).length > 0;
+ : true;
if (!expandable) {
return null;
}
- const isExpanded = expandedKeys.has(key);
+ const key = getRowKey(item);
return (
<ExpansionChevron
- isExpanded={isExpanded}
+ isExpanded={expandedKeys.has(key)}
onToggle={() => onToggle(key)}
- ariaLabel={
- isExpanded
- ? t('@astryx.tableRowExpansion.collapseRow')
- : t('@astryx.tableRowExpansion.expandRow')
- }
/>
);
},
}),
- [
- expandedKeys,
- onToggle,
- getRowKey,
- getChildren,
- getIsItemExpandable,
- getDepth,
- t,
- ],
+ [expandedKeys, onToggle, getRowKey, getIsItemExpandable],
);
return useMemo(
(): TablePlugin<T> => ({
transformColumns(columns: TableColumn<T>[]) {
- // Track the first user column for indentation.
- const firstUserCol = columns.find(c => !c.key.startsWith('__'));
- firstUserColumnKeyRef.current = firstUserCol?.key ?? null;
-
- // Wrap the first user column's renderCell to add depth indentation +
- // an inline chevron for child rows. This is the inherited-columns
- // pattern: child rows use the same columns but indent their first
- // content cell.
- const wrappedColumns = columns.map(col => {
- if (col.key !== firstUserColumnKeyRef.current) {
- return col;
- }
- const originalRenderCell = col.renderCell;
- return {
- ...col,
- renderCell: (item: T): ReactNode => {
- const depth = getDepth ? getDepth(item) : 0;
- const originalContent = originalRenderCell
- ? originalRenderCell(item)
- : String(
- ((item as Record<string, unknown>)[col.key] as
- string | number | null | undefined) ?? '',
- );
-
- if (depth === 0) {
- return originalContent;
- }
-
- const indent = (depth - 1) * INDENT_PER_DEPTH;
- const key = getRowKey(item);
- const isExpanded = expandedKeys.has(key);
- const expandable = getIsItemExpandable
- ? getIsItemExpandable(item)
- : getChildren(item).length > 0;
-
- const chevron = expandable ? (
- <ExpansionChevron
- isExpanded={isExpanded}
- onToggle={() => onToggle(key)}
- ariaLabel={
- isExpanded
- ? t('@astryx.tableRowExpansion.collapseRow')
- : t('@astryx.tableRowExpansion.expandRow')
- }
- />
- ) : (
- <span {...stylex.props(expansionStyles.placeholder)} />
- );
-
- return (
- <div
- {...stylex.props(
- expansionStyles.indentedCell,
- indent > 0 && expansionStyles.indent(indent),
- )}>
- {chevron}
- {originalContent}
- </div>
- );
- },
- };
- });
-
- return [expansionColumn, ...wrappedColumns];
- },
-
- transformHeaderCell(
- props: HeaderCellRenderProps,
- column: TableColumn<T>,
- ): HeaderCellRenderProps {
- if (column.key !== '__expansion') {
- return props;
- }
-
- // Show expand-all toggle when the consumer provides the state + callback.
- if (isAllExpanded !== undefined && onToggleExpandAll) {
- const allExpanded = isAllExpanded === true;
- return {
- ...props,
- content: (
- <button
- type="button"
- {...stylex.props(expansionStyles.chevronButton)}
- onClick={() => onToggleExpandAll(!allExpanded)}
- aria-label={
- allExpanded
- ? t('@astryx.tableRowExpansion.collapseAllRows')
- : t('@astryx.tableRowExpansion.expandAllRows')
- }>
- <Icon
- icon="chevronRight"
- size="xsm"
- // Same one-element treatment as the row chevron: the glyph
- // carries both the rotation and the theme target.
- xstyle={[
- expansionStyles.chevronIcon,
- allExpanded
- ? expansionStyles.chevronIconExpanded
- : expansionStyles.chevronIconCollapsed,
- ]}
- />
- </button>
- ),
- };
- }
-
- return {...props, content: null};
+ const withExpansion = [expansionColumn, ...columns];
+ columnCountRef.current = withExpansion.length;
+ return withExpansion;
},
transformBodyCell(
props: BodyCellRenderProps,
- column: TableColumn<T>,
+ _column: TableColumn<T>,
item: T,
): BodyCellRenderProps {
- // Contribute "Expand/Collapse row" context-menu action on every cell
- // so right-clicking anywhere in the row shows the option.
+ // Contribute the expand/collapse action on every cell; BaseTable
+ // aggregates them into one menu per row. Skip non-expandable rows.
const expandable = getIsItemExpandable
? getIsItemExpandable(item)
- : getChildren(item).length > 0;
+ : true;
if (!expandable) {
return props;
}
-
const key = getRowKey(item);
const isExpanded = expandedKeys.has(key);
return {
@@ -622,7 +249,6 @@ export function useTableRowExpansion<T extends Record<string, unknown>>(
icon={isExpanded ? 'chevronDown' : 'chevronRight'}
size="xsm"
aria-hidden
- xstyle={rtlStyles.mirror}
/>
),
onSelect: () => onToggle(key),
@@ -632,38 +258,50 @@ export function useTableRowExpansion<T extends Record<string, unknown>>(
},
transformBodyRow(props: BodyRowRenderProps, item: T): BodyRowRenderProps {
- if (!hasRowClickExpansion) {
- return props;
- }
const expandable = getIsItemExpandable
? getIsItemExpandable(item)
- : getChildren(item).length > 0;
+ : true;
if (!expandable) {
return props;
}
const key = getRowKey(item);
+ if (!expandedKeys.has(key)) {
+ return props;
+ }
+
+ const panel = (
+ <tr
+ key={`${key}-expanded`}
+ {...stylex.props(expansionStyles.expandedRow)}>
+ <td
+ colSpan={columnCountRef.current}
+ {...stylex.props(expansionStyles.expandedCell)}>
+ {renderExpanded(item)}
+ </td>
+ </tr>
+ );
+
return {
...props,
- htmlProps: {
- ...props.htmlProps,
- onClick: () => onToggle(key),
- },
- xstyle: [...props.xstyle, expansionStyles.clickableRow],
+ afterRow: props.afterRow ? (
+ <>
+ {props.afterRow}
+ {panel}
+ </>
+ ) : (
+ panel
+ ),
};
},
}),
[
expandedKeys,
getRowKey,
- onToggle,
- getChildren,
- getDepth,
+ renderExpanded,
getIsItemExpandable,
- hasRowClickExpansion,
- isAllExpanded,
- onToggleExpandAll,
- expansionColumn,
+ onToggle,
t,
+ expansionColumn,
],
);
}
diff --git a/packages/core/src/Table/types.ts b/packages/core/src/Table/types.ts
index 5cbc2f8920..2b73fed981 100644
--- a/packages/core/src/Table/types.ts
+++ b/packages/core/src/Table/types.ts
@@ -290,6 +290,12 @@ export interface BodyRowRenderProps {
children: ReactNode;
/** Ref for the `<tr>` element. Plugins can set this to access the row DOM node. */
ref?: Ref<HTMLTableRowElement>;
+ /**
+ * Extra content rendered as a sibling immediately after this row's `<tr>`.
+ * Plugins use it to append a full-width detail-panel `<tr>` (e.g. row
+ * expansion). Multiple plugins compose by wrapping the previous `afterRow`.
+ */
+ afterRow?: ReactNode;
}
/** Props passed through the plugin pipeline for each body `<td>` */
diff --git a/packages/core/src/Table/useTableGroupedRows.doc.mjs b/packages/core/src/Table/useTableGroupedRows.doc.mjs
index 0e665402e3..f181e47b4c 100644
--- a/packages/core/src/Table/useTableGroupedRows.doc.mjs
+++ b/packages/core/src/Table/useTableGroupedRows.doc.mjs
@@ -7,7 +7,7 @@ export const docs = {
subComponentOf: 'Table',
displayName: 'useTableGroupedRows',
description:
- 'Hook that groups a flat data array into collapsible section rows. Each distinct groupBy value becomes a full-width section-header row with a chevron toggle, the group label, and a member count; collapsing hides that group\'s data rows while keeping the header visible. Mirrors useTableRowExpansionState: the consumer owns the collapsedGroups set and the hook returns {data, plugin, idKey}: pass all three to Table (data, plugins, and idKey respectively).',
+ 'Hook that groups a flat data array into collapsible section rows. Each distinct groupBy value becomes a full-width section-header row with a chevron toggle, the group label, and a member count; collapsing hides that group\'s data rows while keeping the header visible. Mirrors useTableTreeState: the consumer owns the collapsedGroups set and the hook returns {data, plugin, idKey}: pass all three to Table (data, plugins, and idKey respectively).',
props: [
{
name: 'data',
diff --git a/packages/core/src/Table/useTableRowExpansion.doc.mjs b/packages/core/src/Table/useTableRowExpansion.doc.mjs
index ffd52033ac..f92ab6e8f8 100644
--- a/packages/core/src/Table/useTableRowExpansion.doc.mjs
+++ b/packages/core/src/Table/useTableRowExpansion.doc.mjs
@@ -7,18 +7,19 @@ export const docs = {
subComponentOf: 'Table',
displayName: 'useTableRowExpansion',
description:
- 'Deprecated: use useTableTreeData + useTableTreeState instead. Hook that returns a TablePlugin implementing expandable rows with inherited columns. Child rows use the same columns as their parents, indented by depth. Clicking the chevron (or right-click context menu) toggles expansion. Pair with useTableRowExpansionState, which flattens the tree and derives this config (expand/collapse handlers + expand-all state) from a single expandedKeys set. Converging with useTableTreeData: new tree tables should prefer useTableTreeData + useTableTreeState, which cover the same affordances with a cycle guard and fine-grained re-render. See the migration example below.',
+ 'Hook that returns a TablePlugin which expands a full-width detail panel below a row, rendered by the consumer via renderExpanded(item). Adds a leading chevron column and a right-click "Expand/Collapse row" action; the consumer owns the expandedKeys set. Use it for master-detail rows (order details, forms, charts, nested tables). For hierarchical data where child rows reuse the parent columns, use useTableTreeData + useTableTreeState instead.',
props: [
{
name: 'expandedKeys',
type: 'Set<string>',
- description: 'Set of currently-expanded row keys.',
+ description: 'Set of currently-expanded row keys. Consumer-owned.',
required: true,
},
{
name: 'onToggle',
type: '(key: string) => void',
- description: 'Called when a row expansion is toggled.',
+ description:
+ 'Called with a row key when its expansion is toggled (chevron click or context-menu action).',
required: true,
},
{
@@ -28,48 +29,44 @@ export const docs = {
required: true,
},
{
- name: 'getChildren',
- type: '(item: T) => T[]',
- description: 'Return the children of a row (determines expandability).',
+ name: 'renderExpanded',
+ type: '(item: T) => ReactNode',
+ description:
+ 'Render the detail content shown in a full-width panel below the row when it is expanded. Receives the row item.',
required: true,
},
- {
- name: 'getDepth',
- type: '(item: T) => number',
- description: 'Return the depth of a row in the hierarchy (0 = top-level). Used for indentation.',
- },
{
name: 'getIsItemExpandable',
type: '(item: T) => boolean',
- description: 'Control which rows are expandable. Defaults to checking getChildren length.',
- },
- {
- name: 'hasRowClickExpansion',
- type: 'boolean',
- description: 'When true, clicking anywhere on the row toggles expansion.',
- default: 'false',
- },
- {
- name: 'isAllExpanded',
- type: "boolean | 'indeterminate'",
- description: 'State of the expand-all toggle in the header. Enables the header toggle button.',
- },
- {
- name: 'onToggleExpandAll',
- type: '(expand: boolean) => void',
- description: 'Callback when the expand-all header toggle is clicked.',
+ description:
+ 'Control which rows are expandable. Non-expandable rows show no chevron, no context-menu action, and never render a panel. Defaults to all rows expandable.',
},
],
examples: [
{
- label: 'Migrating to useTableTreeData + useTableTreeState',
- code: `// useTableRowExpansion and useTableTreeData are converging onto one tree
-// plugin. useTableTreeData is the destination: it adds a cycle guard,
-// per-row fine-grained re-render, and imperative row ARIA, and now covers
-// the same affordances (expand-all header control, whole-row click).
+ label: 'Master-detail order rows',
+ code: `const [expandedKeys, setExpandedKeys] = useState(new Set());
+const expansion = useTableRowExpansion({
+ expandedKeys,
+ onToggle: key =>
+ setExpandedKeys(prev => {
+ const next = new Set(prev);
+ next.has(key) ? next.delete(key) : next.add(key);
+ return next;
+ }),
+ getRowKey: item => item.id,
+ renderExpanded: item => <OrderDetails order={item} />,
+});
+
+<Table data={orders} columns={columns} idKey="id" plugins={{expansion}} />;`,
+ },
+ {
+ label: 'Migrating from tree rows to the tree plugin',
+ code: `// useTableRowExpansion is now for DETAIL PANELS, not tree rows. If you used
+// it to render nested child rows that reuse the parent columns, move to
+// useTableTreeData + useTableTreeState.
-// BEFORE: useTableRowExpansion + useTableRowExpansionState
-const [expandedKeys, setExpandedKeys] = useState(new Set(['root']));
+// BEFORE (tree rows via useTableRowExpansion + useTableRowExpansionState):
const {data, expansionConfig} = useTableRowExpansionState({
baseData: tree,
getChildren: item => item.children ?? [],
@@ -80,12 +77,12 @@ const {data, expansionConfig} = useTableRowExpansionState({
const expansion = useTableRowExpansion(expansionConfig);
<Table data={data} columns={columns} idKey="id" plugins={{expansion}} />;
-// AFTER: useTableTreeState + useTableTreeData
+// AFTER (tree rows via the tree plugin):
const {visibleData, treeConfig} = useTableTreeState({
- data: tree, // nested data, not a flat array
+ data: tree, // nested data
idKey: 'id', // or a function: idKey={item => item.id}
- childrenKey: 'children', // replaces getChildren (default 'children')
- defaultExpandedIds: ['root'], // uncontrolled; or expandedIds + onExpandedIdsChange
+ childrenKey: 'children', // replaces getChildren
+ defaultExpandedIds: ['root'], // or controlled: expandedIds + onExpandedIdsChange
});
const tree = useTableTreeData({
...treeConfig,
@@ -94,40 +91,20 @@ const tree = useTableTreeData({
});
<Table data={visibleData} columns={columns} idKey="id" plugins={{tree}} />;`,
},
- {
- label: 'Config mapping',
- code: `// useTableRowExpansion(State) -> useTableTreeState / useTableTreeData
-
-// baseData: T[] (nested) -> data: T[] (useTableTreeState)
-// getChildren: item => item.children -> childrenKey: 'children' (property name)
-// getRowKey: item => item.id -> idKey: 'id' | (item => item.id)
-// getIsItemExpandable -> isItemExpandable (same shape)
-// expandedKeys + setExpandedKeys -> defaultExpandedIds (uncontrolled), or
-// expandedIds + onExpandedIdsChange (controlled)
-// getDepth -> removed; depth derives from nesting
-// isAllExpanded + onToggleExpandAll -> hasExpandAllControl (state is computed)
-// hasRowClickExpansion -> hasRowClickExpansion (unchanged)
-
-// Rendering: useTableRowExpansion prepends a dedicated expander column;
-// useTableTreeData decorates the tree column in place (configurable via
-// treeColumnKey). Keyboard and AT users toggle via the chevron in both.`,
- },
],
};
/** @type {import('@astryxdesign/cli/authoring').ComponentTranslationDoc} */
export const docsDense = {
description:
- 'Deprecated: use useTableTreeData + useTableTreeState instead. Returns a TablePlugin for expandable rows w/ inherited columns. Child rows reuse parent columns, indented by depth. Chevron click (or right-click menu) toggles expansion. Pair w/ useTableRowExpansionState, which flattens the tree + derives this config from one expandedKeys set.',
+ 'Returns a TablePlugin that expands a full-width detail panel below a row via renderExpanded(item). Adds a chevron column + right-click expand/collapse action; consumer owns expandedKeys. For nested child rows that reuse parent columns, use useTableTreeData + useTableTreeState instead.',
propDescriptions: {
- expandedKeys: 'Set of currently-expanded row keys.',
- onToggle: 'Called when a row expansion is toggled.',
+ expandedKeys: 'Set of currently-expanded row keys. Consumer-owned.',
+ onToggle: 'Called with a row key when its expansion is toggled.',
getRowKey: 'Derive a stable unique key from a row item.',
- getChildren: 'Return children of a row; determines expandability.',
- getDepth: 'Return depth of a row (0 = top-level). Used for indentation.',
- getIsItemExpandable: 'Control which rows are expandable. Defaults to checking getChildren length.',
- hasRowClickExpansion: 'If true, clicking anywhere on the row toggles expansion. Default false.',
- isAllExpanded: 'State of the expand-all header toggle. Enables the header toggle button.',
- onToggleExpandAll: 'Callback when the expand-all header toggle is clicked.',
+ renderExpanded:
+ 'Render the full-width detail panel below an expanded row. Receives the row item.',
+ getIsItemExpandable:
+ 'Control which rows are expandable. Defaults to all rows expandable.',
},
};