An open source design system that's fully customizable and agent ready
TypeScript
feat(core): Table tree whole-row-click expansion (#4142) (#4548)
Humberto Virtudesca5837c770de
diff --git a/.changeset/table-tree-row-click.md b/.changeset/table-tree-row-click.mdnew file mode 100644index 0000000000..3a76bcfdf6--- /dev/null+++ b/.changeset/table-tree-row-click.md@@ -0,0 +1,6 @@+---+'@astryxdesign/core': patch+---++[feat] Table: `useTableTreeData` gains an opt-in `hasRowClickExpansion` prop. When set, clicking anywhere on an expandable row toggles it, in addition to the chevron. Clicks on interactive cell content or a text selection are ignored, leaf rows stay inert, and it is a no-op on flat data. (#4142)+@humbertovirtudesdiff --git a/apps/storybook/stories/TableTree.stories.tsx b/apps/storybook/stories/TableTree.stories.tsxindex 4f060aab67..9a023330c1 100644--- a/apps/storybook/stories/TableTree.stories.tsx+++ b/apps/storybook/stories/TableTree.stories.tsx@@ -249,6 +249,32 @@ export const HeaderExpandAllControl: Story = {},};+/**+ * `hasRowClickExpansion` lets a click anywhere on an expandable row toggle it,+ * in addition to the chevron. Leaf rows stay inert, and the chevron still works+ * on its own (it stops propagation, so a chevron click never double-toggles).+ */+export const RowClickExpansion: Story = {+ render: () => {+ const {visibleData, treeConfig} = useTableTreeState<OrgRow>({+ data: orgChart,+ idKey: 'id',+ defaultExpandedIds: ['eng'],+ });+ const tree = useTableTreeData({...treeConfig, hasRowClickExpansion: true});++ return (+ <Table+ data={visibleData}+ columns={columns}+ idKey="id"+ hasHover+ plugins={{tree}}+ />+ );+ },+};+/*** The `indent` token controls the step per level: `sm` (spacing-3), `md`* (spacing-4, the default), and `lg` (spacing-6).diff --git a/packages/core/src/Table/plugins/tree/useTableTreeData.test.tsx b/packages/core/src/Table/plugins/tree/useTableTreeData.test.tsxindex dcf1bfe7cf..bdab599a16 100644--- a/packages/core/src/Table/plugins/tree/useTableTreeData.test.tsx+++ b/packages/core/src/Table/plugins/tree/useTableTreeData.test.tsx@@ -58,15 +58,20 @@ function TreeTable(props: Partial<UseTableTreeStateConfig<FileRow>> & {data?: FileRow[];hasExpandAllControl?: boolean;+ hasRowClickExpansion?: boolean;},) {- const {hasExpandAllControl, ...stateProps} = props;+ const {hasExpandAllControl, hasRowClickExpansion, ...stateProps} = props;const {visibleData, treeConfig} = useTableTreeState<FileRow>({data: props.data ?? fileTree,idKey: 'id',...stateProps,});- const tree = useTableTreeData({...treeConfig, hasExpandAllControl});+ const tree = useTableTreeData({+ ...treeConfig,+ hasExpandAllControl,+ hasRowClickExpansion,+ });return (<Table data={visibleData} columns={columns} idKey="id" plugins={{tree}} />@@ -153,6 +158,160 @@ describe('useTableTreeData — expander', () => {});});+// =============================================================================+// Whole-row-click expansion+// =============================================================================++describe('useTableTreeData — row-click expansion', () => {+ it('does not toggle on row click when hasRowClickExpansion is unset', async () => {+ const user = userEvent.setup();+ render(<TreeTable />);++ await user.click(within(getRowByText('src')).getByText('src'));++ // Row body click is inert by default: subtree stays collapsed.+ expect(screen.queryByText('components')).toBeNull();+ expect(+ within(getRowByText('src')).getByRole('button', {name: 'Expand row'}),+ ).toBeInTheDocument();+ });++ it('expands an expandable row when its body is clicked', async () => {+ const user = userEvent.setup();+ render(<TreeTable hasRowClickExpansion />);++ await user.click(within(getRowByText('src')).getByText('src'));++ expect(screen.getByText('components')).toBeInTheDocument();+ expect(screen.getByText('utils.ts')).toBeInTheDocument();+ expect(+ within(getRowByText('src')).getByRole('button', {name: 'Collapse row'}),+ ).toBeInTheDocument();+ });++ it('collapses an expanded row when its body is clicked', async () => {+ const user = userEvent.setup();+ render(<TreeTable hasRowClickExpansion defaultExpandedIds={['src']} />);++ expect(screen.getByText('components')).toBeInTheDocument();++ await user.click(within(getRowByText('src')).getByText('src'));++ expect(screen.queryByText('components')).toBeNull();+ expect(+ within(getRowByText('src')).getByRole('button', {name: 'Expand row'}),+ ).toBeInTheDocument();+ });++ it('does not toggle when a leaf row body is clicked', async () => {+ const user = userEvent.setup();+ render(<TreeTable hasRowClickExpansion />);++ const before = screen.getAllByRole('row').length;+ await user.click(within(getRowByText('README.md')).getByText('README.md'));++ // Leaf has no expansion: row count is unchanged.+ expect(screen.getAllByRole('row')).toHaveLength(before);+ });++ it('toggles once when the chevron is clicked (no double-toggle via row click)', async () => {+ const user = userEvent.setup();+ const onToggle = vi.fn();++ function SpyTree() {+ const {visibleData, treeConfig} = useTableTreeState<FileRow>({+ data: fileTree,+ idKey: 'id',+ });+ const tree = useTableTreeData({+ ...treeConfig,+ hasRowClickExpansion: true,+ onToggleItem: item => {+ onToggle(item);+ treeConfig.onToggleItem(item);+ },+ });+ return (+ <Table+ data={visibleData}+ columns={columns}+ idKey="id"+ plugins={{tree}}+ />+ );+ }++ render(<SpyTree />);++ await user.click(+ within(getRowByText('src')).getByRole('button', {name: 'Expand row'}),+ );++ // The chevron stops propagation, so a chevron click toggles exactly once.+ expect(onToggle).toHaveBeenCalledTimes(1);+ expect(screen.getByText('components')).toBeInTheDocument();+ });++ it('does not toggle when an interactive control inside the row is clicked', async () => {+ const user = userEvent.setup();+ // Compose with selection: each row carries a checkbox in its own column.+ function TreeWithSelection() {+ const [selectedKeys, setSelectedKeys] = useState<Set<string>>(+ () => new Set(),+ );+ const {visibleData, treeConfig} = useTableTreeState<FileRow>({+ data: fileTree,+ idKey: 'id',+ });+ const {selectionConfig} = useTableSelectionState<FileRow>({+ data: visibleData,+ idKey: 'id',+ selectedKeys,+ setSelectedKeys,+ });+ const selection = useTableSelection<FileRow>(selectionConfig);+ const tree = useTableTreeData({+ ...treeConfig,+ hasRowClickExpansion: true,+ });+ return (+ <Table+ data={visibleData}+ columns={columns}+ idKey="id"+ plugins={{tree, selection}}+ />+ );+ }++ render(<TreeWithSelection />);++ const srcRow = getRowByText('src');+ const cells = within(srcRow).getAllByRole('cell');+ await user.click(within(cells[0]).getByRole('checkbox'));++ // Clicking the checkbox selects the row but must NOT expand it.+ expect(screen.queryByText('components')).toBeNull();+ expect(+ within(getRowByText('src')).getByRole('button', {name: 'Expand row'}),+ ).toBeInTheDocument();+ });++ it('is a no-op on flat data even when hasRowClickExpansion is set', async () => {+ const user = userEvent.setup();+ const flat: FileRow[] = [+ {id: 'a', name: 'a.txt', size: 1},+ {id: 'b', name: 'b.txt', size: 2},+ ];+ render(<TreeTable data={flat} hasRowClickExpansion />);++ const before = screen.getAllByRole('row').length;+ await user.click(within(getRowByText('a.txt')).getByText('a.txt'));++ expect(screen.getAllByRole('row')).toHaveLength(before);+ });+});+// =============================================================================// Row ARIA// =============================================================================diff --git a/packages/core/src/Table/plugins/tree/useTableTreeData.tsx b/packages/core/src/Table/plugins/tree/useTableTreeData.tsxindex 65318f5c8c..8d1d6ed772 100644--- a/packages/core/src/Table/plugins/tree/useTableTreeData.tsx+++ b/packages/core/src/Table/plugins/tree/useTableTreeData.tsx@@ -106,6 +106,17 @@ export interface UseTableTreeDataConfig<T extends Record<string, unknown>> {indent?: 'sm' | 'md' | 'lg';/** Column that carries the indent + expander. @default the first column */treeColumnKey?: string;+ /**+ * When true, clicking anywhere on an expandable row toggles its expansion,+ * in addition to the chevron. Leaf rows stay inert. No-op on flat data.+ *+ * This is a pointer-only convenience layered over the chevron: keyboard and+ * assistive-tech users toggle via the chevron button (which stays the+ * accessible control). Clicks originating from interactive cell content+ * (buttons, links, form controls) or a text selection do not toggle.+ * @default false (only the chevron toggles expansion).+ */+ hasRowClickExpansion?: boolean;}// =============================================================================@@ -271,6 +282,10 @@ const treeStyles = stylex.create({gap: spacingVars['--spacing-1'],minWidth: 0,},+ /** Whole-row-click expansion: signal the row is interactive. */+ clickableRow: {+ cursor: 'pointer',+ },});// =============================================================================@@ -616,10 +631,48 @@ export function useTableTreeData<T extends Record<string, unknown>>(};};- return {+ const withRef = {...props,ref: props.ref ? mergeRefs(props.ref, treeRef) : treeRef,};++ // Whole-row-click expansion (opt-in). Only expandable rows are+ // clickable; leaves and flat data stay inert. `hasExpandableRows` is+ // the feature-level flag (short-circuits the whole feature when off);+ // `hasChildren` is the per-row check — both are intentional.+ const cfg = store.getConfig();+ const rowClickExpandable =+ cfg.hasRowClickExpansion === true &&+ cfg.hasExpandableRows &&+ cfg.getRowMeta(item)?.hasChildren === true;+ if (!rowClickExpandable) {+ return withRef;+ }++ return {+ ...withRef,+ htmlProps: {+ ...withRef.htmlProps,+ onClick: (event: React.MouseEvent<HTMLTableRowElement>) => {+ // Don't hijack clicks on interactive cell content (the chevron+ // already stops propagation, but a composed selection checkbox,+ // link, or action button does not) or a text selection.+ const target = event.target as HTMLElement;+ if (+ target.closest(+ 'button, a, input, select, textarea, [role="button"], [role="checkbox"], [contenteditable="true"]',+ )+ ) {+ return;+ }+ if ((window.getSelection()?.toString() ?? '') !== '') {+ return;+ }+ cfg.onToggleItem(item);+ },+ },+ xstyle: [...withRef.xstyle, treeStyles.clickableRow],+ };},};}, [store]);diff --git a/packages/core/src/Table/useTableTreeData.doc.mjs b/packages/core/src/Table/useTableTreeData.doc.mjsindex 321bfde7be..eaead41bca 100644--- a/packages/core/src/Table/useTableTreeData.doc.mjs+++ b/packages/core/src/Table/useTableTreeData.doc.mjs@@ -65,6 +65,13 @@ export const docs = {description:'Column that carries the indent + expander. Defaults to the first column.',},+ {+ name: 'hasRowClickExpansion',+ type: 'boolean',+ description:+ 'When true, clicking anywhere on an expandable row toggles its expansion, in addition to the chevron. A pointer-only convenience: keyboard and assistive-tech users toggle via the chevron button. Clicks on interactive cell content (buttons, links, form controls) or a text selection do not toggle. Leaf rows stay inert, and it is a no-op on flat data.',+ default: 'false',+ },],examples: [{@@ -100,5 +107,7 @@ export const docsDense = {"aggregate state driving the header toggle: true (all) | false (none) | 'indeterminate' (some).",onExpandAll: 'expand every expandable row (header control)',onCollapseAll: 'collapse every row (header control)',+ hasRowClickExpansion:+ 'true => clicking an expandable row body toggles it (in addition to the chevron). Leaves stay inert; no-op on flat data. Defaults to false.',},};