An open source design system that's fully customizable and agent ready
TypeScript
Table: component-based styling + selection plugin (#123)
Cindy Zhangc5e8d9bf3d4f
diff --git a/apps/storybook/stories/TableSelection.stories.tsx b/apps/storybook/stories/TableSelection.stories.tsxnew file mode 100644index 0000000000..735857ca8b--- /dev/null+++ b/apps/storybook/stories/TableSelection.stories.tsx@@ -0,0 +1,388 @@+import {useState, useMemo} from 'react';+import type {Meta, StoryObj} from '@storybook/react';+import {XDSTable, useXDSTableSelection} from '@xds/core/Table';+import type {XDSTableColumn} from '@xds/core/Table';++// =============================================================================+// Sample Data+// =============================================================================++interface User extends Record<string, unknown> {+ id: string;+ name: string;+ email: string;+ role: string;+ isLocked: boolean;+}++const users: User[] = [+ {+ id: '1',+ name: 'Alice',+ email: '[email protected]',+ role: 'Engineer',+ isLocked: false,+ },+ {+ id: '2',+ name: 'Bob',+ email: '[email protected]',+ role: 'Designer',+ isLocked: false,+ },+ {+ id: '3',+ name: 'Charlie',+ email: '[email protected]',+ role: 'Manager',+ isLocked: false,+ },+ {+ id: '4',+ name: 'Diana',+ email: '[email protected]',+ role: 'Engineer',+ isLocked: true,+ },+ {+ id: '5',+ name: 'Eve',+ email: '[email protected]',+ role: 'Admin',+ isLocked: false,+ },+];++const columns: XDSTableColumn<User>[] = [+ {key: 'name', header: 'Name'},+ {key: 'email', header: 'Email'},+ {key: 'role', header: 'Role'},+];++// =============================================================================+// Stories+// =============================================================================++const meta: Meta = {+ title: 'Core/XDSTable/Selection',+ tags: ['autodocs'],+};++export default meta;+type Story = StoryObj;++export const Default: Story = {+ render: () => {+ const [selectedKeys, setSelectedKeys] = useState<Set<string>>(new Set());++ const selectionPlugin = useXDSTableSelection<User>({+ getIsItemSelected: item => selectedKeys.has(item.id),+ onSelectItem: ({item, isSelected}) => {+ const next = new Set(selectedKeys);+ if (isSelected) {+ next.add(item.id);+ } else {+ next.delete(item.id);+ }+ setSelectedKeys(next);+ },+ onSelectAll: ({isAllSelected}) => {+ setSelectedKeys(+ isAllSelected ? new Set(users.map(u => u.id)) : new Set(),+ );+ },+ getIsAllSelected: () =>+ users.length > 0 && users.every(u => selectedKeys.has(u.id)),+ getIsIndeterminate: () => {+ const count = users.filter(u => selectedKeys.has(u.id)).length;+ return count > 0 && count < users.length;+ },+ });++ return (+ <div style={{maxWidth: 600}}>+ <p style={{marginBottom: 8, fontSize: 14, color: '#666'}}>+ Selected: {selectedKeys.size} of {users.length}+ </p>+ <XDSTable+ data={users}+ columns={columns}+ idKey="id"+ plugins={{selection: selectionPlugin}}+ />+ </div>+ );+ },+};++export const WithPreselection: Story = {+ render: () => {+ const [selectedKeys, setSelectedKeys] = useState<Set<string>>(+ new Set(['1', '3']),+ );++ const selectionPlugin = useXDSTableSelection<User>({+ getIsItemSelected: item => selectedKeys.has(item.id),+ onSelectItem: ({item, isSelected}) => {+ const next = new Set(selectedKeys);+ if (isSelected) {+ next.add(item.id);+ } else {+ next.delete(item.id);+ }+ setSelectedKeys(next);+ },+ onSelectAll: ({isAllSelected}) => {+ setSelectedKeys(+ isAllSelected ? new Set(users.map(u => u.id)) : new Set(),+ );+ },+ getIsAllSelected: () =>+ users.length > 0 && users.every(u => selectedKeys.has(u.id)),+ getIsIndeterminate: () => {+ const count = users.filter(u => selectedKeys.has(u.id)).length;+ return count > 0 && count < users.length;+ },+ });++ return (+ <div style={{maxWidth: 600}}>+ <p style={{marginBottom: 8, fontSize: 14, color: '#666'}}>+ Selected: {[...selectedKeys].join(', ') || 'none'}+ </p>+ <XDSTable+ data={users}+ columns={columns}+ idKey="id"+ plugins={{selection: selectionPlugin}}+ />+ </div>+ );+ },+};++export const NonSelectableRows: Story = {+ render: () => {+ const [selectedKeys, setSelectedKeys] = useState<Set<string>>(new Set());++ const selectableUsers = useMemo(+ () => users.filter(u => u.role !== 'Admin'),+ [],+ );++ const selectionPlugin = useXDSTableSelection<User>({+ getIsItemSelected: item => selectedKeys.has(item.id),+ onSelectItem: ({item, isSelected}) => {+ const next = new Set(selectedKeys);+ if (isSelected) {+ next.add(item.id);+ } else {+ next.delete(item.id);+ }+ setSelectedKeys(next);+ },+ onSelectAll: ({isAllSelected}) => {+ setSelectedKeys(+ isAllSelected ? new Set(selectableUsers.map(u => u.id)) : new Set(),+ );+ },+ getIsAllSelected: () =>+ selectableUsers.length > 0 &&+ selectableUsers.every(u => selectedKeys.has(u.id)),+ getIsIndeterminate: () => {+ const count = selectableUsers.filter(u =>+ selectedKeys.has(u.id),+ ).length;+ return count > 0 && count < selectableUsers.length;+ },+ getIsItemSelectable: item => item.role !== 'Admin',+ });++ return (+ <div style={{maxWidth: 600}}>+ <p style={{marginBottom: 8, fontSize: 14, color: '#666'}}>+ Admin rows have no checkbox. Selected: {selectedKeys.size}+ </p>+ <XDSTable+ data={users}+ columns={columns}+ idKey="id"+ plugins={{selection: selectionPlugin}}+ />+ </div>+ );+ },+};++export const DisabledRows: Story = {+ render: () => {+ const [selectedKeys, setSelectedKeys] = useState<Set<string>>(new Set());++ const selectionPlugin = useXDSTableSelection<User>({+ getIsItemSelected: item => selectedKeys.has(item.id),+ onSelectItem: ({item, isSelected}) => {+ const next = new Set(selectedKeys);+ if (isSelected) {+ next.add(item.id);+ } else {+ next.delete(item.id);+ }+ setSelectedKeys(next);+ },+ onSelectAll: ({isAllSelected}) => {+ setSelectedKeys(+ isAllSelected ? new Set(users.map(u => u.id)) : new Set(),+ );+ },+ getIsAllSelected: () =>+ users.length > 0 && users.every(u => selectedKeys.has(u.id)),+ getIsIndeterminate: () => {+ const count = users.filter(u => selectedKeys.has(u.id)).length;+ return count > 0 && count < users.length;+ },+ getIsItemEnabled: item => !item.isLocked,+ });++ return (+ <div style={{maxWidth: 600}}>+ <p style={{marginBottom: 8, fontSize: 14, color: '#666'}}>+ Locked rows (Diana) have a disabled checkbox. Selected:{' '}+ {selectedKeys.size}+ </p>+ <XDSTable+ data={users}+ columns={columns}+ idKey="id"+ plugins={{selection: selectionPlugin}}+ />+ </div>+ );+ },+};++export const Compact: Story = {+ render: () => {+ const [selectedKeys, setSelectedKeys] = useState<Set<string>>(new Set());++ const selectionPlugin = useXDSTableSelection<User>({+ getIsItemSelected: item => selectedKeys.has(item.id),+ onSelectItem: ({item, isSelected}) => {+ const next = new Set(selectedKeys);+ if (isSelected) {+ next.add(item.id);+ } else {+ next.delete(item.id);+ }+ setSelectedKeys(next);+ },+ onSelectAll: ({isAllSelected}) => {+ setSelectedKeys(+ isAllSelected ? new Set(users.map(u => u.id)) : new Set(),+ );+ },+ getIsAllSelected: () =>+ users.length > 0 && users.every(u => selectedKeys.has(u.id)),+ getIsIndeterminate: () => {+ const count = users.filter(u => selectedKeys.has(u.id)).length;+ return count > 0 && count < users.length;+ },+ });++ return (+ <div style={{maxWidth: 600}}>+ <XDSTable+ data={users}+ columns={columns}+ idKey="id"+ density="compact"+ plugins={{selection: selectionPlugin}}+ />+ </div>+ );+ },+};++export const Spacious: Story = {+ render: () => {+ const [selectedKeys, setSelectedKeys] = useState<Set<string>>(new Set());++ const selectionPlugin = useXDSTableSelection<User>({+ getIsItemSelected: item => selectedKeys.has(item.id),+ onSelectItem: ({item, isSelected}) => {+ const next = new Set(selectedKeys);+ if (isSelected) {+ next.add(item.id);+ } else {+ next.delete(item.id);+ }+ setSelectedKeys(next);+ },+ onSelectAll: ({isAllSelected}) => {+ setSelectedKeys(+ isAllSelected ? new Set(users.map(u => u.id)) : new Set(),+ );+ },+ getIsAllSelected: () =>+ users.length > 0 && users.every(u => selectedKeys.has(u.id)),+ getIsIndeterminate: () => {+ const count = users.filter(u => selectedKeys.has(u.id)).length;+ return count > 0 && count < users.length;+ },+ });++ return (+ <div style={{maxWidth: 600}}>+ <XDSTable+ data={users}+ columns={columns}+ idKey="id"+ density="spacious"+ hasHover+ plugins={{selection: selectionPlugin}}+ />+ </div>+ );+ },+};++export const WithStripedRows: Story = {+ render: () => {+ const [selectedKeys, setSelectedKeys] = useState<Set<string>>(new Set());++ const selectionPlugin = useXDSTableSelection<User>({+ getIsItemSelected: item => selectedKeys.has(item.id),+ onSelectItem: ({item, isSelected}) => {+ const next = new Set(selectedKeys);+ if (isSelected) {+ next.add(item.id);+ } else {+ next.delete(item.id);+ }+ setSelectedKeys(next);+ },+ onSelectAll: ({isAllSelected}) => {+ setSelectedKeys(+ isAllSelected ? new Set(users.map(u => u.id)) : new Set(),+ );+ },+ getIsAllSelected: () =>+ users.length > 0 && users.every(u => selectedKeys.has(u.id)),+ getIsIndeterminate: () => {+ const count = users.filter(u => selectedKeys.has(u.id)).length;+ return count > 0 && count < users.length;+ },+ });++ return (+ <div style={{maxWidth: 600}}>+ <XDSTable+ data={users}+ columns={columns}+ idKey="id"+ isStriped+ plugins={{selection: selectionPlugin}}+ />+ </div>+ );+ },+};diff --git a/packages/core/src/CheckboxInput/XDSCheckboxInput.tsx b/packages/core/src/CheckboxInput/XDSCheckboxInput.tsxindex 6e04331145..b43cd96fb9 100644--- a/packages/core/src/CheckboxInput/XDSCheckboxInput.tsx+++ b/packages/core/src/CheckboxInput/XDSCheckboxInput.tsx@@ -32,6 +32,9 @@ const styles = stylex.create({alignItems: 'flex-start',gap: spacingVars['--spacing-2'],},+ containerLabelHidden: {+ gap: 0,+ },checkboxWrapper: {position: 'relative',display: 'flex',@@ -295,6 +298,7 @@ export const XDSCheckboxInput = forwardRef<<div{...stylex.props(styles.container,+ isLabelHidden && styles.containerLabelHidden,!isDisabled && stylex.defaultMarker(),)}><divdiff --git a/packages/core/src/Table/README.md b/packages/core/src/Table/README.mdindex af897b9aa4..39b2b8ef02 100644--- a/packages/core/src/Table/README.md+++ b/packages/core/src/Table/README.md@@ -6,13 +6,20 @@ Table components for the XDS design system.## Components-| File | Export | Purpose |-| -------------------- | ----------------- | -------------------------------------------------------------- |-| `XDSTable.tsx` | `XDSTable` | Styled, data-driven table with density, dividers, and hasHover |-| `XDSBaseTable.tsx` | `XDSBaseTable` | Unstyled table with colgroup, plugin pipeline, children mode |-| `XDSTableRow.tsx` | `XDSTableRow` | Thin `<tr>` wrapper for XDSTable children/streaming mode |-| `XDSTableCell.tsx` | `XDSTableCell` | Thin `<td>` wrapper for XDSTable children/streaming mode |-| `XDSTableContext.ts` | `XDSTableContext` | Context for passing styling props to row/cell components |+| File | Export | Purpose |+| ------------------------ | -------------------- | ------------------------------------------------------------ |+| `XDSTable.tsx` | `XDSTable` | Styled, data-driven table with density, dividers, and hover |+| `XDSBaseTable.tsx` | `XDSBaseTable` | Unstyled table with colgroup, plugin pipeline, children mode |+| `XDSTableRow.tsx` | `XDSTableRow` | `<tr>` wrapper with context-aware styling + `xstyle` |+| `XDSTableCell.tsx` | `XDSTableCell` | `<td>` wrapper with context-aware styling + `xstyle` |+| `XDSTableHeaderCell.tsx` | `XDSTableHeaderCell` | `<th>` wrapper with context-aware header styling + `xstyle` |+| `XDSTableContext.ts` | `XDSTableContext` | Context for passing styling props to row/cell components |++## Hooks++| File | Export | Purpose |+| -------------------------- | ---------------------- | ---------------------------------------------------- |+| `useXDSTableSelection.tsx` | `useXDSTableSelection` | Selection plugin hook — checkboxes, select-all, aria |## Utilities@@ -25,12 +32,16 @@ Table components for the XDS design system.## Types-| File | Export | Purpose |-| ---------- | ------------------- | ------------------------------------------------ |-| `types.ts` | `XDSTableColumn` | Column definition (key, header, width, renderer) |-| `types.ts` | `ColumnWidth` | Proportional or pixel width union |-| `types.ts` | `TablePlugin` | Plugin interface for transform-props pipeline |-| `types.ts` | `XDSBaseTableProps` | Props for the unstyled base table |+| File | Export | Purpose |+| -------------------------- | ------------------------------- | ------------------------------------------------ |+| `types.ts` | `XDSTableColumn` | Column definition (key, header, width, renderer) |+| `types.ts` | `ColumnWidth` | Proportional or pixel width union |+| `types.ts` | `TablePlugin` | Plugin interface for transform-props pipeline |+| `types.ts` | `XDSBaseTableProps` | Props for the unstyled base table |+| `types.ts` | `TableRowComponentProps` | Props interface for Row components |+| `types.ts` | `TableCellComponentProps` | Props interface for Cell components |+| `types.ts` | `TableHeaderCellComponentProps` | Props interface for HeaderCell components |+| `useXDSTableSelection.tsx` | `UseXDSTableSelectionConfig` | Config type for the selection hook |## Usage Patterns@@ -80,13 +91,74 @@ const highlightPlugin: TablePlugin<User> = {},};-<XDSTable data={users} plugins={[highlightPlugin]} />;+<XDSTable data={users} plugins={{highlight: highlightPlugin}} />;+```++### Selection++```tsx+const [selectedKeys, setSelectedKeys] = useState<Set<string>>(new Set());++const selectionPlugin = useXDSTableSelection<User>({+ getIsItemSelected: item => selectedKeys.has(item.id),+ onSelectItem: ({item, isSelected}) => {+ const next = new Set(selectedKeys);+ isSelected ? next.add(item.id) : next.delete(item.id);+ setSelectedKeys(next);+ },+ onSelectAll: ({isAllSelected}) => {+ setSelectedKeys(isAllSelected ? new Set(users.map(u => u.id)) : new Set());+ },+ getIsAllSelected: () => users.every(u => selectedKeys.has(u.id)),+ getIsIndeterminate: () => {+ const count = users.filter(u => selectedKeys.has(u.id)).length;+ return count > 0 && count < users.length;+ },+ // Optional: hide checkbox for non-selectable rows+ getIsItemSelectable: item => item.role !== 'admin',+ // Optional: disable checkbox for locked rows+ getIsItemEnabled: item => !item.isLocked,+});++<XDSTable+ data={users}+ columns={columns}+ plugins={{selection: selectionPlugin}}+/>;```## Architecture-Two-layer design: **XDSBaseTable** provides unstyled structure and the plugin pipeline. **XDSTable** wraps it and injects a styling plugin built from appearance props (`density`, `dividers`, `isStriped`, `hasHover`). This validates the plugin API by dogfooding it.+Two-layer design: **XDSBaseTable** provides unstyled structure, the plugin pipeline, and a `components` prop for rendering custom elements. **XDSTable** wraps it, providing `XDSTableContext` with appearance configuration and passing styled components (`XDSTableRow`, `XDSTableCell`, `XDSTableHeaderCell`) that read context to apply density, dividers, isStriped, and hasHover styles.++### Component-Based Styling++Styling is owned by components rather than a styling plugin:++- **XDSTableRow** — reads `XDSTableContext` for striped/hover/divider styles+- **XDSTableCell** — reads `XDSTableContext` for density/divider styles+- **XDSTableHeaderCell** — reads `XDSTableContext` for density/header/divider styles++Each component accepts `xstyle` for additional styles from plugin transforms (e.g., selected row background from the selection plugin).++### Plugin System++Plugins transform render props at each structural level (`transformTable`, `transformHeaderRow`, `transformBodyRow`, etc.). XDSTable accepts plugins as a named record (`Record<string, TablePlugin<T>>`), while XDSBaseTable accepts an ordered array. XDSTable converts the record to an array internally.++Plugins can also provide:++- `transformTableContext` — wrap the table output in context providers (used by selection to provide `SelectionContext`)+- Row transforms receive pre-rendered `children` (cells), allowing plugins to prepend/append elements++### Selection Architecture++The selection plugin uses React Context so that `SelectAllCheckbox` and `SelectionRowCheckbox` re-render independently from row content. The hook returns a stable plugin object via ref — only the context value updates when selection state changes. Selection cells render `XDSTableCell` and `XDSTableHeaderCell` directly, inheriting styling from `XDSTableContext`.++### Performance++Body rows are memoized via `React.memo` with a custom comparison function. When a single data item changes, only that row re-renders — unchanged rows are skipped. For this to work optimally, consumers should define `columns` outside the component or memoize them.## Related Files-- `/packages/core/src/theme/tokens.stylex.ts` — Design tokens used by XDSTable styling+- `/packages/core/src/theme/tokens.stylex.ts` — Design tokens used by table component styling+- `/packages/core/src/CheckboxInput/` — Checkbox component used by selection plugindiff --git a/packages/core/src/Table/XDSBaseTable.tsx b/packages/core/src/Table/XDSBaseTable.tsxindex b31ba8d40b..fcd3ff3929 100644--- a/packages/core/src/Table/XDSBaseTable.tsx+++ b/packages/core/src/Table/XDSBaseTable.tsx@@ -10,7 +10,13 @@* - /packages/core/src/Table/index.ts (exports if types change)*/-import {forwardRef, memo, type ReactElement, type Ref} from 'react';+import {+ forwardRef,+ memo,+ type ReactElement,+ type ReactNode,+ type Ref,+} from 'react';import * as stylex from '@stylexjs/stylex';import type {XDSBaseTableProps,@@ -21,14 +27,13 @@ import type {HeaderCellRenderProps,BodyRowRenderProps,BodyCellRenderProps,+ TableRowComponentProps,+ TableCellComponentProps,} from './types';-import {- generateColumns,- defaultCellRenderer,- columnWidthToCSS,-} from './columnUtils';+import {generateColumns, defaultCellRenderer} from './columnUtils';import {XDSTableRow} from './XDSTableRow';import {XDSTableCell} from './XDSTableCell';+import {XDSTableHeaderCell} from './XDSTableHeaderCell';const styles = stylex.create({table: {@@ -56,18 +61,6 @@ function applyPlugins<TPlugin, TProps, TArgs extends unknown[]>(}, initial);}-/**- * Compute total proportional units for percentage calculation.- */-function getTotalProportional<T extends Record<string, unknown>>(- columns: XDSTableColumn<T>[],-): number {- return columns.reduce((sum, col) => {- const w = col.width ?? {type: 'proportional' as const, value: 1};- return w.type === 'proportional' ? sum + w.value : sum;- }, 0);-}-// =============================================================================// Memoized Table Row Component// =============================================================================@@ -81,12 +74,14 @@ interface TableRowProps<T extends Record<string, unknown>> {rowKey: string | number;columns: XDSTableColumn<T>[];plugins: TablePlugin<T>[];+ RowComponent: React.ComponentType<TableRowComponentProps>;+ CellComponent: React.ComponentType<TableCellComponentProps>;}/*** Memoized table row component.* Only re-renders when the specific row's data changes.- * Uses XDSTableRow/Cell for context-based styling, with plugin support.+ * Uses component props for context-based styling, with plugin support.*/function TableRowInner<T extends Record<string, unknown>>({item,@@ -94,45 +89,49 @@ function TableRowInner<T extends Record<string, unknown>>({rowKey,columns,plugins,+ RowComponent,+ CellComponent,}: TableRowProps<T>): ReactElement {- // Apply plugin transforms for row+ // Build cells first+ const cells = columns.map(col => {+ const cellRenderProps = applyPlugins(+ plugins,+ p => p.transformBodyCell,+ {htmlProps: {}, styles: []} as BodyCellRenderProps,+ col,+ item,+ );++ const content = col.renderCell+ ? col.renderCell(item)+ : defaultCellRenderer(item, col.key);++ return (+ <CellComponent+ key={col.key}+ {...cellRenderProps.htmlProps}+ xstyle={cellRenderProps.styles}>+ {content}+ </CellComponent>+ );+ });++ // Apply plugin transforms for row (with pre-rendered children)const rowRenderProps = applyPlugins(plugins,p => p.transformBodyRow,- {htmlProps: {}, styles: []} as BodyRowRenderProps,+ {htmlProps: {}, styles: [], children: <>{cells}</>} as BodyRowRenderProps,item,rowIndex,);return (- <XDSTableRow+ <RowComponentkey={rowKey}{...rowRenderProps.htmlProps}- {...stylex.props(...rowRenderProps.styles)}>- {columns.map(col => {- // Apply plugin transforms for cell- const cellRenderProps = applyPlugins(- plugins,- p => p.transformBodyCell,- {htmlProps: {}, styles: []} as BodyCellRenderProps,- col,- item,- );-- const content = col.renderCell- ? col.renderCell(item)- : defaultCellRenderer(item, col.key);-- return (- <XDSTableCell- key={col.key}- {...cellRenderProps.htmlProps}- {...stylex.props(...cellRenderProps.styles)}>- {content}- </XDSTableCell>- );- })}- </XDSTableRow>+ xstyle={rowRenderProps.styles}>+ {rowRenderProps.children}+ </RowComponent>);}@@ -148,9 +147,11 @@ function areRowPropsEqual<T extends Record<string, unknown>>(// We don't compare rowIndex as it's handled by CSSif (prevProps.rowKey !== nextProps.rowKey) return false;- // If columns or plugins change, need to re-render all rows+ // If columns, plugins, or components change, need to re-render all rowsif (prevProps.columns !== nextProps.columns) return false;if (prevProps.plugins !== nextProps.plugins) return false;+ if (prevProps.RowComponent !== nextProps.RowComponent) return false;+ if (prevProps.CellComponent !== nextProps.CellComponent) return false;// Shallow compare the item - if same reference, skip re-renderif (prevProps.item === nextProps.item) return true;@@ -187,6 +188,7 @@ function XDSBaseTableInner<T extends Record<string, unknown>>(columns: columnsProp,idKey,plugins: pluginsProp,+ components,children,tableProps: userTableProps,}: XDSBaseTableProps<T>,@@ -195,73 +197,67 @@ function XDSBaseTableInner<T extends Record<string, unknown>>(// Use stable empty array when no plugins providedconst plugins = pluginsProp ?? (EMPTY_PLUGINS as TablePlugin<T>[]);+ const RowComponent = components?.Row ?? XDSTableRow;+ const CellComponent = components?.Cell ?? XDSTableCell;+ const HeaderCellComponent = components?.HeaderCell ?? XDSTableHeaderCell;+// Resolve columns: explicit > auto-generated from dataconst resolvedColumns: XDSTableColumn<T>[] =columnsProp ?? (data ? generateColumns(data) : []);- const totalProportional = getTotalProportional(resolvedColumns);-// --- Plugin pipeline: table ---const tableRenderProps = applyPlugins(plugins, p => p.transformTable, {htmlProps: {...userTableProps},styles: [styles.table],} as TableRenderProps);+ // --- Plugin pipeline: header cells ---+ const headerCells = resolvedColumns.map(col => {+ const cellRenderProps = applyPlugins(+ plugins,+ p => p.transformHeaderCell,+ {htmlProps: {}, styles: []} as HeaderCellRenderProps,+ col,+ );++ return (+ <HeaderCellComponent+ key={col.key}+ {...cellRenderProps.htmlProps}+ xstyle={cellRenderProps.styles}>+ {col.header ?? col.key}+ </HeaderCellComponent>+ );+ });+// --- Plugin pipeline: header row ---const headerRowRenderProps = applyPlugins(plugins,p => p.transformHeaderRow,- {htmlProps: {}, styles: []} as HeaderRowRenderProps,+ {+ htmlProps: {},+ styles: [],+ children: <>{headerCells}</>,+ } as HeaderRowRenderProps,);// --- Render ---const hasData = data != null && data.length > 0;const hasColumns = resolvedColumns.length > 0;- return (+ let tableElement: ReactNode = (<tableref={ref}{...tableRenderProps.htmlProps}{...stylex.props(...tableRenderProps.styles)}>- {/* colgroup for column widths */}- {hasColumns && (- <colgroup>- {resolvedColumns.map(col => {- const w = col.width ?? {type: 'proportional' as const, value: 1};- return (- <col- key={col.key}- style={{width: columnWidthToCSS(w, totalProportional)}}- />- );- })}- </colgroup>- )}-{/* thead */}{hasColumns && (<thead>- <tr+ <RowComponent{...headerRowRenderProps.htmlProps}- {...stylex.props(...headerRowRenderProps.styles)}>- {resolvedColumns.map(col => {- const cellRenderProps = applyPlugins(- plugins,- p => p.transformHeaderCell,- {htmlProps: {}, styles: []} as HeaderCellRenderProps,- col,- );-- return (- <th- key={col.key}- {...cellRenderProps.htmlProps}- {...stylex.props(...cellRenderProps.styles)}>- {col.header ?? col.key}- </th>- );- })}- </tr>+ xstyle={headerRowRenderProps.styles}>+ {headerRowRenderProps.children}+ </RowComponent></thead>)}@@ -286,12 +282,23 @@ function XDSBaseTableInner<T extends Record<string, unknown>>(rowKey={rowKey}columns={resolvedColumns}plugins={plugins}+ RowComponent={RowComponent}+ CellComponent={CellComponent}/>);})}</tbody></table>);++ // Apply transformTableContext from each plugin (outermost-first)+ for (const plugin of plugins) {+ if (plugin.transformTableContext) {+ tableElement = plugin.transformTableContext(tableElement);+ }+ }++ return tableElement as ReactElement;}/**@@ -299,6 +306,7 @@ function XDSBaseTableInner<T extends Record<string, unknown>>(** Supports data-driven rendering (via `data` + `columns`) and children mode.* Applies plugins as a transform pipeline over render props.+ * Accepts a `components` prop to render styled components instead of raw elements.** @example* ```tsxdiff --git a/packages/core/src/Table/XDSTable.test.tsx b/packages/core/src/Table/XDSTable.test.tsxindex 9e97205c2d..1dd7d5a60d 100644--- a/packages/core/src/Table/XDSTable.test.tsx+++ b/packages/core/src/Table/XDSTable.test.tsx@@ -233,7 +233,7 @@ describe('XDSBaseTable', () => {expect(screen.getByText('Manual cell')).toBeInTheDocument();});- it('does not render thead or colgroup in children mode without columns', () => {+ it('does not render thead in children mode without columns', () => {const {container} = render(<XDSBaseTable><tr>@@ -242,7 +242,6 @@ describe('XDSBaseTable', () => {</XDSBaseTable>,);expect(container.querySelector('thead')).toBeNull();- expect(container.querySelector('colgroup')).toBeNull();});it('renders empty table when data is empty array', () => {@@ -252,14 +251,9 @@ describe('XDSBaseTable', () => {expect(screen.getAllByRole('row')).toHaveLength(1);});- it('renders colgroup with correct column widths', () => {+ it('does not render colgroup', () => {const {container} = render(<XDSBaseTable data={users} columns={columns} />);- const cols = container.querySelectorAll('colgroup col');- expect(cols).toHaveLength(3);- // Column 0: proportional(1) — default, total proportional = 1+2 = 3, so 33.33%- // Column 1: pixel(80) — 80px- // Column 2: proportional(2) — 2/3 = 66.67%- expect(cols[1]).toHaveStyle({width: '80px'});+ expect(container.querySelector('colgroup')).toBeNull();});it('forwards ref to the table element', () => {@@ -526,7 +520,13 @@ describe('XDSTable', () => {htmlProps: {...props.htmlProps, 'data-testid': 'custom-plugin'},}),};- render(<XDSTable data={users} columns={columns} plugins={[userPlugin]} />);+ render(+ <XDSTable+ data={users}+ columns={columns}+ plugins={{custom: userPlugin}}+ />,+ );expect(screen.getByTestId('custom-plugin')).toBeInTheDocument();});@@ -541,7 +541,13 @@ describe('XDSTable', () => {};},};- render(<XDSTable data={users} columns={columns} plugins={[userPlugin]} />);+ render(+ <XDSTable+ data={users}+ columns={columns}+ plugins={{custom: userPlugin}}+ />,+ );expect(screen.getByTestId('after-xds')).toBeInTheDocument();});diff --git a/packages/core/src/Table/XDSTable.tsx b/packages/core/src/Table/XDSTable.tsxindex 96c6a24b0f..87f812b01e 100644--- a/packages/core/src/Table/XDSTable.tsx+++ b/packages/core/src/Table/XDSTable.tsx@@ -1,6 +1,6 @@/*** @file XDSTable.tsx- * @input React, StyleX, XDSBaseTable, theme tokens, types+ * @input React, StyleX, XDSBaseTable, theme tokens, types, components* @output Exports XDSTable component, XDSTableProps, XDSTableDensity, XDSTableDividers types* @position Styled wrapper; the primary table API for consumers*@@ -13,20 +13,14 @@import {forwardRef, useMemo, type ReactElement, type Ref} from 'react';import * as stylex from '@stylexjs/stylex';-import {- colorVars,- spacingVars,- textSizeVars,- fontWeightVars,-} from '../theme/tokens.stylex';+import {colorVars} from '../theme/tokens.stylex';import {XDSBaseTable} from './XDSBaseTable';+import {XDSTableRow} from './XDSTableRow';+import {XDSTableCell} from './XDSTableCell';+import {XDSTableHeaderCell} from './XDSTableHeaderCell';import {XDSTableContext} from './XDSTableContext';-import type {- XDSBaseTableProps,- TablePlugin,- TableRenderProps,- HeaderCellRenderProps,-} from './types';+import {useXDSBaseTablePlugins} from './useXDSBaseTablePlugins';+import type {XDSBaseTableProps, TablePlugin, TableRenderProps} from './types';// =============================================================================// XDSTable Types@@ -44,9 +38,10 @@ export type XDSTableDividers = 'rows' | 'columns' | 'grid' | 'none';** @template T - The row data type*/-export interface XDSTableProps<- T extends Record<string, unknown>,-> extends XDSBaseTableProps<T> {+export interface XDSTableProps<T extends Record<string, unknown>> extends Omit<+ XDSBaseTableProps<T>,+ 'plugins' | 'components'+> {/** Row density. @default 'balanced' */density?: XDSTableDensity;/** Divider style. @default 'rows' */@@ -55,10 +50,12 @@ export interface XDSTableProps<isStriped?: boolean;/** Hover highlight on rows. @default false */hasHover?: boolean;+ /** Named plugins to extend table behavior */+ plugins?: Record<string, TablePlugin<T>>;}// =============================================================================-// StyleX Styles+// StyleX Styles (table-level only; cell/row/header styles owned by components)// =============================================================================const tableStyles = stylex.create({@@ -68,63 +65,13 @@ const tableStyles = stylex.create({},});-// Density: padding + font size for header cells-const densityStyles = stylex.create({- compact: {- paddingBlock: spacingVars['--spacing-1'],- paddingInline: spacingVars['--spacing-2'],- fontSize: textSizeVars['--text-xsm'],- },- balanced: {- paddingBlock: spacingVars['--spacing-2'],- paddingInline: spacingVars['--spacing-3'],- fontSize: textSizeVars['--text-sm'],- },- spacious: {- paddingBlock: spacingVars['--spacing-3'],- paddingInline: spacingVars['--spacing-4'],- fontSize: textSizeVars['--text-base'],- },-});--// Header cell styles-const headerStyles = stylex.create({- cell: {- fontWeight: fontWeightVars['--font-weight-semibold'],- color: colorVars['--color-text-secondary'],- textAlign: 'start',- },-});--// Column divider styles for headers-const dividerColumnStyles = stylex.create({- cell: {- borderRightWidth: {- default: '1px',- ':last-child': '0',- },- borderRightStyle: 'solid',- borderRightColor: colorVars['--color-divider'],- },-});--// Header divider (bottom border on header row)-const headerDividerStyles = stylex.create({- cell: {- borderBottomWidth: '1px',- borderBottomStyle: 'solid',- borderBottomColor: colorVars['--color-divider'],- },-});-// =============================================================================-// Build XDS Styling Plugin+// Table-level styling plugin (only transforms the <table> element)// =============================================================================-function buildXDSStylePlugin<T extends Record<string, unknown>>(- density: XDSTableDensity,- dividers: XDSTableDividers,-): TablePlugin<T> {+function buildTableStylePlugin<+ T extends Record<string, unknown>,+>(): TablePlugin<T> {return {transformTable(props: TableRenderProps): TableRenderProps {return {@@ -132,37 +79,20 @@ function buildXDSStylePlugin<T extends Record<string, unknown>>(styles: [...props.styles, tableStyles.base],};},-- transformHeaderCell(- props: HeaderCellRenderProps,- _column,- ): HeaderCellRenderProps {- const cellStyles = [- ...props.styles,- headerStyles.cell,- densityStyles[density],- headerDividerStyles.cell,- ];-- // Column dividers on header cells- if (dividers === 'columns' || dividers === 'grid') {- cellStyles.push(dividerColumnStyles.cell);- }-- return {...props, styles: cellStyles};- },-- // Body row/cell styling handled by XDSTableRow/Cell via context};}+// Stable component references for the components prop+const xdsComponents = {+ Row: XDSTableRow,+ Cell: XDSTableCell,+ HeaderCell: XDSTableHeaderCell,+};+// =============================================================================// XDSTable Component// =============================================================================-// Stable empty array to avoid creating new reference on each render-const EMPTY_PLUGINS: TablePlugin<Record<string, unknown>>[] = [];-function XDSTableInner<T extends Record<string, unknown>>({density = 'balanced',@@ -176,20 +106,12 @@ function XDSTableInner<T extends Record<string, unknown>>(}: XDSTableProps<T>,ref: Ref<HTMLTableElement>,): ReactElement {- // Use stable empty array when no plugins provided- const stableUserPlugins = userPlugins ?? (EMPTY_PLUGINS as TablePlugin<T>[]);+ // Table-level styling plugin (just adds font/color to <table>)+ const tablePlugin = useMemo(() => buildTableStylePlugin<T>(), []);+ const basePlugins = useMemo(() => [tablePlugin], [tablePlugin]);- // Build the internal XDS styling plugin (table + header styling only)- const xdsPlugin = useMemo(- () => buildXDSStylePlugin<T>(density, dividers),- [density, dividers],- );-- // XDS plugin runs first, user plugins can override/extend- const mergedPlugins = useMemo(- () => [xdsPlugin, ...stableUserPlugins],- [xdsPlugin, stableUserPlugins],- );+ // Convert named plugin record to stable memoized array+ const mergedPlugins = useXDSBaseTablePlugins<T>(basePlugins, userPlugins);const contextValue = useMemo(() => ({density, dividers, isStriped, hasHover}),@@ -203,6 +125,7 @@ function XDSTableInner<T extends Record<string, unknown>>(data={data}columns={columns}plugins={mergedPlugins}+ components={xdsComponents}{...rest}/></XDSTableContext.Provider>@@ -212,8 +135,10 @@ function XDSTableInner<T extends Record<string, unknown>>(/*** XDSTable — a styled, data-driven table component.*- * Wraps XDSBaseTable with an XDS styling plugin that applies density,- * dividers, striped rows, and hover effects using design tokens.+ * Wraps XDSBaseTable with styled components (XDSTableRow, XDSTableCell,+ * XDSTableHeaderCell) that read appearance configuration from XDSTableContext.+ * Density, dividers, striped rows, and hover effects are applied via+ * design tokens in the component styles.** @example* ```tsxdiff --git a/packages/core/src/Table/XDSTableCell.tsx b/packages/core/src/Table/XDSTableCell.tsxindex 72474559df..383abc4f6d 100644--- a/packages/core/src/Table/XDSTableCell.tsx+++ b/packages/core/src/Table/XDSTableCell.tsx@@ -26,6 +26,7 @@ export interface XDSTableCellProps extends Omit<'className' | 'style'> {children?: ReactNode;+ xstyle?: StyleXStyles | StyleXStyles[];}const densityStyles = stylex.create({@@ -33,16 +34,19 @@ const densityStyles = stylex.create({paddingBlock: spacingVars['--spacing-1'],paddingInline: spacingVars['--spacing-2'],fontSize: textSizeVars['--text-xsm'],+ boxSizing: 'border-box',},balanced: {paddingBlock: spacingVars['--spacing-2'],paddingInline: spacingVars['--spacing-3'],fontSize: textSizeVars['--text-sm'],+ boxSizing: 'border-box',},spacious: {paddingBlock: spacingVars['--spacing-3'],paddingInline: spacingVars['--spacing-4'],fontSize: textSizeVars['--text-base'],+ boxSizing: 'border-box',},});@@ -80,12 +84,12 @@ const dividerColumnStyles = stylex.create({* ```*/export const XDSTableCell = forwardRef<HTMLTableCellElement, XDSTableCellProps>(- ({children, ...props}, ref) => {+ ({children, xstyle, ...props}, ref) => {const ctx = useContext(XDSTableContext);if (!ctx) {return (- <td ref={ref} {...props}>+ <td ref={ref} {...props} {...stylex.props(xstyle)}>{children}</td>);@@ -101,6 +105,14 @@ export const XDSTableCell = forwardRef<HTMLTableCellElement, XDSTableCellProps>(cellStyles.push(dividerColumnStyles.cell);}+ if (xstyle) {+ if (Array.isArray(xstyle)) {+ cellStyles.push(...xstyle);+ } else {+ cellStyles.push(xstyle);+ }+ }+return (<td ref={ref} {...props} {...stylex.props(...cellStyles)}>{children}diff --git a/packages/core/src/Table/XDSTableHeaderCell.tsx b/packages/core/src/Table/XDSTableHeaderCell.tsxnew file mode 100644index 0000000000..7a40b2ad10--- /dev/null+++ b/packages/core/src/Table/XDSTableHeaderCell.tsx@@ -0,0 +1,140 @@+/**+ * @file XDSTableHeaderCell.tsx+ * @input React, StyleX, XDSTableContext, theme tokens+ * @output Exports XDSTableHeaderCell component, XDSTableHeaderCellProps+ * @position Sub-component; used inside XDSTable for header cells+ *+ * SYNC: When modified, update:+ * - /packages/core/src/Table/README.md+ * - /packages/core/src/Table/index.ts+ */++import {+ forwardRef,+ useContext,+ type ThHTMLAttributes,+ type ReactNode,+} from 'react';+import * as stylex from '@stylexjs/stylex';+import {+ colorVars,+ spacingVars,+ textSizeVars,+ fontWeightVars,+} from '../theme/tokens.stylex';+import type {StyleXStyles} from '../theme/types';+import {XDSTableContext} from './XDSTableContext';++/** Props for XDSTableHeaderCell — `<th>` wrapper with context-aware styling */+export interface XDSTableHeaderCellProps extends ThHTMLAttributes<HTMLTableCellElement> {+ children?: ReactNode;+ xstyle?: StyleXStyles | StyleXStyles[];+}++const densityStyles = stylex.create({+ compact: {+ paddingBlock: spacingVars['--spacing-1'],+ paddingInline: spacingVars['--spacing-2'],+ fontSize: textSizeVars['--text-xsm'],+ boxSizing: 'border-box',+ },+ balanced: {+ paddingBlock: spacingVars['--spacing-2'],+ paddingInline: spacingVars['--spacing-3'],+ fontSize: textSizeVars['--text-sm'],+ boxSizing: 'border-box',+ },+ spacious: {+ paddingBlock: spacingVars['--spacing-3'],+ paddingInline: spacingVars['--spacing-4'],+ fontSize: textSizeVars['--text-base'],+ boxSizing: 'border-box',+ },+});++const headerStyles = stylex.create({+ cell: {+ fontWeight: fontWeightVars['--font-weight-semibold'],+ color: colorVars['--color-text-secondary'],+ textAlign: 'start',+ },+});++const headerDividerStyles = stylex.create({+ cell: {+ borderBottomWidth: '1px',+ borderBottomStyle: 'solid',+ borderBottomColor: colorVars['--color-divider'],+ },+});++const dividerColumnStyles = stylex.create({+ cell: {+ borderRightWidth: {+ default: '1px',+ ':last-child': '0',+ },+ borderRightStyle: 'solid',+ borderRightColor: colorVars['--color-divider'],+ },+});++/**+ * XDSTableHeaderCell — a `<th>` wrapper for header cells.+ *+ * When used inside `<XDSTable>`, inherits styling from the table context+ * (density padding, header font weight/color, divider borders).+ * When used standalone, renders a plain `<th>`.+ *+ * Accepts `xstyle` for plugin-provided styles that merge on top.+ *+ * @example+ * ```tsx+ * <thead>+ * <tr>+ * <XDSTableHeaderCell>Name</XDSTableHeaderCell>+ * <XDSTableHeaderCell>Age</XDSTableHeaderCell>+ * </tr>+ * </thead>+ * ```+ */+export const XDSTableHeaderCell = forwardRef<+ HTMLTableCellElement,+ XDSTableHeaderCellProps+>(({children, xstyle, ...props}, ref) => {+ const ctx = useContext(XDSTableContext);++ if (!ctx) {+ return (+ <th ref={ref} {...props} {...stylex.props(xstyle)}>+ {children}+ </th>+ );+ }++ const cellStyles: StyleXStyles[] = [+ headerStyles.cell,+ densityStyles[ctx.density],+ headerDividerStyles.cell,+ ];++ if (ctx.dividers === 'columns' || ctx.dividers === 'grid') {+ cellStyles.push(dividerColumnStyles.cell);+ }++ if (xstyle) {+ if (Array.isArray(xstyle)) {+ cellStyles.push(...xstyle);+ } else {+ cellStyles.push(xstyle);+ }+ }++ return (+ <th ref={ref} {...props} {...stylex.props(...cellStyles)}>+ {children}+ </th>+ );+});++XDSTableHeaderCell.displayName = 'XDSTableHeaderCell';diff --git a/packages/core/src/Table/XDSTableRow.tsx b/packages/core/src/Table/XDSTableRow.tsxindex 3f6c39bcde..1326128283 100644--- a/packages/core/src/Table/XDSTableRow.tsx+++ b/packages/core/src/Table/XDSTableRow.tsx@@ -26,6 +26,7 @@ export interface XDSTableRowProps extends Omit<'className' | 'style'> {children: ReactNode;+ xstyle?: StyleXStyles[];}const stripedRowStyles = stylex.create({@@ -86,12 +87,12 @@ const lastBodyRowStyles = stylex.create({* ```*/export const XDSTableRow = forwardRef<HTMLTableRowElement, XDSTableRowProps>(- ({children, ...props}, ref) => {+ ({children, xstyle, ...props}, ref) => {const ctx = useContext(XDSTableContext);if (!ctx) {return (- <tr ref={ref} {...props}>+ <tr ref={ref} {...props} {...stylex.props(xstyle)}>{children}</tr>);@@ -109,7 +110,12 @@ export const XDSTableRow = forwardRef<HTMLTableRowElement, XDSTableRowProps>(}if (ctx.dividers === 'rows' || ctx.dividers === 'grid') {- rowStyles.push(lastBodyRowStyles.row);+ // Note: last-body-row border removal is handled by XDSTableCell+ // to avoid affecting the header row in <thead>.+ }++ if (xstyle) {+ rowStyles.push(...xstyle);}return (diff --git a/packages/core/src/Table/index.ts b/packages/core/src/Table/index.tsindex 85f9440930..84a940a2e3 100644--- a/packages/core/src/Table/index.ts+++ b/packages/core/src/Table/index.ts@@ -11,7 +11,10 @@ export {XDSBaseTable} from './XDSBaseTable';export {XDSTable} from './XDSTable';export {XDSTableRow} from './XDSTableRow';export {XDSTableCell} from './XDSTableCell';+export {XDSTableHeaderCell} from './XDSTableHeaderCell';export {XDSTableContext} from './XDSTableContext';+export {useXDSTableSelection} from './plugins/selection';+export {useXDSBaseTablePlugins} from './useXDSBaseTablePlugins';export {proportional,pixel,@@ -30,6 +33,9 @@ export type {BodyRowRenderProps,BodyCellRenderProps,XDSBaseTableProps,+ TableRowComponentProps,+ TableCellComponentProps,+ TableHeaderCellComponentProps,} from './types';export type {XDSTableProps,@@ -38,4 +44,6 @@ export type {} from './XDSTable';export type {XDSTableRowProps} from './XDSTableRow';export type {XDSTableCellProps} from './XDSTableCell';+export type {XDSTableHeaderCellProps} from './XDSTableHeaderCell';export type {XDSTableContextValue} from './XDSTableContext';+export type {UseXDSTableSelectionConfig} from './plugins/selection';diff --git a/packages/core/src/Table/plugins/selection/index.ts b/packages/core/src/Table/plugins/selection/index.tsnew file mode 100644index 0000000000..372771cc43--- /dev/null+++ b/packages/core/src/Table/plugins/selection/index.ts@@ -0,0 +1,2 @@+export {useXDSTableSelection} from './useXDSTableSelection';+export type {UseXDSTableSelectionConfig} from './useXDSTableSelection';diff --git a/packages/core/src/Table/plugins/selection/useXDSTableSelection-perf.test.tsx b/packages/core/src/Table/plugins/selection/useXDSTableSelection-perf.test.tsxnew file mode 100644index 0000000000..829f97ee7b--- /dev/null+++ b/packages/core/src/Table/plugins/selection/useXDSTableSelection-perf.test.tsx@@ -0,0 +1,132 @@+/**+ * @file XDSTable.selection-perf.test.tsx+ * @input XDSTable, useXDSTableSelection, React testing utilities+ * @output Performance tests for selection plugin render behavior+ * @position Test file; validates selection interaction correctness+ *+ * The selection plugin passes aria-selected and styles via transformBodyRow.+ * Row re-renders on selection change are expected — checkbox content+ * re-renders independently via SelectionContext.+ */++import {describe, it, expect} from 'vitest';+import {render, screen, act} from '@testing-library/react';+import {useState} from 'react';+import userEvent from '@testing-library/user-event';+import {XDSTable} from '../../XDSTable';+import {useXDSTableSelection} from './useXDSTableSelection';+import type {XDSTableColumn} from '../../types';++// =============================================================================+// Test Data+// =============================================================================++interface TestRow extends Record<string, unknown> {+ id: string;+ name: string;+}++const createTestData = (count: number): TestRow[] =>+ Array.from({length: count}, (_, i) => ({+ id: `row-${i}`,+ name: `Item ${i}`,+ }));++// =============================================================================+// Helper+// =============================================================================++function SelectionTestTable({data}: {data: TestRow[]}) {+ const [selectedKeys, setSelectedKeys] = useState<Set<string>>(new Set());++ const columns: XDSTableColumn<TestRow>[] = [{key: 'name', header: 'Name'}];++ const selectionPlugin = useXDSTableSelection<TestRow>({+ getIsItemSelected: item => selectedKeys.has(item.id),+ onSelectItem: ({item, isSelected}) => {+ const next = new Set(selectedKeys);+ if (isSelected) {+ next.add(item.id);+ } else {+ next.delete(item.id);+ }+ setSelectedKeys(next);+ },+ onSelectAll: ({isAllSelected}) => {+ setSelectedKeys(isAllSelected ? new Set(data.map(d => d.id)) : new Set());+ },+ getIsAllSelected: () =>+ data.length > 0 && data.every(d => selectedKeys.has(d.id)),+ getIsIndeterminate: () => {+ const count = data.filter(d => selectedKeys.has(d.id)).length;+ return count > 0 && count < data.length;+ },+ });++ return (+ <XDSTable+ data={data}+ columns={columns}+ idKey="id"+ plugins={{selection: selectionPlugin}}+ />+ );+}++// =============================================================================+// Tests+// =============================================================================++describe('Selection plugin render performance', () => {+ it('selecting a row updates aria-selected correctly', async () => {+ const user = userEvent.setup();+ render(<SelectionTestTable data={createTestData(5)} />);++ const rowCheckboxes = screen.getAllByLabelText('Select row');+ await act(async () => {+ await user.click(rowCheckboxes[2]);+ });++ const rows = screen.getAllByRole('row');+ expect(rows[3]).toHaveAttribute('aria-selected', 'true');+ expect(rows[1]).not.toHaveAttribute('aria-selected');+ expect(rows[2]).not.toHaveAttribute('aria-selected');+ });++ it('select-all sets aria-selected on all rows', async () => {+ const user = userEvent.setup();+ render(<SelectionTestTable data={createTestData(5)} />);++ await act(async () => {+ await user.click(screen.getByLabelText('Select all rows'));+ });++ const rows = screen.getAllByRole('row');+ for (let i = 1; i <= 5; i++) {+ expect(rows[i]).toHaveAttribute('aria-selected', 'true');+ }+ });++ it('multiple sequential selections work correctly', async () => {+ const user = userEvent.setup();+ render(<SelectionTestTable data={createTestData(5)} />);++ const rowCheckboxes = screen.getAllByLabelText('Select row');+ await act(async () => {+ await user.click(rowCheckboxes[0]);+ });+ await act(async () => {+ await user.click(rowCheckboxes[1]);+ });+ await act(async () => {+ await user.click(rowCheckboxes[2]);+ });++ const rows = screen.getAllByRole('row');+ expect(rows[1]).toHaveAttribute('aria-selected', 'true');+ expect(rows[2]).toHaveAttribute('aria-selected', 'true');+ expect(rows[3]).toHaveAttribute('aria-selected', 'true');+ expect(rows[4]).not.toHaveAttribute('aria-selected');+ expect(rows[5]).not.toHaveAttribute('aria-selected');+ });+});diff --git a/packages/core/src/Table/plugins/selection/useXDSTableSelection.test.tsx b/packages/core/src/Table/plugins/selection/useXDSTableSelection.test.tsxnew file mode 100644index 0000000000..0aec19b68a--- /dev/null+++ b/packages/core/src/Table/plugins/selection/useXDSTableSelection.test.tsx@@ -0,0 +1,195 @@+/**+ * @file useXDSTableSelection.test.tsx+ * @input useXDSTableSelection, XDSTable, React testing utilities+ * @output Functional tests for the selection plugin+ * @position Test file; validates selection behavior (checkboxes, aria, select-all)+ */++import {describe, it, expect} from 'vitest';+import {useState} from 'react';+import {render, screen, within} from '@testing-library/react';+import userEvent from '@testing-library/user-event';+import {XDSTable} from '../../XDSTable';+import {useXDSTableSelection} from './useXDSTableSelection';+import type {XDSTableColumn} from '../../types';++// =============================================================================+// Test Data+// =============================================================================++interface SelectableUser extends Record<string, unknown> {+ id: string;+ name: string;+ role: string;+ isLocked: boolean;+}++const selectableUsers: SelectableUser[] = [+ {id: '1', name: 'Alice', role: 'engineer', isLocked: false},+ {id: '2', name: 'Bob', role: 'admin', isLocked: false},+ {id: '3', name: 'Charlie', role: 'designer', isLocked: true},+];++const selectableColumns: XDSTableColumn<SelectableUser>[] = [+ {key: 'name', header: 'Name'},+ {key: 'role', header: 'Role'},+];++function SelectionTable({+ getIsItemSelectable,+ getIsItemEnabled,+}: {+ getIsItemSelectable?: (item: SelectableUser) => boolean;+ getIsItemEnabled?: (item: SelectableUser) => boolean;+}) {+ const [selectedKeys, setSelectedKeys] = useState<Set<string>>(new Set());++ const nonAdminUsers = getIsItemSelectable+ ? selectableUsers.filter(getIsItemSelectable)+ : selectableUsers;++ const selectionPlugin = useXDSTableSelection<SelectableUser>({+ getIsItemSelected: item => selectedKeys.has(item.id),+ onSelectItem: ({item, isSelected}) => {+ const next = new Set(selectedKeys);+ if (isSelected) {+ next.add(item.id);+ } else {+ next.delete(item.id);+ }+ setSelectedKeys(next);+ },+ onSelectAll: ({isAllSelected}) => {+ setSelectedKeys(+ isAllSelected ? new Set(nonAdminUsers.map(u => u.id)) : new Set(),+ );+ },+ getIsAllSelected: () =>+ nonAdminUsers.length > 0 &&+ nonAdminUsers.every(u => selectedKeys.has(u.id)),+ getIsIndeterminate: () => {+ const count = nonAdminUsers.filter(u => selectedKeys.has(u.id)).length;+ return count > 0 && count < nonAdminUsers.length;+ },+ getIsItemSelectable,+ getIsItemEnabled,+ });++ return (+ <XDSTable+ data={selectableUsers}+ columns={selectableColumns}+ idKey="id"+ plugins={{selection: selectionPlugin}}+ />+ );+}++// =============================================================================+// Tests+// =============================================================================++describe('useXDSTableSelection', () => {+ it('renders selection checkboxes in header and body rows', () => {+ render(<SelectionTable />);+ const checkboxes = screen.getAllByRole('checkbox');+ expect(checkboxes).toHaveLength(4);+ });++ it('renders header checkbox with "Select all rows" label', () => {+ render(<SelectionTable />);+ expect(screen.getByLabelText('Select all rows')).toBeInTheDocument();+ });++ it('renders row checkboxes with "Select row" label', () => {+ render(<SelectionTable />);+ const rowCheckboxes = screen.getAllByLabelText('Select row');+ expect(rowCheckboxes).toHaveLength(3);+ });++ it('toggles individual row selection on click', async () => {+ const user = userEvent.setup();+ render(<SelectionTable />);+ const rowCheckboxes = screen.getAllByLabelText('Select row');++ await user.click(rowCheckboxes[0]);++ const rows = screen.getAllByRole('row');+ expect(rows[1]).toHaveAttribute('aria-selected', 'true');+ expect(rows[2]).not.toHaveAttribute('aria-selected');+ expect(rows[3]).not.toHaveAttribute('aria-selected');+ });++ it('deselects a selected row on click', async () => {+ const user = userEvent.setup();+ render(<SelectionTable />);+ const rowCheckboxes = screen.getAllByLabelText('Select row');++ await user.click(rowCheckboxes[0]);+ expect(screen.getAllByRole('row')[1]).toHaveAttribute(+ 'aria-selected',+ 'true',+ );++ await user.click(rowCheckboxes[0]);+ expect(screen.getAllByRole('row')[1]).not.toHaveAttribute('aria-selected');+ });++ it('selects all rows when select-all is clicked', async () => {+ const user = userEvent.setup();+ render(<SelectionTable />);+ const selectAll = screen.getByLabelText('Select all rows');++ await user.click(selectAll);++ const rows = screen.getAllByRole('row');+ expect(rows[1]).toHaveAttribute('aria-selected', 'true');+ expect(rows[2]).toHaveAttribute('aria-selected', 'true');+ expect(rows[3]).toHaveAttribute('aria-selected', 'true');+ });++ it('deselects all rows when select-all is clicked again', async () => {+ const user = userEvent.setup();+ render(<SelectionTable />);+ const selectAll = screen.getByLabelText('Select all rows');++ await user.click(selectAll);+ await user.click(selectAll);++ const rows = screen.getAllByRole('row');+ expect(rows[1]).not.toHaveAttribute('aria-selected');+ expect(rows[2]).not.toHaveAttribute('aria-selected');+ expect(rows[3]).not.toHaveAttribute('aria-selected');+ });++ it('hides checkbox for non-selectable rows', () => {+ render(+ <SelectionTable getIsItemSelectable={item => item.role !== 'admin'} />,+ );+ const checkboxes = screen.getAllByRole('checkbox');+ expect(checkboxes).toHaveLength(3);+ });++ it('disables checkbox for disabled rows', () => {+ render(<SelectionTable getIsItemEnabled={item => !item.isLocked} />);+ const rowCheckboxes = screen.getAllByLabelText('Select row');+ expect(rowCheckboxes[0]).not.toBeDisabled();+ expect(rowCheckboxes[1]).not.toBeDisabled();+ expect(rowCheckboxes[2]).toBeDisabled();+ });++ it('prepends selection <td> to each body row', () => {+ render(<SelectionTable />);+ const rows = screen.getAllByRole('row');+ const firstBodyRow = rows[1];+ const cells = within(firstBodyRow).getAllByRole('cell');+ expect(cells).toHaveLength(3);+ });++ it('prepends selection <th> to header row', () => {+ render(<SelectionTable />);+ const headerRow = screen.getAllByRole('row')[0];+ const headers = within(headerRow).getAllByRole('columnheader');+ expect(headers).toHaveLength(3);+ });+});diff --git a/packages/core/src/Table/plugins/selection/useXDSTableSelection.tsx b/packages/core/src/Table/plugins/selection/useXDSTableSelection.tsxnew file mode 100644index 0000000000..2a63e0f17b--- /dev/null+++ b/packages/core/src/Table/plugins/selection/useXDSTableSelection.tsx@@ -0,0 +1,171 @@+/**+ * @file useXDSTableSelection.tsx+ * @input React, types, XDSCheckboxInput, XDSTableCell, XDSTableHeaderCell, theme tokens+ * @output Exports useXDSTableSelection hook and UseXDSTableSelectionConfig type+ * @position Selection plugin; consumed by XDSTable via plugins prop+ *+ * SYNC: When modified, update these files to stay in sync:+ * - /packages/core/src/Table/README.md (selection documentation)+ * - /packages/core/src/Table/index.ts (exports)+ */++import {createContext, useContext, useMemo, type ReactNode} from 'react';+import * as stylex from '@stylexjs/stylex';+import {colorVars, spacingVars} from '../../../theme/tokens.stylex';+import {XDSCheckboxInput} from '../../../CheckboxInput';+import {XDSTableCell} from '../../XDSTableCell';+import {XDSTableHeaderCell} from '../../XDSTableHeaderCell';+import type {TablePlugin, BodyRowRenderProps} from '../../types';++// =============================================================================+// Config Type+// =============================================================================++export interface UseXDSTableSelectionConfig<T extends Record<string, unknown>> {+ /** Is this item currently selected? */+ getIsItemSelected: (item: T) => boolean;+ /** Called when a row checkbox is toggled. isSelected = new desired state. */+ onSelectItem: (event: {item: T; isSelected: boolean}) => void;+ /** Called when select-all checkbox is toggled. */+ onSelectAll: (event: {isAllSelected: boolean}) => void;+ /** Are all selectable items currently selected? */+ getIsAllSelected: () => boolean;+ /** Is the selection partial (some but not all)? Shows indeterminate checkbox. */+ getIsIndeterminate?: () => boolean;+ /** Should this row show a checkbox? Non-selectable rows render nothing. @default () => true */+ getIsItemSelectable?: (item: T) => boolean;+ /** Is this row's checkbox interactive? Disabled rows show disabled checkbox. @default () => true */+ getIsItemEnabled?: (item: T) => boolean;+}++// =============================================================================+// Selection Context (for checkbox components to re-render independently)+// =============================================================================++// eslint-disable-next-line @typescript-eslint/no-explicit-any+interface SelectionContextValue<T = any> {+ getIsItemSelected: (item: T) => boolean;+ onSelectItem: (event: {item: T; isSelected: boolean}) => void;+ onSelectAll: (event: {isAllSelected: boolean}) => void;+ getIsAllSelected: () => boolean;+ getIsIndeterminate?: () => boolean;+ getIsItemSelectable?: (item: T) => boolean;+ getIsItemEnabled?: (item: T) => boolean;+}++const SelectionContext = createContext<SelectionContextValue | null>(null);++// =============================================================================+// Checkbox Components+// =============================================================================++function SelectAllCheckbox() {+ const ctx = useContext(SelectionContext);+ if (!ctx) return null;+ const allSelected = ctx.getIsAllSelected();+ const indeterminate = ctx.getIsIndeterminate?.() ?? false;+ return (+ <XDSCheckboxInput+ label="Select all rows"+ isLabelHidden+ value={allSelected ? true : indeterminate ? 'indeterminate' : false}+ onChange={() => ctx.onSelectAll({isAllSelected: !allSelected})}+ size="sm"+ />+ );+}++function SelectionRowCheckbox<T>({item}: {item: T}) {+ const ctx = useContext(SelectionContext);+ if (!ctx) return null;+ const selectable = ctx.getIsItemSelectable?.(item) ?? true;+ if (!selectable) return null;+ const selected = ctx.getIsItemSelected(item);+ const enabled = ctx.getIsItemEnabled?.(item) ?? true;+ return (+ <XDSCheckboxInput+ label="Select row"+ isLabelHidden+ value={selected}+ onChange={() => ctx.onSelectItem({item, isSelected: !selected})}+ isDisabled={!enabled}+ size="sm"+ />+ );+}++// =============================================================================+// Styles+// =============================================================================++const selectedRowStyles = stylex.create({+ row: {+ backgroundColor: colorVars['--color-accent-deemphasized'],+ },+});++const selectionCellStyles = stylex.create({+ base: {+ width: '36px',+ minWidth: '36px',+ maxWidth: '36px',+ paddingInline: spacingVars['--spacing-2'],+ textAlign: 'center',+ },+});++// =============================================================================+// Hook+// =============================================================================++export function useXDSTableSelection<T extends Record<string, unknown>>(+ config: UseXDSTableSelectionConfig<T>,+): TablePlugin<T> {+ return useMemo(+ (): TablePlugin<T> => ({+ transformTableContext(children: ReactNode) {+ return (+ <SelectionContext.Provider value={config}>+ {children}+ </SelectionContext.Provider>+ );+ },++ transformHeaderRow(props) {+ return {+ ...props,+ children: (+ <>+ <XDSTableHeaderCell xstyle={selectionCellStyles.base}>+ <SelectAllCheckbox />+ </XDSTableHeaderCell>+ {props.children}+ </>+ ),+ };+ },++ transformBodyRow(props: BodyRowRenderProps, item: T) {+ const isSelected = config.getIsItemSelected(item);+ return {+ htmlProps: {+ ...props.htmlProps,+ 'aria-selected': isSelected || undefined,+ },+ styles: isSelected+ ? [...props.styles, selectedRowStyles.row]+ : props.styles,+ children: (+ <>+ <XDSTableCell xstyle={selectionCellStyles.base}>+ <SelectionRowCheckbox item={item} />+ </XDSTableCell>+ {props.children}+ </>+ ),+ };+ },+ }),+ [config],+ );+}diff --git a/packages/core/src/Table/types.ts b/packages/core/src/Table/types.tsindex f32b87844e..80f1a98347 100644--- a/packages/core/src/Table/types.ts+++ b/packages/core/src/Table/types.ts@@ -10,6 +10,7 @@*/import type {+ ComponentType,HTMLAttributes,TdHTMLAttributes,ThHTMLAttributes,@@ -79,6 +80,7 @@ export interface TableRenderProps {export interface HeaderRowRenderProps {htmlProps: HTMLAttributes<HTMLTableRowElement>;styles: StyleXStyles[];+ children: ReactNode;}/** Props passed through the plugin pipeline for each `<th>` */@@ -91,6 +93,7 @@ export interface HeaderCellRenderProps {export interface BodyRowRenderProps {htmlProps: HTMLAttributes<HTMLTableRowElement>;styles: StyleXStyles[];+ children: ReactNode;}/** Props passed through the plugin pipeline for each body `<td>` */@@ -131,6 +134,30 @@ export interface TablePlugin<column: XDSTableColumn<T>,item: T,) => BodyCellRenderProps;+ /** Wrap the table output in context providers */+ transformTableContext?: (children: ReactNode) => ReactNode;+}++// =============================================================================+// Component Interfaces (for components prop)+// =============================================================================++/** Props for row components used in the components prop */+export interface TableRowComponentProps extends HTMLAttributes<HTMLTableRowElement> {+ children: ReactNode;+ xstyle?: StyleXStyles[];+}++/** Props for cell components used in the components prop */+export interface TableCellComponentProps extends TdHTMLAttributes<HTMLTableCellElement> {+ children?: ReactNode;+ xstyle?: StyleXStyles | StyleXStyles[];+}++/** Props for header cell components used in the components prop */+export interface TableHeaderCellComponentProps extends ThHTMLAttributes<HTMLTableCellElement> {+ children?: ReactNode;+ xstyle?: StyleXStyles | StyleXStyles[];}// =============================================================================@@ -156,6 +183,16 @@ export interface XDSBaseTableProps<T extends Record<string, unknown>> {idKey?: (keyof T & string) | ((item: T) => string | number);/** Plugins to transform render props at each level */plugins?: TablePlugin<T>[];+ /**+ * Component overrides for table elements.+ * When provided, these components are rendered instead of raw HTML elements.+ * Components receive `xstyle` from plugin transforms.+ */+ components?: {+ Row?: ComponentType<TableRowComponentProps>;+ Cell?: ComponentType<TableCellComponentProps>;+ HeaderCell?: ComponentType<TableHeaderCellComponentProps>;+ };/** Children mode — render `<tr>`/`<td>` directly instead of data-driven */children?: ReactNode;/** Additional HTML attributes for the `<table>` element */diff --git a/packages/core/src/Table/useXDSBaseTablePlugins.ts b/packages/core/src/Table/useXDSBaseTablePlugins.tsnew file mode 100644index 0000000000..14281de142--- /dev/null+++ b/packages/core/src/Table/useXDSBaseTablePlugins.ts@@ -0,0 +1,90 @@+/**+ * @file useXDSBaseTablePlugins.ts+ * @input React, types.ts+ * @output Exports useXDSBaseTablePlugins hook+ * @position Utility hook; used by XDSTable to convert named plugin records to stable arrays+ *+ * SYNC: When modified, update these files to stay in sync:+ * - /packages/core/src/Table/index.ts (exports)+ * - /packages/core/src/Table/XDSTable.tsx (primary consumer)+ */++import {useRef} from 'react';+import type {TablePlugin} from './types';++/**+ * Converts a named plugin record (`Record<string, TablePlugin>`) to a stable+ * memoized array for `XDSBaseTable`. Compares plugin values by identity so+ * that inline `plugins={{ selection: stablePlugin }}` doesn't break row+ * memoization — only produces a new array when a plugin value actually changes.+ *+ * @param basePlugins - Stable array of built-in plugins (e.g. XDS style plugin)+ * @param userPlugins - Named plugin record from the consumer+ * @returns Stable array of plugins suitable for XDSBaseTable+ *+ * @example+ * ```tsx+ * const plugins = useXDSBaseTablePlugins([tablePlugin], userPlugins);+ * <XDSBaseTable plugins={plugins} ... />+ * ```+ */+export function useXDSBaseTablePlugins<T extends Record<string, unknown>>(+ basePlugins: TablePlugin<T>[],+ userPlugins: Record<string, TablePlugin<T>> | undefined,+): TablePlugin<T>[] {+ const prevRef = useRef<{+ basePlugins: TablePlugin<T>[];+ userPlugins: Record<string, TablePlugin<T>> | undefined;+ result: TablePlugin<T>[];+ } | null>(null);++ // Check if we can reuse the previous result+ if (prevRef.current != null) {+ const prev = prevRef.current;++ // Fast path: same references+ if (prev.basePlugins === basePlugins && prev.userPlugins === userPlugins) {+ return prev.result;+ }++ // Deep identity comparison: check if all plugin values are the same+ if (+ prev.basePlugins === basePlugins &&+ arePluginRecordsEqual(prev.userPlugins, userPlugins)+ ) {+ // Update stored reference but return same result array+ prev.userPlugins = userPlugins;+ return prev.result;+ }+ }++ // Compute new result+ const userValues = userPlugins ? Object.values(userPlugins) : [];+ const result = [...basePlugins, ...userValues];++ prevRef.current = {basePlugins, userPlugins, result};+ return result;+}++/**+ * Compares two plugin records by checking that they have the same keys+ * and each key maps to the same plugin instance (by reference).+ */+function arePluginRecordsEqual<T extends Record<string, unknown>>(+ a: Record<string, TablePlugin<T>> | undefined,+ b: Record<string, TablePlugin<T>> | undefined,+): boolean {+ if (a === b) return true;+ if (a == null || b == null) return false;++ const keysA = Object.keys(a);+ const keysB = Object.keys(b);++ if (keysA.length !== keysB.length) return false;++ for (const key of keysA) {+ if (a[key] !== b[key]) return false;+ }++ return true;+}