An open source design system that's fully customizable and agent ready
TypeScript
feat(core): add useTableGroupedRows plugin (#3763)
Humberto Virtudes7a3676408fb1
diff --git a/.changeset/table-grouped-rows.md b/.changeset/table-grouped-rows.mdnew file mode 100644index 0000000000..f485fe6e64--- /dev/null+++ b/.changeset/table-grouped-rows.md@@ -0,0 +1,16 @@+---+'@astryxdesign/core': patch+---++[feat] Add `useTableGroupedRows` — groups a flat data array into collapsible+section rows.++- Each distinct `groupBy` value becomes a full-width section-header row with a+ chevron toggle, group label, and member count; collapsing hides that group's+ rows while keeping the header.+- Mirrors `useTableRowExpansionState`: consumer owns the `collapsedGroups` set;+ the hook returns `{data, plugin, idKey}` (pass to `Table` data / plugins /+ idKey — `idKey` is named for parallelism with the Table prop). Supports+ `renderGroupHeader` and `groupOrder`.++@humbertovirtudesdiff --git a/apps/sandbox/src/app/(sandbox)/pages/table-lab/page.tsx b/apps/sandbox/src/app/(sandbox)/pages/table-lab/page.tsxindex dd6fd224a1..39a28102c8 100644--- a/apps/sandbox/src/app/(sandbox)/pages/table-lab/page.tsx+++ b/apps/sandbox/src/app/(sandbox)/pages/table-lab/page.tsx@@ -47,6 +47,7 @@ import {useTableStickyColumns,useTableRowExpansion,useTableRowExpansionState,+ useTableGroupedRows,} from '@astryxdesign/core/Table';import type {TablePlugin, TableSortState} from '@astryxdesign/core/Table';@@ -68,7 +69,8 @@ type PluginId =| 'pagination'| 'columnResize'| 'stickyColumns'- | 'rowExpansion';+ | 'rowExpansion'+ | 'groupedRows';interface PluginMeta {id: PluginId;@@ -103,6 +105,11 @@ const PLUGIN_REGISTRY: PluginMeta[] = [label: 'Row Expansion',description: 'Expandable tree rows (grouped by team)',},+ {+ id: 'groupedRows',+ label: 'Grouped Rows',+ description: 'Collapsible sections grouped by team',+ },];// =============================================================================@@ -118,6 +125,8 @@ interface UseLabPluginsArgs {interface UseLabPluginsResult {data: LabRow[];plugins: Record<string, TablePlugin<LabRow>>;+ /** idKey passed to <Table>. Grouped rows override this to key synthetic headers. */+ idKey: (keyof LabRow & string) | ((item: LabRow) => string);/** Summary chips for the active-plugin state (selected count, page, etc). */summary: string[];}@@ -196,8 +205,37 @@ function useLabPlugins({summary.push(`${expandedKeys.size} expanded`);}+ // --- grouped rows (collapsible sections by team) ---+ const [collapsedGroups, setCollapsedGroups] = useState<Set<string>>(+ new Set(),+ );+ const toggleGroup = useCallback((key: string) => {+ setCollapsedGroups(prev => {+ const next = new Set(prev);+ if (next.has(key)) {+ next.delete(key);+ } else {+ next.add(key);+ }+ return next;+ });+ }, []);+ const grouped = useTableGroupedRows<LabRow>({+ data: dataAfterPage,+ groupBy: item => item.team,+ collapsedGroups,+ onToggleGroup: toggleGroup,+ getRowKey: item => item.id,+ });+ if (enabled.groupedRows) {+ summary.push(`${collapsedGroups.size} groups collapsed`);+ }+// Assemble enabled plugins in a stable order.const plugins: Record<string, TablePlugin<LabRow>> = {};+ if (enabled.groupedRows) {+ plugins.grouped = grouped.plugin;+ }if (enabled.sortable) {plugins.sort = sortPlugin;}@@ -217,7 +255,12 @@ function useLabPlugins({plugins.pagination = paginationPlugin;}- return {data: dataAfterPage, plugins, summary};+ return {+ data: enabled.groupedRows ? grouped.data : dataAfterPage,+ plugins,+ idKey: enabled.groupedRows ? grouped.idKey : 'id',+ summary,+ };}// =============================================================================@@ -370,10 +413,11 @@ export default function TableLabPage() {columnResize: false,stickyColumns: false,rowExpansion: false,+ groupedRows: false,});const baseData = useMemo(() => generateRows(rowCount), [rowCount]);- const {data, plugins, summary} = useLabPlugins({enabled, baseData});+ const {data, plugins, idKey, summary} = useLabPlugins({enabled, baseData});const {renderStatsRef,@@ -498,7 +542,7 @@ export default function TableLabPage() {<Tabledata={data}columns={labColumns}- idKey="id"+ idKey={idKey}hasHoverisStripedplugins={plugins}diff --git a/apps/storybook/stories/TableGroupedRows.stories.tsx b/apps/storybook/stories/TableGroupedRows.stories.tsxnew file mode 100644index 0000000000..e6229d9e9d--- /dev/null+++ b/apps/storybook/stories/TableGroupedRows.stories.tsx@@ -0,0 +1,148 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++import {useState, useCallback} from 'react';+import type {Meta, StoryObj} from '@storybook/react';+import {+ Table,+ useTableGroupedRows,+ proportional,+ pixel,+} from '@astryxdesign/core/Table';+import type {TableColumn} from '@astryxdesign/core/Table';++// =============================================================================+// Sample Data+// =============================================================================++interface Person extends Record<string, unknown> {+ id: string;+ name: string;+ team: string;+ role: string;+}++const people: Person[] = [+ {id: '1', name: 'Ava Chen', team: 'Design Systems', role: 'Staff Eng'},+ {id: '2', name: 'Liam Park', team: 'Design Systems', role: 'Engineer'},+ {id: '3', name: 'Zoe Vega', team: 'Design Systems', role: 'Manager'},+ {id: '4', name: 'Max Ross', team: 'Infra', role: 'Senior Eng'},+ {id: '5', name: 'Mia Cole', team: 'Infra', role: 'Engineer'},+ {id: '6', name: 'Leo Nash', team: 'Growth', role: 'PM'},+];++const columns: TableColumn<Person>[] = [+ {key: 'name', header: 'Name', width: proportional(2)},+ {key: 'role', header: 'Role', width: pixel(140)},+];++const meta: Meta = {+ title: 'Core/TableGroupedRows',+ tags: ['autodocs'],+};++export default meta;+type Story = StoryObj;++function useCollapsed(initial: string[] = []) {+ const [collapsedGroups, setCollapsed] = useState<Set<string>>(+ new Set(initial),+ );+ const onToggleGroup = useCallback((key: string) => {+ setCollapsed(prev => {+ const next = new Set(prev);+ if (next.has(key)) {+ next.delete(key);+ } else {+ next.add(key);+ }+ return next;+ });+ }, []);+ return {collapsedGroups, onToggleGroup};+}++/**+ * Rows are grouped into collapsible sections by `groupBy`. Each section gets a+ * full-width header with a chevron, the group label, and a member count.+ * Click a header (or its chevron) to collapse/expand that group.+ */+export const Default: Story = {+ render: () => {+ const {collapsedGroups, onToggleGroup} = useCollapsed();+ const grouped = useTableGroupedRows<Person>({+ data: people,+ groupBy: p => p.team,+ collapsedGroups,+ onToggleGroup,+ getRowKey: p => p.id,+ });+ return (+ <Table+ data={grouped.data}+ columns={columns}+ idKey={grouped.idKey}+ hasHover+ plugins={{grouped: grouped.plugin}}+ />+ );+ },+};++/**+ * Groups can start collapsed — pass their keys in the initial `collapsedGroups`+ * set. Here "Infra" begins collapsed.+ */+export const InitiallyCollapsed: Story = {+ render: () => {+ const {collapsedGroups, onToggleGroup} = useCollapsed(['Infra']);+ const grouped = useTableGroupedRows<Person>({+ data: people,+ groupBy: p => p.team,+ collapsedGroups,+ onToggleGroup,+ getRowKey: p => p.id,+ });+ return (+ <Table+ data={grouped.data}+ columns={columns}+ idKey={grouped.idKey}+ hasHover+ plugins={{grouped: grouped.plugin}}+ />+ );+ },+};++/**+ * `groupOrder` pins specific groups to the front; `renderGroupHeader`+ * customizes the header content shown to the right of the chevron.+ */+export const CustomOrderAndHeader: Story = {+ render: () => {+ const {collapsedGroups, onToggleGroup} = useCollapsed();+ const grouped = useTableGroupedRows<Person>({+ data: people,+ groupBy: p => p.team,+ collapsedGroups,+ onToggleGroup,+ getRowKey: p => p.id,+ groupOrder: ['Growth', 'Infra'],+ renderGroupHeader: (key, count, collapsed) => (+ <span>+ <strong>{key}</strong> — {count} {count === 1 ? 'person' : 'people'}+ {collapsed ? ' (hidden)' : ''}+ </span>+ ),+ });+ return (+ <Table+ data={grouped.data}+ columns={columns}+ idKey={grouped.idKey}+ hasHover+ plugins={{grouped: grouped.plugin}}+ />+ );+ },+};diff --git a/packages/cli/templates/blocks/components/Table/TableGroupedRowsTable.doc.mjs b/packages/cli/templates/blocks/components/Table/TableGroupedRowsTable.doc.mjsnew file mode 100644index 0000000000..1fd32b2cf5--- /dev/null+++ b/packages/cli/templates/blocks/components/Table/TableGroupedRowsTable.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: 'useTableGroupedRows',+ name: 'useTableGroupedRows — Collapsible Groups',+ displayName: 'useTableGroupedRows — Collapsible Groups',+ description:+ 'A table grouped into collapsible sections with useTableGroupedRows. Each group gets a full-width header with a chevron, label, and member count; click to collapse/expand.',+ isReady: true,+ aspectRatio: 16 / 9,+ componentsUsed: ['Table'],+};diff --git a/packages/cli/templates/blocks/components/Table/TableGroupedRowsTable.tsx b/packages/cli/templates/blocks/components/Table/TableGroupedRowsTable.tsxnew file mode 100644index 0000000000..8b8ccab951--- /dev/null+++ b/packages/cli/templates/blocks/components/Table/TableGroupedRowsTable.tsx@@ -0,0 +1,66 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++'use client';++import {useState, useCallback} from 'react';+import {+ Table,+ useTableGroupedRows,+ proportional,+ pixel,+} from '@astryxdesign/core/Table';+import type {TableColumn} from '@astryxdesign/core/Table';++interface Person extends Record<string, unknown> {+ id: string;+ name: string;+ team: string;+ role: string;+}++const people: Person[] = [+ {id: '1', name: 'Ava Chen', team: 'Design Systems', role: 'Staff Eng'},+ {id: '2', name: 'Liam Park', team: 'Design Systems', role: 'Engineer'},+ {id: '3', name: 'Zoe Vega', team: 'Design Systems', role: 'Manager'},+ {id: '4', name: 'Max Ross', team: 'Infra', role: 'Senior Eng'},+ {id: '5', name: 'Mia Cole', team: 'Infra', role: 'Engineer'},+ {id: '6', name: 'Leo Nash', team: 'Growth', role: 'PM'},+];++const columns: TableColumn<Person>[] = [+ {key: 'name', header: 'Name', width: proportional(2)},+ {key: 'role', header: 'Role', width: pixel(140)},+];++export default function TableGroupedRowsTable() {+ const [collapsedGroups, setCollapsed] = useState<Set<string>>(new Set());+ const onToggleGroup = useCallback((key: string) => {+ setCollapsed(prev => {+ const next = new Set(prev);+ if (next.has(key)) {+ next.delete(key);+ } else {+ next.add(key);+ }+ return next;+ });+ }, []);++ const grouped = useTableGroupedRows<Person>({+ data: people,+ groupBy: p => p.team,+ collapsedGroups,+ onToggleGroup,+ getRowKey: p => p.id,+ });++ return (+ <Table+ data={grouped.data}+ columns={columns}+ idKey={grouped.idKey}+ hasHover+ plugins={{grouped: grouped.plugin}}+ />+ );+}diff --git a/packages/core/src/Table/index.ts b/packages/core/src/Table/index.tsindex ed33e7bf17..8bd5f5e63c 100644--- a/packages/core/src/Table/index.ts+++ b/packages/core/src/Table/index.ts@@ -26,6 +26,7 @@ export {useTableColumnSettings} from './plugins/columnSettings';export {useTableColumnSettingsState} from './plugins/columnSettings';export {useTableColumnResize} from './plugins/columnResize';export {useTableStickyColumns} from './plugins/stickyColumns';+export {useTableGroupedRows} from './plugins/groupedRows';export {useTableRowExpansion,useTableRowExpansionState,@@ -102,6 +103,10 @@ export type {export type {UseTableColumnResizeConfig} from './plugins/columnResize';export type {UseTableStickyColumnsConfig} from './plugins/stickyColumns';export type {UseTableRowExpansionConfig} from './plugins/rowExpansion';+export type {+ UseTableGroupedRowsConfig,+ UseTableGroupedRowsResult,+} from './plugins/groupedRows';export type {UseTableFilteringConfig,TableFilterState,diff --git a/packages/core/src/Table/plugins/groupedRows/index.ts b/packages/core/src/Table/plugins/groupedRows/index.tsnew file mode 100644index 0000000000..82dc750e49--- /dev/null+++ b/packages/core/src/Table/plugins/groupedRows/index.ts@@ -0,0 +1,7 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++export {useTableGroupedRows} from './useTableGroupedRows';+export type {+ UseTableGroupedRowsConfig,+ UseTableGroupedRowsResult,+} from './useTableGroupedRows';diff --git a/packages/core/src/Table/plugins/groupedRows/useTableGroupedRows.test.tsx b/packages/core/src/Table/plugins/groupedRows/useTableGroupedRows.test.tsxnew file mode 100644index 0000000000..cc5bffd7da--- /dev/null+++ b/packages/core/src/Table/plugins/groupedRows/useTableGroupedRows.test.tsx@@ -0,0 +1,231 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++import {describe, it, expect} from 'vitest';+import {render, screen, fireEvent, within} from '@testing-library/react';+import {useState, useCallback} from 'react';+import {Table} from '../../Table';+import type {TableColumn} from '../../types';+import {useTableGroupedRows} from './useTableGroupedRows';++interface Person extends Record<string, unknown> {+ id: string;+ name: string;+ team: string;+}++const people: Person[] = [+ {id: 'a', name: 'Alice', team: 'Core'},+ {id: 'b', name: 'Bob', team: 'Core'},+ {id: 'c', name: 'Carol', team: 'Infra'},+];++const columns: TableColumn<Person>[] = [{key: 'name', header: 'Name'}];++const EMPTY = new Set<string>();++function Harness({+ rows = people,+ initialCollapsed = EMPTY,+ renderGroupHeader,+}: {+ rows?: Person[];+ initialCollapsed?: Set<string>;+ renderGroupHeader?: (+ groupKey: string,+ count: number,+ collapsed: boolean,+ ) => React.ReactNode;+}) {+ const [collapsedGroups, setCollapsed] = useState(initialCollapsed);+ const onToggleGroup = useCallback((key: string) => {+ setCollapsed(prev => {+ const next = new Set(prev);+ if (next.has(key)) {+ next.delete(key);+ } else {+ next.add(key);+ }+ return next;+ });+ }, []);+ const grouped = useTableGroupedRows<Person>({+ data: rows,+ groupBy: p => p.team,+ collapsedGroups,+ onToggleGroup,+ getRowKey: p => p.id,+ renderGroupHeader,+ });+ return (+ <Table+ data={grouped.data}+ columns={columns}+ idKey={grouped.idKey}+ plugins={{grouped: grouped.plugin}}+ />+ );+}++describe('useTableGroupedRows', () => {+ it('renders a header row per group with label and count', () => {+ render(<Harness />);+ // Two groups: Core (2), Infra (1).+ expect(screen.getByText('Core')).toBeInTheDocument();+ expect(screen.getByText('(2)')).toBeInTheDocument();+ expect(screen.getByText('Infra')).toBeInTheDocument();+ expect(screen.getByText('(1)')).toBeInTheDocument();+ });++ it('shows group members when expanded', () => {+ render(<Harness />);+ expect(screen.getByText('Alice')).toBeInTheDocument();+ expect(screen.getByText('Bob')).toBeInTheDocument();+ expect(screen.getByText('Carol')).toBeInTheDocument();+ });++ it('hides members of a collapsed group but keeps the header', () => {+ render(<Harness initialCollapsed={new Set(['Core'])} />);+ expect(screen.getByText('Core')).toBeInTheDocument();+ expect(screen.queryByText('Alice')).not.toBeInTheDocument();+ expect(screen.queryByText('Bob')).not.toBeInTheDocument();+ // Other group unaffected.+ expect(screen.getByText('Carol')).toBeInTheDocument();+ });++ it('toggles a group via its chevron and back again', () => {+ render(<Harness />);+ expect(screen.getByText('Alice')).toBeInTheDocument();+ // The standalone chevron button toggles the group; its accessible name is+ // qualified with the group key.+ fireEvent.click(screen.getByRole('button', {name: 'Collapse group Core'}));+ expect(screen.queryByText('Alice')).not.toBeInTheDocument();+ expect(screen.queryByText('Bob')).not.toBeInTheDocument();+ expect(screen.getByText('Core')).toBeInTheDocument();+ expect(screen.getByText('Carol')).toBeInTheDocument();+ // Toggle back: the Core chevron now says "Expand group Core".+ fireEvent.click(screen.getByRole('button', {name: 'Expand group Core'}));+ expect(screen.getByText('Alice')).toBeInTheDocument();+ expect(screen.getByText('Bob')).toBeInTheDocument();+ });++ it('exposes each group toggle as a named, keyboard-operable button', () => {+ render(<Harness />);+ // Native <button>: focusable and operable without a custom key handler.+ const coreToggle = screen.getByRole('button', {+ name: 'Collapse group Core',+ });+ expect(coreToggle.tagName).toBe('BUTTON');+ expect(coreToggle).toHaveAttribute('aria-expanded', 'true');+ });++ it('sets aria-expanded on the header row reflecting collapse state', () => {+ render(<Harness initialCollapsed={new Set(['Core'])} />);+ const rows = screen.getAllByRole('row');+ // rows[1] = Core header (collapsed), rows[2] = Infra header (expanded).+ expect(rows[1]).toHaveAttribute('aria-expanded', 'false');+ expect(rows[2]).toHaveAttribute('aria-expanded', 'true');+ });++ it('respects groupOrder in the flattened data', () => {+ function OrderedHarness() {+ const [collapsed, setCollapsed] = useState<Set<string>>(new Set());+ const grouped = useTableGroupedRows<Person>({+ data: people,+ groupBy: p => p.team,+ collapsedGroups: collapsed,+ onToggleGroup: k => setCollapsed(new Set([k])),+ getRowKey: p => p.id,+ groupOrder: ['Infra', 'Core'],+ });+ expect(grouped.data.length).toBeGreaterThan(0);+ return (+ <Table+ data={grouped.data}+ columns={columns}+ idKey={grouped.idKey}+ plugins={{grouped: grouped.plugin}}+ />+ );+ }+ render(<OrderedHarness />);+ const rows = screen.getAllByRole('row');+ // rows[0] = column header; rows[1] = first group header (Infra).+ expect(within(rows[1]).getByText('Infra')).toBeInTheDocument();+ });++ it('renders custom group header content via renderGroupHeader', () => {+ render(+ <Harness+ renderGroupHeader={(key, count, collapsed) => (+ <span>{`${key}::${count}::${collapsed ? 'closed' : 'open'}`}</span>+ )}+ />,+ );+ expect(screen.getByText('Core::2::open')).toBeInTheDocument();+ expect(screen.getByText('Infra::1::open')).toBeInTheDocument();+ });++ it('renders nothing (no group headers) for empty data', () => {+ render(<Harness rows={[]} />);+ // Column header row still renders; no group header rows.+ expect(screen.queryByText('Core')).not.toBeInTheDocument();+ expect(screen.queryByText('Infra')).not.toBeInTheDocument();+ expect(+ screen.queryByRole('button', {name: /group/i}),+ ).not.toBeInTheDocument();+ });++ it('keeps a group collapsed across a data change (state keyed by group)', () => {+ function ChangingHarness() {+ const [collapsed, setCollapsed] = useState<Set<string>>(+ new Set(['Core']),+ );+ const [rows, setRows] = useState(people);+ const onToggleGroup = useCallback((key: string) => {+ setCollapsed(prev => {+ const next = new Set(prev);+ if (next.has(key)) {+ next.delete(key);+ } else {+ next.add(key);+ }+ return next;+ });+ }, []);+ const grouped = useTableGroupedRows<Person>({+ data: rows,+ groupBy: p => p.team,+ collapsedGroups: collapsed,+ onToggleGroup,+ getRowKey: p => p.id,+ });+ return (+ <>+ <button+ type="button"+ onClick={() =>+ setRows([...people, {id: 'd', name: 'Dave', team: 'Core'}])+ }>+ add+ </button>+ <Table+ data={grouped.data}+ columns={columns}+ idKey={grouped.idKey}+ plugins={{grouped: grouped.plugin}}+ />+ </>+ );+ }+ render(<ChangingHarness />);+ // Core collapsed initially: Alice hidden.+ expect(screen.queryByText('Alice')).not.toBeInTheDocument();+ // Add a new Core member; Core must stay collapsed (keyed by group value).+ fireEvent.click(screen.getByText('add'));+ expect(screen.queryByText('Alice')).not.toBeInTheDocument();+ expect(screen.queryByText('Dave')).not.toBeInTheDocument();+ // Count reflects the new member (3), header still present.+ expect(screen.getByText('Core')).toBeInTheDocument();+ expect(screen.getByText('(3)')).toBeInTheDocument();+ });+});diff --git a/packages/core/src/Table/plugins/groupedRows/useTableGroupedRows.tsx b/packages/core/src/Table/plugins/groupedRows/useTableGroupedRows.tsxnew file mode 100644index 0000000000..211b85471b--- /dev/null+++ b/packages/core/src/Table/plugins/groupedRows/useTableGroupedRows.tsx@@ -0,0 +1,349 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++'use client';++/**+ * @file useTableGroupedRows.tsx+ * @input React, StyleX, Icon, Table types + the flat data array+ * @output Exports useTableGroupedRows hook + config/result types+ * @position Grouped-rows 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, type ReactNode} from 'react';+import * as stylex from '@stylexjs/stylex';+import {+ spacingVars,+ colorVars,+ fontWeightVars,+} from '../../../theme/tokens.stylex';+import {Icon} from '../../../Icon';+import type {TablePlugin} from '../../types';++// A synthetic group-header row injected into the flattened data. Real rows+// never carry this marker.+const GROUP_HEADER = Symbol('tableGroupHeader');++interface GroupHeader {+ [GROUP_HEADER]: true;+ groupKey: string;+ count: number;+}++function isGroupHeader(item: unknown): item is GroupHeader {+ return (+ typeof item === 'object' &&+ item !== null &&+ (item as Record<symbol, unknown>)[GROUP_HEADER] === true+ );+}++// Proxy handler: any field access beyond the marker fields resolves to `''`+// so user cell renderers (`item.name.toUpperCase()`) never throw on a header.+const HEADER_PROXY_HANDLER: ProxyHandler<Record<string | symbol, unknown>> = {+ // eslint-disable-next-line @typescript-eslint/promise-function-async -- Proxy get trap, not a promise-returning fn+ get(t: Record<string | symbol, unknown>, prop: string | symbol): unknown {+ if (prop === GROUP_HEADER || prop === 'groupKey' || prop === 'count') {+ return t[prop];+ }+ return prop in t ? t[prop] : '';+ },+};++/**+ * Build a synthetic header row wrapped in a Proxy so arbitrary field access+ * from user cell renderers (e.g. `item.name.toUpperCase()`) resolves to `''`+ * instead of throwing — BaseTable evaluates `col.renderCell(item)` on every+ * row (including synthetic headers) before `transformBodyRow` can replace the+ * row's cells. `transformBodyRow` then discards those cells and renders a+ * single full-width header cell.+ */+function makeHeader<T extends Record<string, unknown>>(+ groupKey: string,+ count: number,+): T {+ const target: Record<string | symbol, unknown> = {+ [GROUP_HEADER]: true,+ groupKey,+ count,+ };+ return new Proxy(target, HEADER_PROXY_HANDLER) as unknown as T;+}++/** Configuration for {@link useTableGroupedRows}. */+export interface UseTableGroupedRowsConfig<T extends Record<string, unknown>> {+ /** The flat data to group. */+ data: T[];+ /** Derive the group key for a row. Rows with the same key share a section. */+ groupBy: (item: T) => string;+ /** Set of currently-collapsed group keys. */+ collapsedGroups: Set<string>;+ /** Called with a group key when its header is toggled. */+ onToggleGroup: (groupKey: string) => void;+ /**+ * Custom renderer for a group header's content (right of the chevron).+ * Defaults to `<groupKey> (<count>)`.+ */+ renderGroupHeader?: (+ groupKey: string,+ count: number,+ collapsed: boolean,+ ) => ReactNode;+ /** Stable key for a real row. Falls back to a positional key when omitted. */+ getRowKey?: (item: T) => string;+ /** Explicit group ordering; groups not listed keep first-seen order after these. */+ groupOrder?: string[];+}++export interface UseTableGroupedRowsResult<T extends Record<string, unknown>> {+ /** Ready-to-use plugin for `<Table plugins>`. */+ plugin: TablePlugin<T>;+ /** Flattened rows: `[header, ...visibleRows, header, ...visibleRows]`. */+ data: T[];+ /**+ * Row-key resolver (also keys synthetic headers as `__group_<key>`). Pass to+ * `<Table idKey>` — named for parallelism with the Table prop:+ * `<Table idKey={grouped.idKey} />`.+ */+ idKey: (item: T) => string;+}++const styles = stylex.create({+ headerRow: {+ cursor: 'pointer',+ userSelect: 'none',+ backgroundColor: colorVars['--color-background-muted'],+ // Divider beneath each group header row (Ernest review #2).+ borderBottomWidth: '1px',+ borderBottomStyle: 'solid',+ borderBottomColor: colorVars['--color-border'],+ },+ headerCell: {+ paddingBlock: spacingVars['--spacing-2'],+ // No inline start padding so the chevron aligns with the table's leading+ // edge (Ernest review #1).+ paddingInlineStart: spacingVars['--spacing-1'],+ paddingInlineEnd: spacingVars['--spacing-3'],+ },+ headerInner: {+ display: 'flex',+ alignItems: 'center',+ gap: spacingVars['--spacing-1'],+ },+ // Standalone chevron button with no heavy chrome (transparent, borderless,+ // zero padding) so the icon sits flush with the start of the table+ // (Ernest review #1) while staying keyboard-operable.+ chevron: {+ display: 'inline-flex',+ alignItems: 'center',+ justifyContent: 'center',+ flexShrink: '0',+ padding: 0,+ margin: 0,+ background: 'transparent',+ border: 'none',+ cursor: 'pointer',+ color: {+ default: colorVars['--color-icon-secondary'],+ ':hover': colorVars['--color-icon-primary'],+ },+ },+ chevronIcon: {+ display: 'inline-flex',+ transitionProperty: 'transform',+ transitionDuration: '150ms',+ },+ chevronExpanded: {+ transform: 'rotate(90deg)',+ },+ // Emphasized body text — same size as body, heavier weight (Ernest #3).+ label: {+ fontWeight: fontWeightVars['--font-weight-semibold'],+ color: colorVars['--color-text-primary'],+ },+ count: {+ fontWeight: fontWeightVars['--font-weight-normal'],+ color: colorVars['--color-text-secondary'],+ },+});++/**+ * 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 {@link useTableRowExpansionState}: the consumer owns the+ * `collapsedGroups` set and this hook returns `{data, plugin, idKey}` —+ * pass all three to `<Table>`.+ *+ * @example+ * ```tsx+ * const [collapsed, setCollapsed] = useState<Set<string>>(new Set());+ * const grouped = useTableGroupedRows({+ * data: rows,+ * groupBy: r => r.team,+ * collapsedGroups: collapsed,+ * onToggleGroup: key =>+ * setCollapsed(prev => {+ * const next = new Set(prev);+ * next.has(key) ? next.delete(key) : next.add(key);+ * return next;+ * }),+ * getRowKey: r => r.id,+ * });+ * <Table+ * data={grouped.data}+ * columns={columns}+ * idKey={grouped.idKey}+ * plugins={{grouped: grouped.plugin}}+ * />;+ * ```+ */+export function useTableGroupedRows<T extends Record<string, unknown>>(+ config: UseTableGroupedRowsConfig<T>,+): UseTableGroupedRowsResult<T> {+ const {+ data,+ groupBy,+ collapsedGroups,+ onToggleGroup,+ renderGroupHeader,+ getRowKey: getRowKeyProp,+ groupOrder,+ } = config;++ const flattened = useMemo((): T[] => {+ if (data.length === 0) {+ return [];+ }++ // Group preserving first-seen order.+ const groups = new Map<string, T[]>();+ for (const item of data) {+ const key = groupBy(item);+ const bucket = groups.get(key);+ if (bucket) {+ bucket.push(item);+ } else {+ groups.set(key, [item]);+ }+ }++ // Determine iteration order.+ let keys = [...groups.keys()];+ if (groupOrder && groupOrder.length > 0) {+ const ordered = groupOrder.filter(k => groups.has(k));+ const rest = keys.filter(k => !groupOrder.includes(k));+ keys = [...ordered, ...rest];+ }++ const out: T[] = [];+ for (const key of keys) {+ const rows = groups.get(key) ?? [];+ out.push(makeHeader<T>(key, rows.length));+ if (!collapsedGroups.has(key)) {+ out.push(...rows);+ }+ }+ return out;+ }, [data, groupBy, collapsedGroups, groupOrder]);++ // Positional fallback index, built once per flattened array so key lookup+ // stays O(1) instead of O(n) per row (which would make table keying O(n²)).+ const positionByItem = useMemo(() => {+ if (getRowKeyProp) {+ return null;+ }+ const map = new Map<T, number>();+ for (let i = 0; i < flattened.length; i++) {+ map.set(flattened[i], i);+ }+ return map;+ }, [flattened, getRowKeyProp]);++ const idKey = useCallback(+ (item: T): string => {+ if (isGroupHeader(item)) {+ return `__group_${item.groupKey}`;+ }+ if (getRowKeyProp) {+ return getRowKeyProp(item);+ }+ return String(positionByItem?.get(item) ?? -1);+ },+ [getRowKeyProp, positionByItem],+ );++ const plugin = useMemo(+ (): TablePlugin<T> => ({+ // Replace a header row's pre-rendered cells with one full-width cell.+ transformBodyRow(props, item) {+ if (!isGroupHeader(item)) {+ return props;+ }+ const header = item as unknown as GroupHeader;+ const collapsed = collapsedGroups.has(header.groupKey);+ const toggle = () => onToggleGroup(header.groupKey);+ const content: ReactNode = renderGroupHeader ? (+ renderGroupHeader(header.groupKey, header.count, collapsed)+ ) : (+ <span {...stylex.props(styles.label)}>+ {header.groupKey}{' '}+ <span {...stylex.props(styles.count)}>({header.count})</span>+ </span>+ );+ return {+ ...props,+ htmlProps: {+ ...props.htmlProps,+ // Convenience: clicking anywhere on the row toggles it. The chevron+ // button below is the accessible, keyboard-operable control, so the+ // row keeps its implicit `row` role (no role override here).+ onClick: toggle,+ 'aria-expanded': !collapsed,+ },+ styles: [...props.styles, styles.headerRow],+ children: (+ // colSpan larger than the column count is clamped by the browser+ // to the actual number of columns, so the header always spans the+ // full width without the plugin knowing the column count.+ <td colSpan={999} {...stylex.props(styles.headerCell)}>+ <span {...stylex.props(styles.headerInner)}>+ {/* Standalone chevron button, flush with the table's start+ edge (no heavy button chrome) — the keyboard control. */}+ <button+ type="button"+ {...stylex.props(styles.chevron)}+ onClick={e => {+ e.stopPropagation();+ toggle();+ }}+ aria-label={+ collapsed+ ? `Expand group ${header.groupKey}`+ : `Collapse group ${header.groupKey}`+ }+ aria-expanded={!collapsed}>+ <span+ {...stylex.props(+ styles.chevronIcon,+ !collapsed && styles.chevronExpanded,+ )}>+ <Icon icon="chevronRight" size="xsm" />+ </span>+ </button>+ {content}+ </span>+ </td>+ ),+ };+ },+ }),+ [collapsedGroups, onToggleGroup, renderGroupHeader],+ );++ return {plugin, data: flattened, idKey};+}diff --git a/packages/core/src/Table/useTableGroupedRows.doc.mjs b/packages/core/src/Table/useTableGroupedRows.doc.mjsnew file mode 100644index 0000000000..bd91b04d91--- /dev/null+++ b/packages/core/src/Table/useTableGroupedRows.doc.mjs@@ -0,0 +1,71 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('../docs-types').ComponentDoc} */++export const docs = {+ name: 'useTableGroupedRows',+ 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\u2019s data rows while keeping the header visible. Mirrors useTableRowExpansionState: the consumer owns the collapsedGroups set and the hook returns {data, plugin, idKey} \u2014 pass all three to Table (data, plugins, and idKey respectively).',+ props: [+ {+ name: 'data',+ type: 'T[]',+ description: 'The flat data to group.',+ required: true,+ },+ {+ name: 'groupBy',+ type: '(item: T) => string',+ description:+ 'Derive the group key for a row. Rows with the same key share a section.',+ required: true,+ },+ {+ name: 'collapsedGroups',+ type: 'Set<string>',+ description: 'Set of currently-collapsed group keys.',+ required: true,+ },+ {+ name: 'onToggleGroup',+ type: '(groupKey: string) => void',+ description: 'Called with a group key when its header is toggled.',+ required: true,+ },+ {+ name: 'renderGroupHeader',+ type: '(groupKey: string, count: number, collapsed: boolean) => ReactNode',+ description:+ "Custom renderer for a group header's content (right of the chevron). Defaults to `<groupKey> (<count>)`.",+ },+ {+ name: 'getRowKey',+ type: '(item: T) => string',+ description:+ 'Stable key for a real row. Falls back to a positional key when omitted.',+ },+ {+ name: 'groupOrder',+ type: 'string[]',+ description:+ 'Explicit group ordering; groups not listed keep first-seen order after these.',+ },+ ],+};++/** @type {import('../docs-types').TranslationDoc} */+export const docsDense = {+ description:+ 'Groups a flat data array into collapsible section rows. Each groupBy value becomes a full-width header (chevron + label + count); collapsing hides its rows. Returns {data, plugin, idKey} \u2014 pass to Table data / plugins / idKey. Consumer owns the collapsedGroups set.',+ propDescriptions: {+ data: 'The flat data to group.',+ groupBy: 'Derive a row\u2019s group key. Same key = same section.',+ collapsedGroups: 'Set of currently-collapsed group keys.',+ onToggleGroup: 'Called with the group key when a header is toggled.',+ renderGroupHeader: "Custom header content (right of chevron). Default '<key> (<count>)'.",+ getRowKey: 'Stable key for a real row; positional fallback when omitted.',+ groupOrder: 'Pin these group keys first; others keep first-seen order.',+ },+};