Skip to content

An open source design system that's fully customizable and agent ready

TypeScript

refactor(table): Phase 1 — foundations (#1059)

Cindy Zhang791a57b5ffe1
diff --git a/packages/core/src/Table/XDSBaseTable.tsx b/packages/core/src/Table/XDSBaseTable.tsx
index c058f2c9b3..fea66c17c8 100644
--- a/packages/core/src/Table/XDSBaseTable.tsx
+++ b/packages/core/src/Table/XDSBaseTable.tsx
@@ -28,7 +28,7 @@ import type {
import {
generateColumns,
defaultCellRenderer,
- DEFAULT_MIN_COLUMN_WIDTH,
+ resolveColumnWidths,
} from './columnUtils';
import {XDSTableRow} from './XDSTableRow';
import {XDSTableCell} from './XDSTableCell';
@@ -147,14 +147,18 @@ function TableRowInner<T extends Record<string, unknown>>({
/**
* Compares TableRowProps to determine if re-render is needed.
* Shallow compares the item object and checks if columns/plugins references changed.
+ *
+ * Includes rowIndex in the comparison so that plugins using the index
+ * (e.g. for row numbering or conditional formatting) get correct values
+ * after insertions/deletions. This also future-proofs for tree grid
+ * index paths where structural position matters.
*/
function areRowPropsEqual<T extends Record<string, unknown>>(
prevProps: TableRowProps<T>,
nextProps: TableRowProps<T>,
): boolean {
- // Row index affects CSS :nth-child styling, but not React re-render
- // We don't compare rowIndex as it's handled by CSS
if (prevProps.rowKey !== nextProps.rowKey) return false;
+ if (prevProps.rowIndex !== nextProps.rowIndex) return false;
// If columns, plugins, or components change, need to re-render all rows
if (prevProps.columns !== nextProps.columns) return false;
@@ -215,44 +219,9 @@ function XDSBaseTableInner<T extends Record<string, unknown>>({
const resolvedColumns: XDSTableColumn<T>[] =
columnsProp ?? (data ? generateColumns(data) : []);
- // Compute table min-width from column constraints.
- // With table-layout: fixed, minWidth on cells is ignored — the table itself
- // must be wide enough that no proportional column shrinks below its minWidth.
- // Since proportional ratios are always maintained, we find the column that
- // constrains the table the most: tableWidth >= minWidth * totalProportion / proportion.
- // Table min-width = max of those values + sum of pixel column widths.
- const tableMinWidth = (() => {
- let totalProportion = 0;
- let pixelTotal = 0;
- const proportionalCols: Array<{proportion: number; minWidth: number}> = [];
-
- for (const col of resolvedColumns) {
- const w = col.width;
- if (w?.type === 'pixel') {
- pixelTotal += w.value;
- } else {
- const proportion = w?.value ?? 1;
- // Only count minWidth for columns that explicitly used proportional().
- // Columns with no width set (w === undefined) have no minimum.
- const minW = w != null ? (w.minWidth ?? DEFAULT_MIN_COLUMN_WIDTH) : 0;
- totalProportion += proportion;
- proportionalCols.push({proportion, minWidth: minW});
- }
- }
-
- if (totalProportion === 0) return pixelTotal;
-
- // Find the proportional column that requires the most total space
- let maxProportionalSpace = 0;
- for (const col of proportionalCols) {
- const required = (col.minWidth * totalProportion) / col.proportion;
- if (required > maxProportionalSpace) {
- maxProportionalSpace = required;
- }
- }
-
- return pixelTotal + maxProportionalSpace;
- })();
+ // Resolve all column widths in a single pass — produces per-column
+ // inline styles and the aggregate table min-width.
+ const resolvedWidths = resolveColumnWidths(resolvedColumns);
// --- Plugin pipeline: table ---
const tableRenderProps = applyPlugins(plugins, p => p.transformTable, {
@@ -275,35 +244,9 @@ function XDSBaseTableInner<T extends Record<string, unknown>>({
col,
);
- // Apply column width on the <th>. With table-layout: fixed,
- // header cell sizing controls column widths.
- const colWidth = col.width;
- const widthStyle: React.CSSProperties = {};
-
- if (colWidth?.type === 'pixel') {
- // Fixed pixel width — set both width and minWidth to prevent shrinking
- widthStyle.width = `${colWidth.value}px`;
- widthStyle.minWidth = `${colWidth.value}px`;
- } else {
- // Proportional width — compute percentage from total proportional units.
- const totalProportion = resolvedColumns.reduce((sum, c) => {
- const w = c.width;
- if (!w || w.type === 'proportional') {
- return sum + (w?.value ?? 1);
- }
- return sum;
- }, 0);
- const proportion = colWidth?.value ?? 1;
- if (totalProportion > 0) {
- widthStyle.width = `${(proportion / totalProportion) * 100}%`;
- }
- // Only apply minWidth if the column explicitly used proportional().
- // Columns with no width set (colWidth === undefined) have no minimum.
- if (colWidth != null) {
- const minW = colWidth.minWidth ?? DEFAULT_MIN_COLUMN_WIDTH;
- widthStyle.minWidth = `${minW}px`;
- }
- }
+ // Apply pre-computed column width styles on the <th>.
+ // With table-layout: fixed, header cell sizing controls column widths.
+ const widthStyle = resolvedWidths.columns.get(col.key)?.style ?? {};
const existingStyle = cellRenderProps.htmlProps.style as
| React.CSSProperties
@@ -360,7 +303,10 @@ function XDSBaseTableInner<T extends Record<string, unknown>>({
const tableStyle: React.CSSProperties = {
...(tableRenderProps.htmlProps.style as React.CSSProperties | undefined),
- minWidth: tableMinWidth > 0 ? `${tableMinWidth}px` : undefined,
+ minWidth:
+ resolvedWidths.tableMinWidth > 0
+ ? `${resolvedWidths.tableMinWidth}px`
+ : undefined,
};
let tableElement: ReactNode = (
diff --git a/packages/core/src/Table/XDSTableCell.tsx b/packages/core/src/Table/XDSTableCell.tsx
index a765298757..d2740af141 100644
--- a/packages/core/src/Table/XDSTableCell.tsx
+++ b/packages/core/src/Table/XDSTableCell.tsx
@@ -2,7 +2,7 @@
/**
* @file XDSTableCell.tsx
- * @input React, StyleX, XDSTableContext, theme tokens
+ * @input React, StyleX, XDSTableContext, theme tokens, useTableCellStyles
* @output Exports XDSTableCell component, XDSTableCellProps
* @position Sub-component; used inside XDSTable children mode
*
@@ -11,7 +11,7 @@
* - /packages/core/src/Table/index.ts
*/
-import {useContext, type ReactNode} from 'react';
+import {type ReactNode} from 'react';
import type {XDSBaseProps} from '../XDSBaseProps';
import * as stylex from '@stylexjs/stylex';
import {
@@ -21,8 +21,12 @@ import {
typeScaleVars,
} from '../theme/tokens.stylex';
import type {StyleXStyles} from '../theme/types';
-import {XDSTableContext} from './XDSTableContext';
import {overflowStyles} from './table.stylex';
+import {
+ useTableContext,
+ buildDividerStyles,
+ mergeXStyle,
+} from './useTableCellStyles';
import {xdsClassName, mergeProps} from '../utils';
/** Props for XDSTableCell — thin `<td>` wrapper */
@@ -81,8 +85,6 @@ const dividerColumnStyles = stylex.create({
},
});
-// Shared overflow styles — see table.stylex.ts for rationale
-
/**
* XDSTableCell — a `<td>` wrapper for children/streaming mode.
*
@@ -103,7 +105,7 @@ export function XDSTableCell({
ref,
...props
}: XDSTableCellProps) {
- const ctx = useContext(XDSTableContext);
+ const ctx = useTableContext();
if (!ctx) {
return (
@@ -119,29 +121,17 @@ export function XDSTableCell({
const cellStyles: StyleXStyles[] = [
densityStyles[ctx.density],
overflowStyles.cell,
+ ...buildDividerStyles(ctx, dividerRowStyles.cell, dividerColumnStyles.cell),
];
- if (ctx.dividers === 'rows' || ctx.dividers === 'grid') {
- cellStyles.push(dividerRowStyles.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 (
<td
ref={ref}
{...props}
- {...mergeProps(xdsClassName('table-cell'), stylex.props(...cellStyles))}>
+ {...mergeProps(
+ xdsClassName('table-cell'),
+ stylex.props(...mergeXStyle(cellStyles, xstyle)),
+ )}>
{children}
</td>
);
diff --git a/packages/core/src/Table/XDSTableHeaderCell.tsx b/packages/core/src/Table/XDSTableHeaderCell.tsx
index 22d17edbac..511d09658e 100644
--- a/packages/core/src/Table/XDSTableHeaderCell.tsx
+++ b/packages/core/src/Table/XDSTableHeaderCell.tsx
@@ -2,7 +2,7 @@
/**
* @file XDSTableHeaderCell.tsx
- * @input React, StyleX, XDSTableContext, theme tokens
+ * @input React, StyleX, XDSTableContext, theme tokens, useTableCellStyles
* @output Exports XDSTableHeaderCell component, XDSTableHeaderCellProps
* @position Sub-component; used inside XDSTable for header cells
*
@@ -11,7 +11,7 @@
* - /packages/core/src/Table/index.ts
*/
-import {useContext, type ReactNode} from 'react';
+import {type ReactNode} from 'react';
import type {XDSBaseProps} from '../XDSBaseProps';
import * as stylex from '@stylexjs/stylex';
import {
@@ -22,8 +22,12 @@ import {
borderVars,
} from '../theme/tokens.stylex';
import type {StyleXStyles} from '../theme/types';
-import {XDSTableContext} from './XDSTableContext';
import {overflowStyles} from './table.stylex';
+import {
+ useTableContext,
+ buildDividerStyles,
+ mergeXStyle,
+} from './useTableCellStyles';
import {xdsClassName, mergeProps} from '../utils';
/** Props for XDSTableHeaderCell — `<th>` wrapper with context-aware styling */
@@ -88,8 +92,6 @@ const dividerColumnStyles = stylex.create({
},
});
-// Shared overflow styles — see table.stylex.ts for rationale
-
/**
* XDSTableHeaderCell — a `<th>` wrapper for header cells.
*
@@ -117,7 +119,7 @@ export function XDSTableHeaderCell({
style: incomingStyle,
...props
}: XDSTableHeaderCellProps) {
- const ctx = useContext(XDSTableContext);
+ const ctx = useTableContext();
if (!ctx) {
return (
@@ -135,6 +137,9 @@ export function XDSTableHeaderCell({
);
}
+ // Header cells always get the bottom divider (separates header from body).
+ // Column dividers use the shared buildDividerStyles — but only for
+ // the column axis, since the row divider is the headerDividerStyles.
const cellStyles: StyleXStyles[] = [
headerStyles.cell,
densityStyles[ctx.density],
@@ -142,25 +147,18 @@ export function XDSTableHeaderCell({
overflowStyles.cell,
];
+ // Only add column dividers from the shared builder
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}
{...mergeProps(
xdsClassName('table-header-cell'),
- stylex.props(...cellStyles),
+ stylex.props(...mergeXStyle(cellStyles, xstyle)),
incomingClassName,
incomingStyle as React.CSSProperties,
)}>
diff --git a/packages/core/src/Table/columnUtils.ts b/packages/core/src/Table/columnUtils.ts
index 0805e22827..3171d3b5b7 100644
--- a/packages/core/src/Table/columnUtils.ts
+++ b/packages/core/src/Table/columnUtils.ts
@@ -1,7 +1,7 @@
/**
* @file columnUtils.ts
* @input XDSTableColumn types from types.ts
- * @output Pure utility functions for column width and auto-generation
+ * @output Pure utility functions for column width, layout resolution, and auto-generation
* @position Utility layer; consumed by XDSBaseTable.tsx
*
* SYNC: When modified, update these files to stay in sync:
@@ -9,12 +9,119 @@
* - /packages/core/src/Table/index.ts (exports if functions change)
*/
-import type {ReactNode} from 'react';
+import type {CSSProperties, ReactNode} from 'react';
import type {XDSTableColumn, ProportionalWidth, PixelWidth} from './types';
/** Default minimum width (in px) for proportional columns. */
export const DEFAULT_MIN_COLUMN_WIDTH = 120;
+// =============================================================================
+// Resolved Column Widths
+// =============================================================================
+
+/**
+ * Pre-computed width information for a single column.
+ * Produced by `resolveColumnWidths()`, consumed by header cell rendering.
+ */
+export interface ResolvedColumnWidth {
+ /** Inline style to apply on the `<th>` for this column. */
+ style: CSSProperties;
+}
+
+/**
+ * Result of `resolveColumnWidths()` — contains per-column width styles
+ * and the aggregate table min-width. Computed once and shared between
+ * the table min-width calculation and header cell rendering.
+ */
+export interface ResolvedColumnWidths {
+ /** Per-column width styles, indexed by column key. */
+ columns: Map<string, ResolvedColumnWidth>;
+ /** Minimum table width (px) to prevent proportional columns from shrinking below their minWidth. */
+ tableMinWidth: number;
+}
+
+/**
+ * Resolve column widths for the entire table in a single pass.
+ *
+ * Computes:
+ * - Per-column inline styles (`width`, `minWidth`) for `<th>` elements
+ * - Aggregate `tableMinWidth` for the `<table>` element
+ *
+ * This consolidates width logic that was previously duplicated between
+ * the `tableMinWidth` IIFE and the header cell rendering loop.
+ *
+ * @param columns - Resolved column definitions (after auto-generation)
+ * @returns Pre-computed widths for each column and the table minimum width
+ */
+export function resolveColumnWidths<T extends Record<string, unknown>>(
+ columns: XDSTableColumn<T>[],
+): ResolvedColumnWidths {
+ // --- Pass 1: Categorize columns and compute totals ---
+ let totalProportion = 0;
+ let pixelTotal = 0;
+ const proportionalCols: Array<{
+ key: string;
+ proportion: number;
+ minWidth: number;
+ }> = [];
+
+ for (const col of columns) {
+ const w = col.width;
+ if (w?.type === 'pixel') {
+ pixelTotal += w.value;
+ } else {
+ const proportion = w?.value ?? 1;
+ // Only count minWidth for columns that explicitly used proportional().
+ // Columns with no width set (w === undefined) have no minimum.
+ const minW = w != null ? (w.minWidth ?? DEFAULT_MIN_COLUMN_WIDTH) : 0;
+ totalProportion += proportion;
+ proportionalCols.push({key: col.key, proportion, minWidth: minW});
+ }
+ }
+
+ // --- Pass 2: Compute table min-width ---
+ let maxProportionalSpace = 0;
+ if (totalProportion > 0) {
+ for (const col of proportionalCols) {
+ const required = (col.minWidth * totalProportion) / col.proportion;
+ if (required > maxProportionalSpace) {
+ maxProportionalSpace = required;
+ }
+ }
+ }
+ const tableMinWidth = pixelTotal + maxProportionalSpace;
+
+ // --- Pass 3: Build per-column styles ---
+ const result = new Map<string, ResolvedColumnWidth>();
+
+ for (const col of columns) {
+ const w = col.width;
+ const style: CSSProperties = {};
+
+ if (w?.type === 'pixel') {
+ // Fixed pixel width — set both width and minWidth to prevent shrinking
+ style.width = `${w.value}px`;
+ style.minWidth = `${w.value}px`;
+ } else {
+ // Proportional width — compute percentage from total proportional units.
+ const proportion = w?.value ?? 1;
+ if (totalProportion > 0) {
+ style.width = `${(proportion / totalProportion) * 100}%`;
+ }
+ // Only apply minWidth if the column explicitly used proportional().
+ // Columns with no width set (w === undefined) have no minimum.
+ if (w != null) {
+ const minW = w.minWidth ?? DEFAULT_MIN_COLUMN_WIDTH;
+ style.minWidth = `${minW}px`;
+ }
+ }
+
+ result.set(col.key, {style});
+ }
+
+ return {columns: result, tableMinWidth};
+}
+
/**
* Create a proportional column width (fr-like).
* Columns share available space proportionally.
diff --git a/packages/core/src/Table/index.ts b/packages/core/src/Table/index.ts
index 12e1833692..b45d00cc02 100644
--- a/packages/core/src/Table/index.ts
+++ b/packages/core/src/Table/index.ts
@@ -25,6 +25,7 @@ export {
proportional,
pixel,
generateColumns,
+ resolveColumnWidths,
DEFAULT_MIN_COLUMN_WIDTH,
} from './columnUtils';
export type {
diff --git a/packages/core/src/Table/plugins/selection/useXDSTableSelection.tsx b/packages/core/src/Table/plugins/selection/useXDSTableSelection.tsx
index c10e0fdda0..541c10002b 100644
--- a/packages/core/src/Table/plugins/selection/useXDSTableSelection.tsx
+++ b/packages/core/src/Table/plugins/selection/useXDSTableSelection.tsx
@@ -137,6 +137,15 @@ function SelectAllCheckbox() {
return <SelectAllCheckboxInner store={store} />;
}
+/**
+ * Encode select-all state as a number for useSyncExternalStore.
+ * Avoids string encoding + splitting — the snapshot is a cheap numeric
+ * comparison. Values: 0 = none, 1 = indeterminate, 2 = all selected.
+ */
+const SELECT_NONE = 0;
+const SELECT_INDETERMINATE = 1;
+const SELECT_ALL = 2;
+
/**
* Inner component that subscribes to all-selected/indeterminate state.
* Separated so the useCallback/useSyncExternalStore hooks are not
@@ -150,14 +159,14 @@ function SelectAllCheckboxInner<T extends Record<string, unknown>>({
const getSnapshot = useCallback(() => {
const config = store.getConfig();
const allSelected = config.getIsAllSelected();
+ if (allSelected) return SELECT_ALL;
const indeterminate = config.getIsIndeterminate?.() ?? false;
- return `${allSelected}:${indeterminate}`;
+ return indeterminate ? SELECT_INDETERMINATE : SELECT_NONE;
}, [store]);
- const key = useSyncExternalStore(store.subscribe, getSnapshot, getSnapshot);
- const [allSelectedStr, indeterminateStr] = key.split(':');
- const allSelected = allSelectedStr === 'true';
- const indeterminate = indeterminateStr === 'true';
+ const state = useSyncExternalStore(store.subscribe, getSnapshot, getSnapshot);
+ const allSelected = state === SELECT_ALL;
+ const indeterminate = state === SELECT_INDETERMINATE;
return (
<XDSCheckboxInput
diff --git a/packages/core/src/Table/useTableCellStyles.ts b/packages/core/src/Table/useTableCellStyles.ts
new file mode 100644
index 0000000000..8afb953668
--- /dev/null
+++ b/packages/core/src/Table/useTableCellStyles.ts
@@ -0,0 +1,70 @@
+'use client';
+
+/**
+ * @file useTableCellStyles.ts
+ * @input React, StyleX, XDSTableContext, theme tokens
+ * @output Exports shared cell styling utilities
+ * @position Utility layer; consumed by XDSTableCell and XDSTableHeaderCell
+ *
+ * Consolidates the shared pattern of building divider style arrays
+ * and merging consumer xstyle. Eliminates structural duplication
+ * between body cells and header cells.
+ *
+ * SYNC: When modified, update these files to stay in sync:
+ * - /packages/core/src/Table/XDSTableCell.tsx
+ * - /packages/core/src/Table/XDSTableHeaderCell.tsx
+ */
+
+import {useContext} from 'react';
+import type {StyleXStyles} from '../theme/types';
+import {XDSTableContext, type XDSTableContextValue} from './XDSTableContext';
+
+// =============================================================================
+// Shared Style Builders
+// =============================================================================
+
+/**
+ * Build the divider styles array for a cell based on context.
+ * Shared between body cells and header cells — both apply row/column
+ * dividers the same way.
+ */
+export function buildDividerStyles(
+ ctx: XDSTableContextValue,
+ dividerRowStyle: StyleXStyles,
+ dividerColumnStyle: StyleXStyles,
+): StyleXStyles[] {
+ const result: StyleXStyles[] = [];
+
+ if (ctx.dividers === 'rows' || ctx.dividers === 'grid') {
+ result.push(dividerRowStyle);
+ }
+
+ if (ctx.dividers === 'columns' || ctx.dividers === 'grid') {
+ result.push(dividerColumnStyle);
+ }
+
+ return result;
+}
+
+/**
+ * Merge consumer xstyle (single or array) into a styles array.
+ * Handles the polymorphic xstyle prop that both cell components accept.
+ */
+export function mergeXStyle(
+ styles: StyleXStyles[],
+ xstyle: StyleXStyles | StyleXStyles[] | undefined,
+): StyleXStyles[] {
+ if (!xstyle) return styles;
+ if (Array.isArray(xstyle)) {
+ return [...styles, ...xstyle];
+ }
+ return [...styles, xstyle];
+}
+
+/**
+ * Read the XDSTableContext. Returns null when outside XDSTable,
+ * signaling that the component should render unstyled.
+ */
+export function useTableContext(): XDSTableContextValue | null {
+ return useContext(XDSTableContext);
+}