An open source design system that's fully customizable and agent ready
TypeScript
refactor(table): Phase 3 — Selection rewrite using transformColumns (#1064)
Cindy Zhangaea93356f536
diff --git a/packages/core/src/Table/XDSBaseTable.tsx b/packages/core/src/Table/XDSBaseTable.tsxindex a397c8f18a..6a1b332d4d 100644--- a/packages/core/src/Table/XDSBaseTable.tsx+++ b/packages/core/src/Table/XDSBaseTable.tsx@@ -10,7 +10,7 @@* - /packages/core/src/Table/index.ts (exports if types change)*/-import {memo, type ReactElement, type ReactNode, type Ref} from 'react';+import {memo, useRef, type ReactElement, type ReactNode, type Ref} from 'react';import * as stylex from '@stylexjs/stylex';import type {XDSBaseTableProps,@@ -80,6 +80,19 @@ function applyPlugins<TPlugin, TProps, TArgs extends unknown[]>(// Stable empty array to avoid creating new reference on each renderconst EMPTY_PLUGINS: TablePlugin<Record<string, unknown>>[] = [];+/**+ * Shallow-compare two arrays by element identity.+ * Used to stabilize the resolved columns array across renders.+ */+function areArraysShallowEqual<T>(a: T[], b: T[]): boolean {+ if (a === b) return true;+ if (a.length !== b.length) return false;+ for (let i = 0; i < a.length; i++) {+ if (a[i] !== b[i]) return false;+ }+ return true;+}+interface TableRowProps<T extends Record<string, unknown>> {item: T;rowIndex: number;@@ -149,6 +162,7 @@ function TableRowInner<T extends Record<string, unknown>>({return (<RowComponentkey={rowKey}+ ref={rowRenderProps.ref}{...rowRenderProps.htmlProps}xstyle={rowRenderProps.styles}>{rowRenderProps.children}@@ -234,12 +248,22 @@ function XDSBaseTableInner<T extends Record<string, unknown>>({// --- Plugin pipeline: transformColumns ---// Runs before any element-level transforms. Allows plugins to filter,// reorder, or inject synthetic columns (e.g. selection checkbox).- const resolvedColumns = applyPlugins(+ const transformedColumns = applyPlugins(plugins,p => p.transformColumns,baseColumns,);+ // Stabilize the resolved columns array — transformColumns returns a+ // new array on every call, but if the contents haven't changed, we+ // reuse the previous reference. This prevents MemoizedTableRow from+ // re-rendering all rows when the column array is structurally identical.+ const resolvedColumnsRef = useRef(transformedColumns);+ if (!areArraysShallowEqual(resolvedColumnsRef.current, transformedColumns)) {+ resolvedColumnsRef.current = transformedColumns;+ }+ const resolvedColumns = resolvedColumnsRef.current;+// Resolve all column widths in a single pass — produces per-column// inline styles and the aggregate table min-width.const resolvedWidths = resolveColumnWidths(resolvedColumns);diff --git a/packages/core/src/Table/plugins/selection/useXDSTableSelection.tsx b/packages/core/src/Table/plugins/selection/useXDSTableSelection.tsxindex 541c10002b..2da866c3b6 100644--- a/packages/core/src/Table/plugins/selection/useXDSTableSelection.tsx+++ b/packages/core/src/Table/plugins/selection/useXDSTableSelection.tsx@@ -2,22 +2,27 @@/*** @file useXDSTableSelection.tsx- * @input React, types, XDSCheckboxInput, XDSTableCell, XDSTableHeaderCell, theme tokens+ * @input React, types, XDSCheckboxInput, theme tokens* @output Exports useXDSTableSelection hook and UseXDSTableSelectionConfig type* @position Selection plugin; consumed by XDSTable via plugins prop*- * ## Performance Architecture+ * ## Architecture (v2 — transformColumns + ref-based row styling)*- * Selection state is managed via an external store (SelectionStore) so that- * individual rows can subscribe to their own selection state independently.- * When a row is selected/deselected, only that row re-renders — not the- * entire table body.+ * Selection checkboxes are implemented as a synthetic column prepended via+ * `transformColumns`. The checkbox column flows through the normal cell+ * component pipeline, so it automatically respects component overrides+ * (components prop on XDSBaseTable).*- * The plugin object returned by useXDSTableSelection is referentially stable- * across renders. Selection-dependent rendering (aria-selected, background- * highlight, checkbox state) is handled by store-subscribing components- * (SelectionRowContent, SelectAllCheckbox) rather than in the plugin- * transform functions.+ * Selection state is managed via an external store (SelectionStore) for+ * fine-grained row subscriptions. Each row's checkbox subscribes+ * independently — when selection changes, only that row's checkbox+ * re-renders, not the entire table body.+ *+ * Row-level styling (aria-selected, background) uses imperative DOM+ * updates via a ref callback on each <tr>. The ref subscribes to the+ * store and applies/removes styles when selection changes — no extra+ * DOM elements and no central element tracking. Each subscription+ * self-cleans when the row disconnects.** SYNC: When modified, update these files to stay in sync:* - /packages/core/src/Table/Table.doc.mjs (selection documentation)@@ -33,13 +38,17 @@ import {useMemo,useSyncExternalStore,type ReactNode,+ type Ref,} from 'react';import * as stylex from '@stylexjs/stylex';-import {colorVars, spacingVars} from '../../../theme/tokens.stylex';+import {colorVars} from '../../../theme/tokens.stylex';import {XDSCheckboxInput} from '../../../CheckboxInput';-import {XDSTableCell} from '../../XDSTableCell';-import {XDSTableHeaderCell} from '../../XDSTableHeaderCell';-import type {TablePlugin, BodyRowRenderProps} from '../../types';+import type {+ TablePlugin,+ XDSTableColumn,+ BodyRowRenderProps,+} from '../../types';+import {pixel} from '../../columnUtils';// =============================================================================// Config Type@@ -68,9 +77,8 @@ export interface UseXDSTableSelectionConfig<T extends Record<string, unknown>> {/*** Lightweight external store that lets each row subscribe to selection- * changes independently. When selection state changes, all subscribers are- * notified but only components whose snapshot actually changed will re-render- * (thanks to useSyncExternalStore's built-in equality check on the snapshot).+ * changes independently. Row styling is handled by per-row ref callbacks+ * that subscribe to this store — the store itself holds no DOM references.*/interface SelectionStore<T extends Record<string, unknown>> {subscribe: (listener: () => void) => () => void;@@ -99,6 +107,42 @@ function createSelectionStore<T extends Record<string, unknown>>(};}+/**+ * Apply or remove selection styling on a <tr> element.+ */+function applyRowSelectionStyle(+ el: HTMLTableRowElement,+ isSelected: boolean,+): void {+ if (isSelected) {+ el.setAttribute('aria-selected', 'true');+ el.style.backgroundColor = selectedBgColor;+ } else {+ el.removeAttribute('aria-selected');+ el.style.backgroundColor = '';+ }+}++// =============================================================================+// Ref Merging Utility+// =============================================================================++/**+ * Compose multiple refs into a single callback ref.+ * Used when multiple plugins need to attach refs to the same row.+ */+function mergeRefs<T>(...refs: (Ref<T> | undefined)[]): React.RefCallback<T> {+ return (el: T | null) => {+ for (const ref of refs) {+ if (typeof ref === 'function') {+ ref(el);+ } else if (ref != null) {+ (ref as React.MutableRefObject<T | null>).current = el;+ }+ }+ };+}+// =============================================================================// Selection Context// =============================================================================@@ -110,10 +154,6 @@ const SelectionStoreContext = createContext<SelectionStore<any> | null>(null);// Hooks for subscribing to selection state// =============================================================================-/**- * Subscribe to whether a specific item is selected.- * Only triggers re-render when this item's selected state changes.- */function useIsItemSelected<T extends Record<string, unknown>>(store: SelectionStore<T>,item: T,@@ -182,63 +222,45 @@ function SelectAllCheckboxInner<T extends Record<string, unknown>>({}/**- * Row content component that subscribes to this item's selection state.- * Handles the checkbox cell, aria-selected attribute, and selected row styling.- * Only re-renders when this specific item's selection state changes.+ * Row checkbox component — used as renderCell for the synthetic selection column.+ * Subscribes to this item's selection state independently.*/-function SelectionRowContent<T extends Record<string, unknown>>({+function SelectionCellContent<T extends Record<string, unknown>>({+ item,+}: {+ item: T;+}) {+ const store = useContext(SelectionStoreContext);+ if (!store) return null;++ return <SelectionCellContentInner store={store} item={item} />;+}++function SelectionCellContentInner<T extends Record<string, unknown>>({+ store,item,- children,}: {+ store: SelectionStore<T>;item: T;- children: ReactNode;}) {- const store = useContext(SelectionStoreContext)!;const config = store.getConfig();const isSelected = useIsItemSelected(store, item);const selectable = config.getIsItemSelectable?.(item) ?? true;const enabled = config.getIsItemEnabled?.(item) ?? true;- // Manage aria-selected and background color on the parent <tr> imperatively.- // This avoids re-rendering the entire memoized row component — only this- // content component re-renders when selection state changes.- const cellRef = useRef<HTMLTableCellElement>(null);- useEffect(() => {- const tr = cellRef.current?.parentElement;- if (!tr) return;- if (isSelected) {- tr.setAttribute('aria-selected', 'true');- tr.style.backgroundColor = selectedBgColor;- } else {- tr.removeAttribute('aria-selected');- tr.style.backgroundColor = '';- }- return () => {- if (tr) {- tr.removeAttribute('aria-selected');- tr.style.backgroundColor = '';- }- };- }, [isSelected]);+ if (!selectable) return null;return (- <>- <XDSTableCell ref={cellRef} xstyle={selectionCellStyles.base}>- {selectable && (- <XDSCheckboxInput- label="Select row"- isLabelHidden- value={isSelected}- onChange={() =>- store.getConfig().onSelectItem({item, isSelected: !isSelected})- }- isDisabled={!enabled}- size="sm"- />- )}- </XDSTableCell>- {children}- </>+ <XDSCheckboxInput+ label="Select row"+ isLabelHidden+ value={isSelected}+ onChange={() =>+ store.getConfig().onSelectItem({item, isSelected: !isSelected})+ }+ isDisabled={!enabled}+ size="sm"+ />);}@@ -246,22 +268,22 @@ function SelectionRowContent<T extends Record<string, unknown>>({// Styles// =============================================================================-/**- * Resolved CSS variable for imperative style updates on the <tr>.- * Uses the StyleX token directly so it stays in sync with the theme.- */const selectedBgColor = colorVars['--color-accent-muted'];-const selectionCellStyles = stylex.create({- base: {- width: '36px',- minWidth: '36px',- maxWidth: '36px',- paddingInline: spacingVars['--spacing-2'],- textAlign: 'center',+const selectionColumnStyles = stylex.create({+ center: {+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',},});+/** Selection column key — prefixed to avoid collisions with user columns. */+const SELECTION_COLUMN_KEY = '__xds_selection';++/** Fixed width for the selection column. Content is centered with no horizontal padding. */+const SELECTION_COLUMN_WIDTH = pixel(36);+// =============================================================================// Hook// =============================================================================@@ -269,12 +291,9 @@ const selectionCellStyles = stylex.create({export function useXDSTableSelection<T extends Record<string, unknown>>(config: UseXDSTableSelectionConfig<T>,): TablePlugin<T> {- // Keep config in a ref so the store always reads the latest version- // without creating a new store or plugin object.const configRef = useRef(config);configRef.current = config;- // Create the store once — it reads config via ref, so it never goes stale.const storeRef = useRef<SelectionStore<T> | null>(null);if (storeRef.current == null) {storeRef.current = createSelectionStore(configRef);@@ -282,14 +301,32 @@ export function useXDSTableSelection<T extends Record<string, unknown>>(const store = storeRef.current;// Notify subscribers on every render — useSyncExternalStore will only- // re-render components whose snapshot actually changed.+ // re-render components whose snapshot actually changed. Row ref+ // subscribers apply imperative styling independently.useEffect(() => {store.notify();});- // Return a stable plugin object — never changes after mount.- // Selection-dependent rendering is handled by SelectionRowContent- // and SelectAllCheckbox which subscribe to the store independently.+ // Synthetic selection column — uses renderCell with a subscribing+ // component so each row's checkbox re-renders independently.+ const selectionColumn = useMemo(+ (): XDSTableColumn<T> => ({+ key: SELECTION_COLUMN_KEY,+ header: (+ <div {...stylex.props(selectionColumnStyles.center)}>+ <SelectAllCheckbox />+ </div>+ ),+ width: SELECTION_COLUMN_WIDTH,+ renderCell: (item: T) => (+ <div {...stylex.props(selectionColumnStyles.center)}>+ <SelectionCellContent item={item} />+ </div>+ ),+ }),+ [],+ );+return useMemo((): TablePlugin<T> => ({transformTableContext(children: ReactNode) {@@ -300,35 +337,37 @@ export function useXDSTableSelection<T extends Record<string, unknown>>();},- transformHeaderRow(props) {- return {- ...props,- children: (- <>- <XDSTableHeaderCell xstyle={selectionCellStyles.base}>- <SelectAllCheckbox />- </XDSTableHeaderCell>- {props.children}- </>- ),- };+ transformColumns(columns: XDSTableColumn<T>[]) {+ return [selectionColumn, ...columns];},transformBodyRow(props: BodyRowRenderProps, item: T) {- // Don't read selection state here — that would cause all rows- // to re-render when any selection changes. Instead, delegate to- // SelectionRowContent which subscribes to the store and only- // re-renders when this specific item's selection state changes.+ // Attach a ref to the <tr> that subscribes to the store for+ // imperative row styling. Each row manages its own subscription+ // and self-cleans when disconnected — no central element tracking.+ const selectionRef: React.RefCallback<HTMLTableRowElement> = el => {+ if (!el) return;+ // Apply initial style+ applyRowSelectionStyle(el, store.getConfig().getIsItemSelected(item));+ // Subscribe for future changes+ const unsub = store.subscribe(() => {+ if (!el.isConnected) {+ unsub();+ return;+ }+ applyRowSelectionStyle(+ el,+ store.getConfig().getIsItemSelected(item),+ );+ });+ };+return {...props,- children: (- <SelectionRowContent item={item}>- {props.children}- </SelectionRowContent>- ),+ ref: props.ref ? mergeRefs(props.ref, selectionRef) : selectionRef,};},}),- [store],+ [store, selectionColumn],);}diff --git a/packages/core/src/Table/types.ts b/packages/core/src/Table/types.tsindex 4769529215..538a31be8f 100644--- a/packages/core/src/Table/types.ts+++ b/packages/core/src/Table/types.ts@@ -12,6 +12,7 @@import type {ComponentType,HTMLAttributes,+ Ref,TdHTMLAttributes,ThHTMLAttributes,ReactNode,@@ -170,6 +171,8 @@ export interface BodyRowRenderProps {htmlProps: HTMLAttributes<HTMLTableRowElement>;styles: StyleXStyles[];children: ReactNode;+ /** Ref for the `<tr>` element. Plugins can set this to access the row DOM node. */+ ref?: Ref<HTMLTableRowElement>;}/** Props passed through the plugin pipeline for each body `<td>` */@@ -204,9 +207,7 @@ export interface TablePlugin<* Runs before any element-level transforms. Use to filter, reorder,* or inject synthetic columns (e.g. a selection checkbox column).*/- transformColumns?: (- columns: XDSTableColumn<T>[],- ) => XDSTableColumn<T>[];+ transformColumns?: (columns: XDSTableColumn<T>[]) => XDSTableColumn<T>[];/** Transform the root `<table>` element props */transformTable?: (props: TableRenderProps) => TableRenderProps;/** Transform the header `<tr>` props */@@ -238,6 +239,8 @@ export interface TablePlugin</** Props for row components used in the components prop */export interface TableRowComponentProps extends HTMLAttributes<HTMLTableRowElement> {+ /** Ref forwarded to the root `<tr>` element */+ ref?: Ref<HTMLTableRowElement>;children: ReactNode;xstyle?: StyleXStyles[];}