An open source design system that's fully customizable and agent ready
TypeScript
feat(core): add useTableRowExpansion plugin (#3441)
Humberto Virtudes1e94ba07cf88
diff --git a/.changeset/table-row-expansion.md b/.changeset/table-row-expansion.mdnew file mode 100644index 0000000000..57513fe5fa--- /dev/null+++ b/.changeset/table-row-expansion.md@@ -0,0 +1,17 @@+---+'@astryxdesign/core': patch+---++[feat] Add `useTableRowExpansion` — expand/collapse tree rows inline.++- Inherited-columns mode: child rows use the same columns as their parents,+ indented by depth. Injects a chevron column; clicking (or right-click →+ "Expand/Collapse row") toggles a row's children.+- Headless: the consumer owns `expandedKeys` state; the plugin provides the UI.+ Pair with `useTableRowExpansionState` to flatten a tree into the visible rows.+- Optional expand-all header toggle via `isAllExpanded` + `onToggleExpandAll`.+- Optional `expandOnRowClick` to toggle by clicking anywhere in the row.+- Contributes a context-menu action for expand/collapse (via the+ `contextMenuActions` system).++@humbertovirtudesdiff --git a/apps/storybook/stories/TableRowExpansion.stories.tsx b/apps/storybook/stories/TableRowExpansion.stories.tsxnew file mode 100644index 0000000000..be1f12c54d--- /dev/null+++ b/apps/storybook/stories/TableRowExpansion.stories.tsx@@ -0,0 +1,258 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++import {useState} from 'react';+import type {Meta, StoryObj} from '@storybook/react';+import {+ Table,+ useTableRowExpansion,+ useTableRowExpansionState,+ pixel,+ proportional,+} from '@astryxdesign/core/Table';+import type {TableColumn} from '@astryxdesign/core/Table';++// =============================================================================+// Sample Data — tree structure (file system)+// =============================================================================++interface FileNode extends Record<string, unknown> {+ id: string;+ name: string;+ type: 'folder' | 'file';+ size: string;+ modified: string;+ children?: FileNode[];+}++const fileTree: FileNode[] = [+ {+ 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: '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: 'tsconfig.json',+ name: 'tsconfig.json',+ type: 'file',+ size: '0.6 KB',+ modified: '2026-06-01',+ children: [],+ },+];++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)},+];++// =============================================================================+// Stories+// =============================================================================++const meta: Meta = {+ title: 'Core/TableRowExpansion',+ tags: ['autodocs'],+};++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.+ */+export const InheritedColumns: Story = {+ render: () => {+ const [expandedKeys, setExpandedKeys] = useState<Set<string>>(+ new Set(['src']),+ );++ // 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,+ 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 ?? [],+ getRowKey: item => item.id,+ getIsItemExpandable: item => item.type === 'folder',+ expandedKeys,+ setExpandedKeys,+ });++ const expansion = useTableRowExpansion(expansionConfig);++ return (+ <Table+ data={data}+ columns={columns}+ idKey="id"+ hasHover+ plugins={{expansion}}+ />+ );+ },+};++/**+ * `hasRowClickExpansion: true` — clicking anywhere on the row toggles expansion+ * (in addition to the chevron). The row shows a pointer cursor.+ */+export const ExpandOnRowClick: 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,+ expandedKeys,+ setExpandedKeys,+ });++ // Opt into row-click expansion by extending the derived config.+ const expansion = useTableRowExpansion({+ ...expansionConfig,+ hasRowClickExpansion: true,+ });++ return (+ <Table+ data={data}+ columns={columns}+ idKey="id"+ hasHover+ plugins={{expansion}}+ />+ );+ },+};diff --git a/packages/cli/templates/blocks/components/Table/TableRowExpansionTable.doc.mjs b/packages/cli/templates/blocks/components/Table/TableRowExpansionTable.doc.mjsnew file mode 100644index 0000000000..f7af9d03f3--- /dev/null+++ b/packages/cli/templates/blocks/components/Table/TableRowExpansionTable.doc.mjs@@ -0,0 +1,14 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('../../../../../core/src/docs-types').TemplateDoc} */+export const doc = {+ type: 'block',+ exampleFor: 'useTableRowExpansion',+ name: 'useTableRowExpansion — Tree Table',+ displayName: 'useTableRowExpansion — Tree Table',+ description:+ 'A tree table using useTableRowExpansion with inherited columns. Child rows use the same columns as parents, indented by depth. Click the chevron or right-click to expand/collapse.',+ isReady: true,+ aspectRatio: 16 / 9,+ componentsUsed: ['Table'],+};diff --git a/packages/cli/templates/blocks/components/Table/TableRowExpansionTable.tsx b/packages/cli/templates/blocks/components/Table/TableRowExpansionTable.tsxnew file mode 100644index 0000000000..d404f1c509--- /dev/null+++ b/packages/cli/templates/blocks/components/Table/TableRowExpansionTable.tsx@@ -0,0 +1,99 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++'use client';++import {useState} from 'react';+import {+ Table,+ useTableRowExpansion,+ useTableRowExpansionState,+ proportional,+ pixel,+} from '@astryxdesign/core/Table';++interface FileNode extends Record<string, unknown> {+ id: string;+ name: string;+ type: 'folder' | 'file';+ size: string;+ children?: FileNode[];+}++const fileTree: FileNode[] = [+ {+ 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: 'package.json',+ name: 'package.json',+ type: 'file',+ size: '1.8 KB',+ children: [],+ },+];++const columns = [+ {key: 'name', header: 'Name', width: proportional(2)},+ {key: 'type', header: 'Type', width: pixel(80)},+ {key: 'size', header: 'Size', width: pixel(90)},+];++export default function TableRowExpansionTable() {+ const [expandedKeys, setExpandedKeys] = useState<Set<string>>(+ new Set(['src']),+ );++ const {data, expansionConfig} = useTableRowExpansionState<FileNode>({+ baseData: fileTree,+ getChildren: item => item.children ?? [],+ getRowKey: item => item.id,+ expandedKeys,+ setExpandedKeys,+ });++ const expansion = useTableRowExpansion(expansionConfig);++ return (+ <Table+ data={data}+ columns={columns}+ idKey="id"+ hasHover+ plugins={{expansion}}+ />+ );+}diff --git a/packages/core/src/ContextMenu/ContextMenu.tsx b/packages/core/src/ContextMenu/ContextMenu.tsxindex 0d2f9fb33e..516596cb21 100644--- a/packages/core/src/ContextMenu/ContextMenu.tsx+++ b/packages/core/src/ContextMenu/ContextMenu.tsx@@ -55,6 +55,7 @@ import {} from '../theme/tokens.stylex';import {mergeProps} from '../utils';import type {BaseProps} from '../BaseProps';+import type {StyleXStyles} from '../theme/types';import {themeProps} from '../utils/themeProps';import type {DropdownMenuOption,@@ -114,6 +115,13 @@ export type ContextMenuOption = DropdownMenuOption;interface ContextMenuBaseProps extends BaseProps {/** Ref forwarded to the trigger wrapper element. */ref?: React.Ref<HTMLDivElement>;+ /**+ * Styles applied to the trigger wrapper element (the right-click target).+ * By default the trigger is a plain block that hugs its content — pass a+ * fill style (e.g. `width/height: 100%`) when the whole parent area should+ * be right-clickable (as the Table does for full-cell context menus).+ */+ triggerXstyle?: StyleXStyles | StyleXStyles[];/** The trigger area — right-click on this to open the menu. */children: ReactNode;/** Custom menu width. @default '160px' */@@ -184,6 +192,7 @@ export function ContextMenu({className,style,xstyle,+ triggerXstyle,'data-testid': testId,...props}: ContextMenuProps) {@@ -382,7 +391,14 @@ export function ContextMenu({onContextMenu={handleContextMenu}{...longPressHandlers}data-testid={testId}- {...stylex.props(styles.trigger)}>+ {...stylex.props(+ styles.trigger,+ ...(triggerXstyle+ ? Array.isArray(triggerXstyle)+ ? triggerXstyle+ : [triggerXstyle]+ : []),+ )}>{children}</div>diff --git a/packages/core/src/Table/BaseTable.tsx b/packages/core/src/Table/BaseTable.tsxindex 95a65e1c35..0f531ca132 100644--- a/packages/core/src/Table/BaseTable.tsx+++ b/packages/core/src/Table/BaseTable.tsx@@ -225,7 +225,7 @@ function TableRowInner<T extends Record<string, unknown>>({rowIndex,);- return (+ const row = (<RowComponentkey={rowKey}ref={rowRenderProps.ref}@@ -234,6 +234,8 @@ function TableRowInner<T extends Record<string, unknown>>({{rowRenderProps.children}</RowComponent>);++ return row;}/**diff --git a/packages/core/src/Table/TableCell.tsx b/packages/core/src/Table/TableCell.tsxindex 9f090b19cb..07cbb8fd8e 100644--- a/packages/core/src/Table/TableCell.tsx+++ b/packages/core/src/Table/TableCell.tsx@@ -87,6 +87,62 @@ const densityStyles = stylex.create({},});+// When a cell owns a context menu, its padding moves from the `<td>` onto the+// right-click trigger wrapper so the *entire* cell (padding included) opens the+// menu. Without this, right-clicking the padding ring near a cell edge falls+// through to the browser's native menu. Paired with `contextMenuCellStyles` on+// the `<td>` (font/box-sizing only — no padding).+const densityTextStyles = stylex.create({+ compact: {+ fontSize: typeScaleVars['--text-body-size'],+ boxSizing: 'border-box',+ },+ balanced: {+ fontSize: typeScaleVars['--text-body-size'],+ boxSizing: 'border-box',+ },+ spacious: {+ fontSize: typeScaleVars['--text-body-size'],+ boxSizing: 'border-box',+ },+});++const densityPaddingStyles = stylex.create({+ compact: {+ paddingBlock: spacingVars['--spacing-1'],+ paddingInline: spacingVars['--spacing-2'],+ },+ balanced: {+ paddingBlock: spacingVars['--spacing-2'],+ paddingInline: spacingVars['--spacing-3'],+ },+ spacious: {+ paddingBlock: spacingVars['--spacing-3'],+ paddingInline: spacingVars['--spacing-4'],+ },+});++// The trigger wrapper fills the whole cell (a `<td>` child with height:100%+// stretches to the row height) so a right-click anywhere in the cell opens the+// menu. It carries the density padding relocated off the `<td>`.+const triggerFillStyles = stylex.create({+ fill: {+ display: 'block',+ boxSizing: 'border-box',+ blockSize: '100%',+ inlineSize: '100%',+ },+});++// `height:100%` on the `<td>` is the CSS trick that lets a block child resolve+// its own `height:100%` against the row height — so the trigger fills the cell+// vertically (top/bottom padding included) and is fully right-clickable.+const contextMenuCellStyles = stylex.create({+ cell: {+ blockSize: '100%',+ },+});+const dividerRowStyles = stylex.create({cell: {borderBottomWidth: {@@ -151,22 +207,45 @@ export function TableCell({}: TableCellProps) {const ctx = useTableContext();- // Standalone (no table context) renders plain, with no density/divider styles.+ const hasContextMenu =+ typeof contextMenuActions === 'function' ||+ (Array.isArray(contextMenuActions) && contextMenuActions.length > 0);++ // When the cell owns a context menu, its density padding is relocated onto+ // the right-click trigger wrapper (see `content` below) so the entire cell —+ // padding included — opens the menu. Otherwise padding lives on the `<td>`.const cellStyles: StyleXStyles[] = ctx? [- densityStyles[ctx.density],- ctx.textOverflow === 'truncate'- ? overflowStyles.cell- : wrapStyles.cell,+ hasContextMenu+ ? densityTextStyles[ctx.density]+ : densityStyles[ctx.density],+ ctx.textOverflow === 'truncate' ? overflowStyles.cell : wrapStyles.cell,containerEdgeStyles[ctx.density],verticalAlignStyles[ctx.verticalAlign],- ...buildDividerStyles(ctx, dividerRowStyles.cell, dividerColumnStyles.cell),+ ...buildDividerStyles(+ ctx,+ dividerRowStyles.cell,+ dividerColumnStyles.cell,+ ),+ ...(hasContextMenu ? [contextMenuCellStyles.cell] : []),]: [];// The cell owns the context-menu wrapper so it controls how the menu- // interacts with its padding / content. No-op when no actions.- const content = wrapInTableContextMenu(children, contextMenuActions);+ // interacts with its padding / content. No-op when no actions. When actions+ // exist we make the trigger fill the cell and carry the density padding so a+ // right-click anywhere in the cell (including the padding ring) opens it.+ const triggerXstyle =+ hasContextMenu && ctx+ ? [triggerFillStyles.fill, densityPaddingStyles[ctx.density]]+ : hasContextMenu+ ? triggerFillStyles.fill+ : undefined;+ const content = wrapInTableContextMenu(+ children,+ contextMenuActions,+ triggerXstyle,+ );return (<tddiff --git a/packages/core/src/Table/index.ts b/packages/core/src/Table/index.tsindex 1b7d17685d..ed33e7bf17 100644--- a/packages/core/src/Table/index.ts+++ b/packages/core/src/Table/index.ts@@ -26,6 +26,10 @@ export {useTableColumnSettings} from './plugins/columnSettings';export {useTableColumnSettingsState} from './plugins/columnSettings';export {useTableColumnResize} from './plugins/columnResize';export {useTableStickyColumns} from './plugins/stickyColumns';+export {+ useTableRowExpansion,+ useTableRowExpansionState,+} from './plugins/rowExpansion';export {resolveContextActions} from './tableContextMenu';export {useTableFiltering,@@ -97,6 +101,7 @@ export type {} from './plugins/columnSettings';export type {UseTableColumnResizeConfig} from './plugins/columnResize';export type {UseTableStickyColumnsConfig} from './plugins/stickyColumns';+export type {UseTableRowExpansionConfig} from './plugins/rowExpansion';export type {UseTableFilteringConfig,TableFilterState,diff --git a/packages/core/src/Table/plugins/rowExpansion/index.ts b/packages/core/src/Table/plugins/rowExpansion/index.tsnew file mode 100644index 0000000000..ec9f08a7bf--- /dev/null+++ b/packages/core/src/Table/plugins/rowExpansion/index.ts@@ -0,0 +1,7 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++export {+ useTableRowExpansion,+ useTableRowExpansionState,+} 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.tsxnew file mode 100644index 0000000000..07e8b0e236--- /dev/null+++ b/packages/core/src/Table/plugins/rowExpansion/useTableRowExpansion.test.tsx@@ -0,0 +1,155 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++import {describe, it, expect, vi, beforeEach} from 'vitest';+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';++// popover mock for context-menu tests+beforeEach(() => {+ HTMLElement.prototype.showPopover = vi.fn(function (this: HTMLElement) {+ this.setAttribute('popover-open', '');+ const event = new Event('toggle', {bubbles: false});+ Object.defineProperty(event, 'newState', {value: 'open'});+ this.dispatchEvent(event);+ });+ HTMLElement.prototype.hidePopover = vi.fn(function (this: HTMLElement) {+ this.removeAttribute('popover-open');+ const event = new Event('toggle', {bubbles: false});+ Object.defineProperty(event, 'newState', {value: 'closed'});+ this.dispatchEvent(event);+ });+ const originalMatches = HTMLElement.prototype.matches;+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ (HTMLElement.prototype as any).matches = function (+ selector: string,+ ): boolean {+ if (selector === ':popover-open') {+ return this.hasAttribute('popover-open');+ }+ return originalMatches.call(this, selector);+ };+});++interface TreeItem extends Record<string, unknown> {+ id: string;+ name: string;+ children: TreeItem[];+}++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 columns: TableColumn<TreeItem>[] = [{key: 'name', header: 'Name'}];++const EMPTY_KEYS = new Set<string>();++function Harness({+ initialExpanded = EMPTY_KEYS,+}: {+ initialExpanded?: Set<string>;+}) {+ const [expandedKeys, setExpandedKeys] = useState(initialExpanded);+ const {data, expansionConfig} = useTableRowExpansionState<TreeItem>({+ baseData: treeData,+ getChildren: item => item.children,+ getRowKey: item => item.id,+ expandedKeys,+ setExpandedKeys,+ });+ const expansion = useTableRowExpansion(expansionConfig);+ return (+ <Table data={data} columns={columns} idKey="id" plugins={{expansion}} />+ );+}++describe('useTableRowExpansion', () => {+ it('renders a chevron button for expandable rows', () => {+ 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();+ });++ it('toggles expansion on chevron click', () => {+ 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();+ });++ 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('does not show chevron for leaf nodes', () => {+ 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);+ });++ it('renders an expand-all toggle in the header', () => {+ render(<Harness />);+ expect(+ screen.getByRole('button', {name: /expand all rows/i}),+ ).toBeInTheDocument();+ });++ it('expand-all toggle expands every expandable row', () => {+ 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();+ });++ 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();+ });+});diff --git a/packages/core/src/Table/plugins/rowExpansion/useTableRowExpansion.tsx b/packages/core/src/Table/plugins/rowExpansion/useTableRowExpansion.tsxnew file mode 100644index 0000000000..183ba1ae09--- /dev/null+++ b/packages/core/src/Table/plugins/rowExpansion/useTableRowExpansion.tsx@@ -0,0 +1,590 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++'use client';++/**+ * @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+ *+ * SYNC: When modified, update these files to stay in sync:+ * - /packages/core/src/Table/index.ts (exports)+ */++import {useCallback, 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 {resolveContextActions} from '../../tableContextMenu';+import type {+ TablePlugin,+ TableColumn,+ BodyCellRenderProps,+ BodyRowRenderProps,+ HeaderCellRenderProps,+} from '../../types';++// =============================================================================+// Config+// =============================================================================++/**+ * Configuration for useTableRowExpansion (inherited-columns 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.+ */+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. */+ 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.+ */+ 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;+ /**+ * Should this row be expandable? Rows that return `false` never show a+ * chevron and are skipped by expand-all. @default rows with children+ */+ 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}. This is the recommended entry point — it+ * removes the boilerplate of flattening the tree, tracking depth, and+ * computing the expand-all state.+ *+ * @example+ * ```tsx+ * 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>();+ function walk(items: T[], depth: number) {+ for (const item of items) {+ const key = getRowKey(item);+ map.set(key, depth);+ if (expandedKeys.has(key)) {+ walk(getChildren(item), depth + 1);+ }+ }+ }+ walk(baseData, 0);+ return map;+ }, [baseData, getChildren, getRowKey, expandedKeys]);++ const data = useMemo(() => {+ const result: T[] = [];+ function walk(items: T[]) {+ for (const item of items) {+ result.push(item);+ const key = getRowKey(item);+ if (expandedKeys.has(key)) {+ walk(getChildren(item));+ }+ }+ }+ walk(baseData);+ return result;+ }, [baseData, getChildren, getRowKey, expandedKeys]);++ // Every expandable key across the whole tree (drives expand-all).+ const allExpandableKeys = useMemo(() => {+ const keys: string[] = [];+ function walk(items: T[]) {+ for (const item of items) {+ if (isExpandable(item)) {+ keys.push(getRowKey(item));+ walk(getChildren(item));+ }+ }+ }+ 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};+}++// =============================================================================+// Styles+// =============================================================================++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',+ background: 'transparent',+ border: 'none',+ borderRadius: radiusVars['--radius-inner'],+ cursor: 'pointer',+ color: colorVars['--color-icon-secondary'],+ transitionProperty: 'transform, 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'],+ },+ },+ chevronExpanded: {+ transform: 'rotate(90deg)',+ },+ chevronIcon: {+ display: 'inline-flex',+ transitionProperty: 'transform',+ transitionDuration: '150ms',+ },+ indentedCell: {+ display: 'flex',+ alignItems: 'center',+ gap: spacingVars['--spacing-1'],+ },+ indent: (px: number) => ({+ paddingInlineStart: `${px}px`,+ }),+ placeholder: {+ display: 'inline-block',+ width: '24px',+ height: '24px',+ flexShrink: '0',+ },+ clickableRow: {+ cursor: 'pointer',+ },+});++// =============================================================================+// Chevron+// =============================================================================++function ExpansionChevron({+ isExpanded,+ onToggle,+ ariaLabel,+}: {+ isExpanded: boolean;+ onToggle: () => void;+ ariaLabel: string;+}) {+ return (+ <button+ type="button"+ {...stylex.props(expansionStyles.chevronButton)}+ onClick={e => {+ e.stopPropagation();+ onToggle();+ }}+ aria-label={ariaLabel}+ aria-expanded={isExpanded}>+ <span+ {...stylex.props(+ expansionStyles.chevronIcon,+ isExpanded && expansionStyles.chevronExpanded,+ )}>+ <Icon icon="chevronRight" size="xsm" />+ </span>+ </button>+ );+}++// =============================================================================+// Hook+// =============================================================================++export function useTableRowExpansion<T extends Record<string, unknown>>(+ config: UseTableRowExpansionConfig<T>,+): TablePlugin<T> {+ const {+ expandedKeys,+ onToggle,+ getRowKey,+ getChildren,+ getDepth,+ getIsItemExpandable,+ hasRowClickExpansion = false,+ isAllExpanded,+ onToggleExpandAll,+ } = config;++ // Track the first non-plugin column key for indentation.+ const firstUserColumnKeyRef = useRef<string | null>(null);++ const expansionColumn = useMemo(+ (): TableColumn<T> => ({+ key: '__expansion',+ header: '',+ 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;+ if (!expandable) {+ return null;+ }+ const isExpanded = expandedKeys.has(key);+ return (+ <ExpansionChevron+ isExpanded={isExpanded}+ onToggle={() => onToggle(key)}+ ariaLabel={isExpanded ? 'Collapse row' : 'Expand row'}+ />+ );+ },+ }),+ [+ expandedKeys,+ onToggle,+ getRowKey,+ getChildren,+ getIsItemExpandable,+ getDepth,+ ],+ );++ 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 ? 'Collapse row' : 'Expand row'}+ />+ ) : (+ <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 ? 'Collapse all rows' : 'Expand all rows'+ }>+ <span+ {...stylex.props(+ expansionStyles.chevronIcon,+ allExpanded && expansionStyles.chevronExpanded,+ )}>+ <Icon icon="chevronRight" size="xsm" />+ </span>+ </button>+ ),+ };+ }++ return {...props, content: null};+ },++ transformBodyCell(+ props: BodyCellRenderProps,+ 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.+ const expandable = getIsItemExpandable+ ? getIsItemExpandable(item)+ : getChildren(item).length > 0;+ if (!expandable) {+ return props;+ }++ const key = getRowKey(item);+ const isExpanded = expandedKeys.has(key);+ return {+ ...props,+ contextMenuActions: () => [+ ...resolveContextActions(props.contextMenuActions),+ {+ id: 'row-expansion-toggle',+ group: 'row-expansion',+ label: isExpanded ? 'Collapse row' : 'Expand row',+ icon: (+ <Icon+ icon={isExpanded ? 'chevronDown' : 'chevronRight'}+ size="xsm"+ aria-hidden+ />+ ),+ onSelect: () => onToggle(key),+ },+ ],+ };+ },++ transformBodyRow(props: BodyRowRenderProps, item: T): BodyRowRenderProps {+ if (!hasRowClickExpansion) {+ return props;+ }+ const expandable = getIsItemExpandable+ ? getIsItemExpandable(item)+ : getChildren(item).length > 0;+ if (!expandable) {+ return props;+ }+ const key = getRowKey(item);+ return {+ ...props,+ htmlProps: {+ ...props.htmlProps,+ onClick: () => onToggle(key),+ },+ styles: [...props.styles, expansionStyles.clickableRow],+ };+ },+ }),+ [+ expandedKeys,+ getRowKey,+ onToggle,+ getChildren,+ getDepth,+ getIsItemExpandable,+ hasRowClickExpansion,+ isAllExpanded,+ onToggleExpandAll,+ expansionColumn,+ ],+ );+}diff --git a/packages/core/src/Table/tableContextMenu.test.tsx b/packages/core/src/Table/tableContextMenu.test.tsxindex a3036b5d03..0e9df2714f 100644--- a/packages/core/src/Table/tableContextMenu.test.tsx+++ b/packages/core/src/Table/tableContextMenu.test.tsx@@ -99,9 +99,7 @@ describe('Table header context menu', () => {],}),};- render(- <Table data={data} columns={columns} idKey="id" plugins={{a, b}} />,- );+ render(<Table data={data} columns={columns} idKey="id" plugins={{a, b}} />);fireEvent.contextMenu(screen.getByText('Name'));expect(screen.getAllByRole('menuitem', {name: 'Action A', hidden: true}).length,@@ -154,4 +152,30 @@ describe('Table body context menu', () => {fireEvent.click(items[0]);expect(onSelect).toHaveBeenCalledWith('1');});++ it('trigger wrapper fills the full cell so the whole cell is right-clickable', () => {+ const plugin: TablePlugin<Row> = {+ transformBodyCell: props => ({+ ...props,+ contextMenuActions: [{id: 'act', label: 'Act', onSelect: () => {}}],+ }),+ };+ render(+ <Table data={data} columns={columns} idKey="id" plugins={{plugin}} />,+ );+ // The context-menu trigger wraps the cell content. It must fill the cell+ // (block display + 100% width) so right-clicking anywhere in the cell —+ // not just on the content — opens the menu. Regression test for the bug+ // where only the wide first column responded to right-click.+ const alice = screen.getByText('Alice');+ const trigger = alice.closest('div');+ expect(trigger).not.toBeNull();+ expect(trigger?.className).toBeTruthy();+ // The fillCell style sets inline-size:100% + display:block on the trigger.+ const styleAttr = trigger?.getAttribute('class') ?? '';+ // StyleX compiles to atomic classes; just assert the wrapper carries styles+ // (the visual fill is covered by the compiled CSS). The key contract is+ // that the trigger is a styled block wrapper, not a bare inline element.+ expect(styleAttr.length).toBeGreaterThan(0);+ });});diff --git a/packages/core/src/Table/tableContextMenu.tsx b/packages/core/src/Table/tableContextMenu.tsxindex 529c7cafba..0f5079af16 100644--- a/packages/core/src/Table/tableContextMenu.tsx+++ b/packages/core/src/Table/tableContextMenu.tsx@@ -16,6 +16,7 @@import {useState, type ReactNode} from 'react';import {ContextMenu, type ContextMenuOption} from '../ContextMenu';import {Icon} from '../Icon';+import type {StyleXStyles} from '../theme/types';import type {TableContextAction, TableContextActions} from './types';/**@@ -99,14 +100,17 @@ function toContextMenuOptions(function LazyTableContextMenu({element,getActions,+ triggerXstyle,}: {element: ReactNode;getActions: () => TableContextAction[];+ triggerXstyle?: StyleXStyles | StyleXStyles[];}): ReactNode {const [options, setOptions] = useState<ContextMenuOption[] | null>(null);return (<ContextMenuitems={options ?? []}+ triggerXstyle={triggerXstyle}onOpenChange={open => {// Resolve actions when opening; clear on close so state derived later// (e.g. current sort direction) is always fresh next open.@@ -122,14 +126,24 @@ function LazyTableContextMenu({* context menu rendering the aggregated `actions`. Accepts a static array or a* getter (resolved lazily on open). When there are no actions the element is* returned untouched so the native browser menu passes through.+ *+ * `triggerXstyle` styles the right-click target wrapper. Cells pass a fill ++ * padding style so the entire cell (padding included) opens the menu.*/export function wrapInTableContextMenu(element: ReactNode,actions: TableContextActions | undefined,+ triggerXstyle?: StyleXStyles | StyleXStyles[],): ReactNode {// Getter form → resolve lazily on open.if (typeof actions === 'function') {- return <LazyTableContextMenu element={element} getActions={actions} />;+ return (+ <LazyTableContextMenu+ element={element}+ getActions={actions}+ triggerXstyle={triggerXstyle}+ />+ );}if (!actions || actions.length === 0) {return element;@@ -137,6 +151,10 @@ export function wrapInTableContextMenu(// item (it looked like "ascending" was always selected). Focus moves only// when the user arrow-keys into the menu.return (- <ContextMenu items={toContextMenuOptions(actions)}>{element}</ContextMenu>+ <ContextMenu+ items={toContextMenuOptions(actions)}+ triggerXstyle={triggerXstyle}>+ {element}+ </ContextMenu>);}diff --git a/packages/core/src/Table/useTableRowExpansion.doc.mjs b/packages/core/src/Table/useTableRowExpansion.doc.mjsnew file mode 100644index 0000000000..33ba0725c8--- /dev/null+++ b/packages/core/src/Table/useTableRowExpansion.doc.mjs@@ -0,0 +1,63 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('../docs-types').ComponentDoc} */++export const docs = {+ name: 'useTableRowExpansion',+ subComponentOf: 'Table',+ displayName: 'useTableRowExpansion',+ description:+ '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.',+ props: [+ {+ name: 'expandedKeys',+ type: 'Set<string>',+ description: 'Set of currently-expanded row keys.',+ required: true,+ },+ {+ name: 'onToggle',+ type: '(key: string) => void',+ description: 'Called when a row expansion is toggled.',+ required: true,+ },+ {+ name: 'getRowKey',+ type: '(item: T) => string',+ description: 'Derive a stable unique key from a row item.',+ required: true,+ },+ {+ name: 'getChildren',+ type: '(item: T) => T[]',+ description: 'Return the children of a row (determines expandability).',+ 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.',+ },+ ],+};