An open source design system that's fully customizable and agent ready
TypeScript
feat(Table): useXDSTableColumnResize plugin #978 (#1012)
Cindy Zhangafbe39997f98
diff --git a/0001-feat-Table-implement-useXDSTableColumnResize-plugin-.patch b/0001-feat-Table-implement-useXDSTableColumnResize-plugin-.patchnew file mode 100644index 0000000000..c344571a53--- /dev/null+++ b/0001-feat-Table-implement-useXDSTableColumnResize-plugin-.patch@@ -0,0 +1,1521 @@+From 5d99b110c107892f4666ccfe0c29af9ce987968c Mon Sep 17 00:00:00 2001+From: Cindy Zhang <[email protected]>+Date: Tue, 31 Mar 2026 00:42:58 -0700+Subject: [PATCH] feat(Table): implement useXDSTableColumnResize plugin #978++---+ packages/core/src/Table/XDSBaseTable.tsx | 9 +-+ packages/core/src/Table/index.ts | 2 ++ .../src/Table/plugins/columnResize/SPEC.md | 410 ++++++++++++++ .../src/Table/plugins/columnResize/index.ts | 2 ++ .../useXDSTableColumnResize.test.tsx | 576 +++++++++++++++++++ .../columnResize/useXDSTableColumnResize.tsx | 445 +++++++++++++++ 6 files changed, 1443 insertions(+), 1 deletion(-)+ create mode 100644 packages/core/src/Table/plugins/columnResize/SPEC.md+ create mode 100644 packages/core/src/Table/plugins/columnResize/index.ts+ create mode 100644 packages/core/src/Table/plugins/columnResize/useXDSTableColumnResize.test.tsx+ create mode 100644 packages/core/src/Table/plugins/columnResize/useXDSTableColumnResize.tsx++diff --git a/packages/core/src/Table/XDSBaseTable.tsx b/packages/core/src/Table/XDSBaseTable.tsx+index 0ab81cfd1..f14f084c9 100644+--- a/packages/core/src/Table/XDSBaseTable.tsx++++ b/packages/core/src/Table/XDSBaseTable.tsx+@@ -257,13 +257,20 @@ function XDSBaseTableInner<T extends Record<string, unknown>>({+ ? {title: headerContent}+ : {};+++ // Extract plugin-injected children (e.g. resize handles) so they++ // render alongside the header content. Explicit JSX children would++ // otherwise override htmlProps.children during spread.++ const {children: injectedChildren, ...restHtmlProps} = mergedHtmlProps as++ typeof mergedHtmlProps & {children?: ReactNode};+++ return (+ <HeaderCellComponent+ key={col.key}+- {...mergedHtmlProps}++ {...restHtmlProps}+ {...headerTitleProp}+ xstyle={cellRenderProps.styles}>+ {headerContent}++ {injectedChildren}+ </HeaderCellComponent>+ );+ });+diff --git a/packages/core/src/Table/index.ts b/packages/core/src/Table/index.ts+index 577da692b..6730cf933 100644+--- a/packages/core/src/Table/index.ts++++ b/packages/core/src/Table/index.ts+@@ -17,6 +17,7 @@ export {XDSTableHeaderCell} from './XDSTableHeaderCell';+ export {XDSTableContext} from './XDSTableContext';+ export {useXDSTableSelection} from './plugins/selection';+ export {useXDSTableSelectionState} from './plugins/selection';++export {useXDSTableColumnResize} from './plugins/columnResize';+ export {useXDSBaseTablePlugins} from './useXDSBaseTablePlugins';+ export {+ proportional,+@@ -54,3 +55,4 @@ export type {+ UseXDSTableSelectionStateConfig,+ UseXDSTableSelectionStateResult,+ } from './plugins/selection';++export type {UseXDSTableColumnResizeConfig} from './plugins/columnResize';+diff --git a/packages/core/src/Table/plugins/columnResize/SPEC.md b/packages/core/src/Table/plugins/columnResize/SPEC.md+new file mode 100644+index 000000000..fe56d1b72+--- /dev/null++++ b/packages/core/src/Table/plugins/columnResize/SPEC.md+@@ -0,0 +1,410 @@++# useXDSTableColumnResize — Plugin Specification++++## 1. WWW Reference Analysis++++### API Surface++++```ts++hook useXDSTableColumnResize<TItem, TColumnKey>(++ config: XDSTableColumnResizeConfig<TColumnKey>++): XDSTableColumnResize<TItem, TColumnKey>++```++++**Config type:**++++```ts++interface XDSTableColumnResizeConfig<TColumnKey> {++ /** Map of column keys to their current size specs */++ columnSizes: XDSColumnSizeSpecMap<TColumnKey>;++ /** Callback when a column resize operation completes */++ onColumnResizeEnd?: XDSTableOnColumnResizeEnd<TColumnKey>;++}++++type XDSColumnSizeSpecMap<TColumnKey> = Map<TColumnKey, XDSTableColumnSizeSpec>;++type XDSTableColumnSizeSpec = { width: number };++type XDSTableOnColumnResizeEnd<TColumnKey> = (event: {++ columnKey: TColumnKey;++ newColumnWidth: number;++}) => void;++```++++### Interaction Model (WWW)++++- **Resize handle**: 6px invisible hit area positioned at the right edge of each header cell++- **Hover**: `cursor: ew-resize`, handle opacity transitions from 0 to 1++- **Dragging**: 1px colored line indicator visible during drag, uses theme colors via `useXDSTheme()`++- **StyleX**: Handle is `position: absolute`, `right: 0`, full height, `opacity: 0 → 1` on hover/active++++### State Flow (WWW)++++1. User hovers header cell right edge → handle becomes visible++2. `mousedown` on handle → begin drag, capture pointer++3. `mousemove` → update column width in real-time (pixel-based delta)++4. `mouseup` → finalize width, fire `onColumnResizeEnd` callback++5. During resize, proportional columns convert to pixel widths++++---++++## 2. XDS OSS Plugin API++++### Hook Signature++++```ts++function useXDSTableColumnResize<T extends Record<string, unknown>>(++ config: UseXDSTableColumnResizeConfig++): TablePlugin<T>++```++++### Config Type++++```ts++interface UseXDSTableColumnResizeConfig {++ /**++ * Column width overrides from resize operations.++ * Keys are column `key` strings. Values are pixel widths.++ * When a column key is present here, it overrides the column's++ * declared `width` (proportional or pixel).++ *++ * Controlled: consumer owns this state and persists as needed.++ */++ columnWidths?: Record<string, number>;++++ /**++ * Called when a resize operation completes (mouseup / pointerup).++ * Consumer updates their `columnWidths` state here.++ */++ onColumnResizeEnd?: (event: {++ columnKey: string;++ newWidth: number;++ }) => void;++++ /**++ * Minimum column width in pixels during resize.++ * @default 50++ */++ minWidth?: number;++++ /**++ * Maximum column width in pixels during resize.++ * @default Infinity (no max)++ */++ maxWidth?: number;++}++```++++### Design Decisions++++**Why `Record<string, number>` instead of `Map`?**++XDS OSS uses plain objects for config throughout (see selection plugin). Maps add serialization friction and don't match the existing API patterns. Column keys are already `string` in `XDSTableColumn`.++++**Why controlled state?**++The selection plugin pattern uses controlled state (`getIsItemSelected`, `onSelectItem`). Column resize follows the same principle — the consumer owns `columnWidths` in their state and updates it via `onColumnResizeEnd`. This makes persistence (localStorage, URL params, server) trivial.++++**Proportional → Pixel Conversion on Resize:**++When a user starts resizing a proportional column, the plugin must resolve its current rendered pixel width (via `getBoundingClientRect()` on the `<th>`) and operate in pixel space from that point forward. The `onColumnResizeEnd` callback reports the final pixel width. The consumer's `columnWidths` state then overrides the original proportional width for that column.++++Columns that are never resized keep their original `proportional()` or `pixel()` width — only resized columns get pixel overrides.++++**Double-Click Auto-Fit:**++Double-clicking the resize handle should auto-size the column to fit its content. Implementation approach:++1. On `dblclick`, measure the natural content width of all visible cells in the column++2. Create an off-screen measurement element, render cell content, read `scrollWidth`++3. Clamp to `[minWidth, maxWidth]`, fire `onColumnResizeEnd` with the result++++This is a P1 follow-up, not required for initial implementation.++++### Plugin Transforms Used++++| Transform | Purpose |++|---|---|++| `transformHeaderCell` | Inject resize handle element into each header cell; apply `position: relative` so handle can be absolutely positioned; apply `width` style override from `columnWidths` |++| `transformTable` | Add `user-select: none` to `<table>` during active drag to prevent text selection |++++The plugin does NOT use:++- `transformHeaderRow` — no row-level changes needed++- `transformBodyRow` — body rows don't need modification++- `transformBodyCell` — column widths are controlled via `<th>` with `table-layout: fixed`++- `transformTableContext` — no context provider needed (resize state is internal to the hook)++++### Colgroup Strategy++++The current `XDSBaseTable` uses `table-layout: fixed` and sets widths via `<th>` `minWidth` styles. The resize plugin continues this pattern: overridden widths are applied as inline `width` + `minWidth` + `maxWidth` (all set to the same pixel value) on the `<th>` via `transformHeaderCell`. This locks the column to the resized width under `table-layout: fixed`.++++No `<colgroup>` is introduced. This keeps the plugin self-contained and avoids structural changes to `XDSBaseTable`.++++### Persist Model++++The plugin is **stateless** — it receives `columnWidths` and reports changes via `onColumnResizeEnd`. Persistence is the consumer's responsibility:++++```tsx++// Example: useState persistence++const [columnWidths, setColumnWidths] = useState<Record<string, number>>({});++++const resizePlugin = useXDSTableColumnResize({++ columnWidths,++ onColumnResizeEnd: ({ columnKey, newWidth }) => {++ setColumnWidths(prev => ({ ...prev, [columnKey]: newWidth }));++ },++});++++// Example: localStorage persistence++const [columnWidths, setColumnWidths] = useState<Record<string, number>>(() => {++ const saved = localStorage.getItem('table-widths');++ return saved ? JSON.parse(saved) : {};++});++++const resizePlugin = useXDSTableColumnResize({++ columnWidths,++ onColumnResizeEnd: ({ columnKey, newWidth }) => {++ setColumnWidths(prev => {++ const next = { ...prev, [columnKey]: newWidth };++ localStorage.save('table-widths', JSON.stringify(next));++ return next;++ });++ },++});++```++++### Reset API++++Consumers can reset column widths by clearing their state:++++```tsx++// Reset single column++setColumnWidths(prev => {++ const { [columnKey]: _, ...rest } = prev;++ return rest;++});++++// Reset all++setColumnWidths({});++```++++No special reset API is needed in the plugin.++++---++++## 3. Behavioral Spec++++### 3.1 Hover++++| State | Visual |++|---|---|++| Mouse not near right edge of `<th>` | No resize indicator visible |++| Mouse enters 6px hit area at right edge | `cursor: ew-resize`; resize handle fades in (1px vertical line, theme accent color) |++| Mouse leaves hit area | Handle fades out |++++The hit area extends 3px inside and 3px outside the cell border to make it easy to target.++++### 3.2 Drag (Pointer-Based Resize)++++| Step | Behavior |++|---|---|++| `pointerdown` on handle | Capture pointer (`setPointerCapture`). Record initial column width and pointer X. Add `user-select: none` to table. |++| `pointermove` | Calculate delta = `currentX - startX`. New width = `max(minWidth, min(maxWidth, initialWidth + delta))`. Apply width to `<th>` via inline style (live preview). |++| `pointerup` | Release pointer capture. Remove `user-select: none`. Fire `onColumnResizeEnd({ columnKey, newWidth })`. |++| Drag below `minWidth` | Column clamps to `minWidth`; cursor continues tracking but width doesn't decrease further. |++| Drag above `maxWidth` | Column clamps to `maxWidth`. |++| `pointercancel` / blur | Abort resize; revert to width before drag started. |++++**Why pointer events, not mouse events?**++Pointer events provide `setPointerCapture`, which ensures `pointermove`/`pointerup` fire on the handle element even when the pointer moves outside the element or the window. This eliminates the need for document-level event listeners and works correctly with touch input.++++### 3.3 Release++++- On `pointerup`, the final width is committed via `onColumnResizeEnd`.++- The `<th>` inline style applied during drag remains in place (it matches the committed width).++- Adjacent columns reflow naturally under `table-layout: fixed` — their proportional widths redistribute within remaining space.++++### 3.4 Double-Click (Auto-Fit) — P1 Follow-Up++++| Step | Behavior |++|---|---|++| `dblclick` on resize handle | Measure natural content width of all visible cells in the column. Clamp to `[minWidth, maxWidth]`. Fire `onColumnResizeEnd`. |++++### 3.5 Keyboard Accessibility++++| Key | Behavior |++|---|---|++| `Tab` | Resize handle is focusable (rendered as a `<div role="separator" tabIndex={0}>`) |++| `Enter` / `Space` | Activate resize mode (equivalent to pointerdown) |++| `ArrowLeft` | Decrease column width by 10px (clamped to minWidth) |++| `ArrowRight` | Increase column width by 10px (clamped to maxWidth) |++| `Shift+ArrowLeft/Right` | Decrease/increase by 50px |++| `Escape` | Cancel resize, revert to width before activation |++| `Enter` (while active) | Commit current width, exit resize mode |++++**ARIA attributes on the handle:**++```tsx++<div++ role="separator"++ aria-orientation="vertical"++ aria-valuenow={currentWidth}++ aria-valuemin={minWidth}++ aria-valuemax={maxWidth}++ aria-label={`Resize column ${columnHeader}`}++ tabIndex={0}++/>++```++++### 3.6 RTL Support++++In RTL layouts, the resize handle appears at the left edge of the header cell (logical "end" edge). Drag direction is inverted: dragging left increases width, dragging right decreases.++++Use CSS logical properties (`inset-inline-end: 0`) for handle positioning so RTL works automatically.++++### 3.7 Touch Support++++Pointer events handle touch natively. The 6px hit area may be too small for touch — consider increasing to 16px on touch devices via `@media (pointer: coarse)`.++++---++++## 4. Competitive Analysis++++### 4.1 WWW XDS Internal (`useXDSTableColumnResize`)++++- **Architecture**: Wraps `useWebTableColumnResize` with XDS theming++- **Width model**: `Map<TColumnKey, { width: number }>` — pixel-only after resize++- **Handle**: 6px absolute-positioned div, opacity animation++- **Callback**: `onColumnResizeEnd({ columnKey, newColumnWidth })`++- **Strengths**: Proven in production, theme-integrated++- **Gaps**: No keyboard a11y, no auto-fit, no RTL consideration documented++++### 4.2 AG Grid++++- **Architecture**: Built into column definition; `resizable: true` per column++- **Width model**: Pixel widths with `minWidth`/`maxWidth` per column++- **Handle**: Appears between column headers++- **Auto-fit**: `autoSizeColumn()` / `autoSizeAllColumns()` API++- **Callback**: `onColumnResized` event with `{ column, finished, source }`++- **Strengths**: `source` field distinguishes user vs API resize; auto-size API; `suppressAutoSize` per column++- **Gaps**: Heavy abstraction, not composable as a plugin++++### 4.3 Mantine Table++++- **Architecture**: `columnSizing` state in `useReactTable` (TanStack-based)++- **Width model**: `columnSizingInfo` tracks delta during drag++- **Handle**: CSS class on th, styled separator++- **Callback**: `onColumnSizingChange` state updater++- **Strengths**: TanStack integration, declarative state++- **Gaps**: Tightly coupled to TanStack table internals++++### 4.4 TanStack Table++++- **Architecture**: `columnResizing` feature; `enableResizing` per column++- **Width model**: Tracks `deltaOffset` during drag, `columnSizingInfo` state++- **Resize modes**: `onChange` (live) and `onEnd` (commit on release)++- **Handle**: Consumer renders using `header.getResizeHandler()`++- **Callback**: `onColumnSizingChange`, `onColumnSizingInfoChange`++- **Strengths**: Headless — complete rendering control; two resize modes; works with any framework++- **Gaps**: Consumer responsible for all rendering; no built-in a11y++++### Summary++++| Feature | WWW | AG Grid | Mantine | TanStack | XDS OSS (proposed) |++|---|---|---|---|---|---|++| Plugin/composable | Yes | No (built-in) | No (TanStack) | Yes (headless) | Yes |++| Controlled state | Yes | Partial | Yes | Yes | Yes |++| Min/max constraints | No | Yes | No | No | Yes |++| Keyboard a11y | No | Yes | No | No | Yes |++| Auto-fit | No | Yes | No | No | P1 |++| RTL | Unknown | Yes | Unknown | No | Yes |++| Live preview | Yes | Yes | Optional | Optional | Yes |++| Persist model | Consumer | Built-in | Consumer | Consumer | Consumer |++++---++++## 5. Component Dependencies++++### Required (exist in XDS OSS)++++| Dependency | Location | Purpose |++|---|---|---|++| `TablePlugin<T>` | `Table/types.ts` | Plugin interface — hook return type |++| `HeaderCellRenderProps` | `Table/types.ts` | Transform target for header cells |++| `TableRenderProps` | `Table/types.ts` | Transform target for table element |++| `XDSTableColumn<T>` | `Table/types.ts` | Column definition (passed to `transformHeaderCell`) |++| `colorVars` | `theme/tokens.stylex.ts` | Theme color tokens for handle styling |++| `spacingVars` | `theme/tokens.stylex.ts` | Theme spacing tokens |++| `stylex` | `@stylexjs/stylex` | Style definitions |++++### Used from Platform++++| Dependency | Purpose |++|---|---|++| `React.useRef` | Track drag state, store refs |++| `React.useMemo` | Stable plugin object |++| `React.useCallback` | Stable event handlers |++| `PointerEvent` | Cross-platform drag handling |++++### Not Required++++- No new components needed — the resize handle is a plain `<div>` rendered inside the existing `<th>`++- No context provider needed — drag state is local to the hook++- No external libraries — pointer events are sufficient for drag handling++++---++++## 6. Test Specification++++### 6.1 Unit Tests — Hook Behavior++++| # | Test | Assertion |++|---|---|---|++| 1 | Returns a stable `TablePlugin` object across re-renders | `plugin` reference identity does not change when config callbacks change |++| 2 | `transformHeaderCell` adds resize handle to each header cell | Rendered header cell contains a `[role="separator"]` element |++| 3 | `transformHeaderCell` applies width override when `columnWidths` has entry | `<th>` has inline `width` style matching the override value |++| 4 | `transformHeaderCell` does not override width when `columnWidths` is empty | `<th>` has no inline `width` style from the plugin |++| 5 | `transformTable` does not add `user-select: none` when not dragging | Table element has normal `user-select` |++++### 6.2 Integration Tests — Resize Interaction++++| # | Test | Assertion |++|---|---|---|++| 6 | Pointer drag resizes column | Simulate `pointerdown` → `pointermove(+100px)` → `pointerup` on handle. `onColumnResizeEnd` called with `{ columnKey, newWidth: initialWidth + 100 }` |++| 7 | Drag respects `minWidth` | Drag left past `minWidth`. `onColumnResizeEnd` reports `minWidth`, not a smaller value |++| 8 | Drag respects `maxWidth` | Drag right past `maxWidth`. `onColumnResizeEnd` reports `maxWidth` |++| 9 | Live preview during drag | During `pointermove`, the `<th>` inline style updates to reflect current drag position |++| 10 | Cancel on Escape during drag | Press `Escape` during drag. Width reverts to pre-drag value. `onColumnResizeEnd` is NOT called |++| 11 | Cancel on pointer cancel | Fire `pointercancel` during drag. Width reverts. No callback |++| 12 | Double-click calls onColumnResizeEnd (P1) | `dblclick` on handle fires callback with auto-fit width |++++### 6.3 Integration Tests — Table Rendering++++| # | Test | Assertion |++|---|---|---|++| 13 | Plugin composes with selection plugin | Table with both `useXDSTableSelection` and `useXDSTableColumnResize` renders correctly — selection checkbox column and resize handles both present |++| 14 | Proportional columns get correct initial pixel width | Render table with `proportional(2)` and `proportional(1)` columns. Start resize on the 2:1 column. Initial width captured via `getBoundingClientRect` is approximately 2/3 of table width |++| 15 | Resized column persists across re-renders | Set `columnWidths` state, trigger parent re-render. Column retains pixel width |++| 16 | Reset column width | Remove a key from `columnWidths`. Column reverts to its declared `proportional()` or `pixel()` width |++++### 6.4 Keyboard Accessibility Tests++++| # | Test | Assertion |++|---|---|---|++| 17 | Handle is focusable via Tab | `Tab` to resize handle. Element receives focus |++| 18 | Enter activates resize mode | Focus handle, press `Enter`. Resize mode is active (aria state updates) |++| 19 | Arrow keys adjust width | In resize mode, `ArrowRight` increases width by 10px. `ArrowLeft` decreases by 10px |++| 20 | Shift+Arrow for large steps | `Shift+ArrowRight` increases by 50px |++| 21 | Escape cancels keyboard resize | Activate resize, press `ArrowRight` twice, then `Escape`. Width reverts to original |++| 22 | Enter commits keyboard resize | Activate resize, press `ArrowRight` three times, press `Enter`. `onColumnResizeEnd` called with `+30px` |++++### 6.5 ARIA Tests++++| # | Test | Assertion |++|---|---|---|++| 23 | Handle has `role="separator"` | Resize handle element has `role="separator"` |++| 24 | Handle has `aria-orientation="vertical"` | Attribute present |++| 25 | Handle has `aria-valuenow` | Value matches current column width |++| 26 | Handle has `aria-label` | Label includes column header text |++++### 6.6 Edge Cases++++| # | Test | Assertion |++|---|---|---|++| 27 | No columns → no crash | Plugin with empty columns array renders without error |++| 28 | Single column resize | Table with one column can be resized (doesn't collapse table) |++| 29 | Rapid sequential resizes | Multiple quick resize operations don't produce stale state |++| 30 | Column reorder after resize | If columns prop changes (reorder), `columnWidths` keys still map correctly |++| 31 | `user-select: none` is cleaned up | After drag ends (including cancel), `user-select` is removed from table |++| 32 | Touch drag works | `pointerdown` with `pointerType: "touch"` works the same as mouse |+diff --git a/packages/core/src/Table/plugins/columnResize/index.ts b/packages/core/src/Table/plugins/columnResize/index.ts+new file mode 100644+index 000000000..8f0339203+--- /dev/null++++ b/packages/core/src/Table/plugins/columnResize/index.ts+@@ -0,0 +1,2 @@++export {useXDSTableColumnResize} from './useXDSTableColumnResize';++export type {UseXDSTableColumnResizeConfig} from './useXDSTableColumnResize';+diff --git a/packages/core/src/Table/plugins/columnResize/useXDSTableColumnResize.test.tsx b/packages/core/src/Table/plugins/columnResize/useXDSTableColumnResize.test.tsx+new file mode 100644+index 000000000..06ab1a21c+--- /dev/null++++ b/packages/core/src/Table/plugins/columnResize/useXDSTableColumnResize.test.tsx+@@ -0,0 +1,576 @@++/**++ * @file useXDSTableColumnResize.test.tsx++ * @input useXDSTableColumnResize, XDSTable, React testing utilities++ * @output Functional tests for the column resize plugin++ * @position Test file; validates resize behavior (handle, drag, keyboard, aria)++ */++++import {describe, it, expect, vi, beforeAll} from 'vitest';++import {useState} from 'react';++import {render, screen, within, fireEvent} from '@testing-library/react';++import userEvent from '@testing-library/user-event';++import {XDSTable} from '../../XDSTable';++import {useXDSTableColumnResize} from './useXDSTableColumnResize';++import {useXDSTableSelection} from '../selection/useXDSTableSelection';++import type {XDSTableColumn} from '../../types';++++// JSDOM doesn't implement pointer capture++beforeAll(() => {++ HTMLElement.prototype.setPointerCapture = vi.fn();++ HTMLElement.prototype.releasePointerCapture = vi.fn();++});++++// =============================================================================++// Test Data++// =============================================================================++++interface TestItem extends Record<string, unknown> {++ id: string;++ name: string;++ role: string;++}++++const testData: TestItem[] = [++ {id: '1', name: 'Alice', role: 'engineer'},++ {id: '2', name: 'Bob', role: 'admin'},++ {id: '3', name: 'Charlie', role: 'designer'},++];++++const testColumns: XDSTableColumn<TestItem>[] = [++ {key: 'name', header: 'Name'},++ {key: 'role', header: 'Role'},++];++++// =============================================================================++// Test Helpers++// =============================================================================++++function ResizeTable({++ columnWidths: initialWidths = {},++ onColumnResizeEnd,++ minWidth,++ maxWidth,++}: {++ columnWidths?: Record<string, number>;++ onColumnResizeEnd?: (event: {columnKey: string; newWidth: number}) => void;++ minWidth?: number;++ maxWidth?: number;++}) {++ const [columnWidths, setColumnWidths] = useState(initialWidths);++++ const resizePlugin = useXDSTableColumnResize<TestItem>({++ columnWidths,++ onColumnResizeEnd: event => {++ setColumnWidths(prev => ({...prev, [event.columnKey]: event.newWidth}));++ onColumnResizeEnd?.(event);++ },++ minWidth,++ maxWidth,++ });++++ return (++ <XDSTable++ data={testData}++ columns={testColumns}++ idKey="id"++ plugins={{resize: resizePlugin}}++ />++ );++}++++function getResizeHandles() {++ return screen.getAllByRole('separator');++}++++// =============================================================================++// 6.1 Unit Tests — Hook Behavior++// =============================================================================++++describe('useXDSTableColumnResize', () => {++ describe('hook behavior', () => {++ it('renders resize handles in each header cell', () => {++ render(<ResizeTable />);++ const handles = getResizeHandles();++ expect(handles).toHaveLength(2);++ });++++ it('applies width override when columnWidths has entry', () => {++ render(<ResizeTable columnWidths={{name: 200}} />);++ const headerRow = screen.getAllByRole('row')[0];++ const headers = within(headerRow).getAllByRole('columnheader');++ // The first header (Name) should have width and maxWidth override++ // Note: minWidth may be overridden by XDSBaseTable's column min-width logic++ expect(headers[0].style.width).toBe('200px');++ expect(headers[0].style.maxWidth).toBe('200px');++ });++++ it('does not override width when columnWidths is empty', () => {++ render(<ResizeTable />);++ const headerRow = screen.getAllByRole('row')[0];++ const headers = within(headerRow).getAllByRole('columnheader');++ // No pixel width override from the plugin++ expect(headers[0].style.width).toBe('');++ });++++ it('does not add user-select: none when not dragging', () => {++ render(<ResizeTable />);++ const table = screen.getByRole('table');++ expect(table.style.userSelect).not.toBe('none');++ });++ });++++ // ===========================================================================++ // 6.2 Integration Tests — Resize Interaction++ // ===========================================================================++++ describe('resize interaction', () => {++ it('calls onColumnResizeEnd after pointer drag', () => {++ const onResize = vi.fn();++ render(++ <ResizeTable++ columnWidths={{name: 200}}++ onColumnResizeEnd={onResize}++ />,++ );++ const handle = getResizeHandles()[0];++++ fireEvent.pointerDown(handle, {clientX: 200, pointerId: 1});++ fireEvent.pointerMove(handle, {clientX: 300, pointerId: 1});++ fireEvent.pointerUp(handle, {clientX: 300, pointerId: 1});++++ expect(onResize).toHaveBeenCalledWith({++ columnKey: 'name',++ newWidth: 300,++ });++ });++++ it('respects minWidth during drag', () => {++ const onResize = vi.fn();++ render(++ <ResizeTable++ columnWidths={{name: 100}}++ onColumnResizeEnd={onResize}++ minWidth={80}++ />,++ );++ const handle = getResizeHandles()[0];++++ // Drag left past minWidth++ fireEvent.pointerDown(handle, {clientX: 200, pointerId: 1});++ fireEvent.pointerMove(handle, {clientX: 50, pointerId: 1});++ fireEvent.pointerUp(handle, {clientX: 50, pointerId: 1});++++ expect(onResize).toHaveBeenCalledWith({++ columnKey: 'name',++ newWidth: 80,++ });++ });++++ it('respects maxWidth during drag', () => {++ const onResize = vi.fn();++ render(++ <ResizeTable++ columnWidths={{name: 200}}++ onColumnResizeEnd={onResize}++ maxWidth={300}++ />,++ );++ const handle = getResizeHandles()[0];++++ fireEvent.pointerDown(handle, {clientX: 200, pointerId: 1});++ fireEvent.pointerMove(handle, {clientX: 600, pointerId: 1});++ fireEvent.pointerUp(handle, {clientX: 600, pointerId: 1});++++ expect(onResize).toHaveBeenCalledWith({++ columnKey: 'name',++ newWidth: 300,++ });++ });++++ it('does not call onColumnResizeEnd on Escape during drag', () => {++ const onResize = vi.fn();++ render(++ <ResizeTable++ columnWidths={{name: 200}}++ onColumnResizeEnd={onResize}++ />,++ );++ const handle = getResizeHandles()[0];++++ fireEvent.pointerDown(handle, {clientX: 200, pointerId: 1});++ fireEvent.pointerMove(handle, {clientX: 300, pointerId: 1});++ // Cancel via pointerCancel++ fireEvent.pointerCancel(handle, {pointerId: 1});++++ expect(onResize).not.toHaveBeenCalled();++ });++ });++++ // ===========================================================================++ // 6.3 Integration Tests — Table Rendering++ // ===========================================================================++++ describe('table rendering', () => {++ it('composes with selection plugin', () => {++ function ComposedTable() {++ const [columnWidths, setColumnWidths] = useState<++ Record<string, number>++ >({});++++ const resizePlugin = useXDSTableColumnResize<TestItem>({++ columnWidths,++ onColumnResizeEnd: ({columnKey, newWidth}) => {++ setColumnWidths(prev => ({...prev, [columnKey]: newWidth}));++ },++ });++++ const selectionPlugin = useXDSTableSelection<TestItem>({++ getIsItemSelected: () => false,++ onSelectItem: () => {},++ onSelectAll: () => {},++ getIsAllSelected: () => false,++ });++++ return (++ <XDSTable++ data={testData}++ columns={testColumns}++ idKey="id"++ plugins={{resize: resizePlugin, selection: selectionPlugin}}++ />++ );++ }++++ render(<ComposedTable />);++++ // Both selection checkboxes and resize handles should be present++ const checkboxes = screen.getAllByRole('checkbox');++ expect(checkboxes.length).toBeGreaterThan(0);++++ const handles = getResizeHandles();++ expect(handles).toHaveLength(2);++ });++++ it('resized column persists across re-renders', () => {++ const {rerender} = render(++ <ResizeTable columnWidths={{name: 250}} />,++ );++ const headerRow = screen.getAllByRole('row')[0];++ const headers = within(headerRow).getAllByRole('columnheader');++ expect(headers[0].style.width).toBe('250px');++++ // Trigger re-render++ rerender(<ResizeTable columnWidths={{name: 250}} />);++ const headersAfter = within(++ screen.getAllByRole('row')[0],++ ).getAllByRole('columnheader');++ expect(headersAfter[0].style.width).toBe('250px');++ });++++ it('resets column width when key removed from columnWidths', () => {++ // Use a controlled component that passes columnWidths directly++ function ControlledResizeTable({++ columnWidths,++ }: {++ columnWidths: Record<string, number>;++ }) {++ const resizePlugin = useXDSTableColumnResize<TestItem>({++ columnWidths,++ });++ return (++ <XDSTable++ data={testData}++ columns={testColumns}++ idKey="id"++ plugins={{resize: resizePlugin}}++ />++ );++ }++++ const {rerender} = render(++ <ControlledResizeTable columnWidths={{name: 250}} />,++ );++ const headers = within(++ screen.getAllByRole('row')[0],++ ).getAllByRole('columnheader');++ expect(headers[0].style.width).toBe('250px');++++ rerender(<ControlledResizeTable columnWidths={{}} />);++ const headersAfter = within(++ screen.getAllByRole('row')[0],++ ).getAllByRole('columnheader');++ expect(headersAfter[0].style.width).toBe('');++ });++ });++++ // ===========================================================================++ // 6.4 Keyboard Accessibility Tests++ // ===========================================================================++++ describe('keyboard accessibility', () => {++ it('handle is focusable via Tab', async () => {++ const user = userEvent.setup();++ render(<ResizeTable />);++ const handle = getResizeHandles()[0];++++ await user.tab();++ // Tab may land on the handle (or other focusable elements first)++ // Explicitly focus the handle++ handle.focus();++ expect(document.activeElement).toBe(handle);++ });++++ it('Enter activates resize mode and locks width', () => {++ render(<ResizeTable columnWidths={{name: 200}} />);++ const handle = getResizeHandles()[0];++ handle.focus();++++ fireEvent.keyDown(handle, {key: 'Enter'});++ // After activation, the th should have width locked as inline style++ const headers = within(++ screen.getAllByRole('row')[0],++ ).getAllByRole('columnheader');++ expect(headers[0].style.width).toBe('200px');++ });++++ it('ArrowRight increases width by 10px in resize mode', () => {++ const onResize = vi.fn();++ render(++ <ResizeTable++ columnWidths={{name: 200}}++ onColumnResizeEnd={onResize}++ />,++ );++ const handle = getResizeHandles()[0];++ handle.focus();++++ // Activate++ fireEvent.keyDown(handle, {key: 'Enter'});++ // Arrow right++ fireEvent.keyDown(handle, {key: 'ArrowRight'});++ // Commit++ fireEvent.keyDown(handle, {key: 'Enter'});++++ expect(onResize).toHaveBeenCalledWith({++ columnKey: 'name',++ newWidth: 210,++ });++ });++++ it('ArrowLeft decreases width by 10px', () => {++ const onResize = vi.fn();++ render(++ <ResizeTable++ columnWidths={{name: 200}}++ onColumnResizeEnd={onResize}++ />,++ );++ const handle = getResizeHandles()[0];++ handle.focus();++++ fireEvent.keyDown(handle, {key: 'Enter'});++ fireEvent.keyDown(handle, {key: 'ArrowLeft'});++ fireEvent.keyDown(handle, {key: 'Enter'});++++ expect(onResize).toHaveBeenCalledWith({++ columnKey: 'name',++ newWidth: 190,++ });++ });++++ it('Shift+ArrowRight increases by 50px', () => {++ const onResize = vi.fn();++ render(++ <ResizeTable++ columnWidths={{name: 200}}++ onColumnResizeEnd={onResize}++ />,++ );++ const handle = getResizeHandles()[0];++ handle.focus();++++ fireEvent.keyDown(handle, {key: 'Enter'});++ fireEvent.keyDown(handle, {key: 'ArrowRight', shiftKey: true});++ fireEvent.keyDown(handle, {key: 'Enter'});++++ expect(onResize).toHaveBeenCalledWith({++ columnKey: 'name',++ newWidth: 250,++ });++ });++++ it('Escape cancels keyboard resize and reverts width', () => {++ const onResize = vi.fn();++ render(++ <ResizeTable++ columnWidths={{name: 200}}++ onColumnResizeEnd={onResize}++ />,++ );++ const handle = getResizeHandles()[0];++ handle.focus();++++ fireEvent.keyDown(handle, {key: 'Enter'});++ fireEvent.keyDown(handle, {key: 'ArrowRight'});++ fireEvent.keyDown(handle, {key: 'ArrowRight'});++ fireEvent.keyDown(handle, {key: 'Escape'});++++ expect(onResize).not.toHaveBeenCalled();++++ // Width should revert — the th should have the original 200px++ const headers = within(++ screen.getAllByRole('row')[0],++ ).getAllByRole('columnheader');++ expect(headers[0].style.width).toBe('200px');++ });++++ it('Enter commits keyboard resize with accumulated changes', () => {++ const onResize = vi.fn();++ render(++ <ResizeTable++ columnWidths={{name: 200}}++ onColumnResizeEnd={onResize}++ />,++ );++ const handle = getResizeHandles()[0];++ handle.focus();++++ fireEvent.keyDown(handle, {key: 'Enter'});++ fireEvent.keyDown(handle, {key: 'ArrowRight'});++ fireEvent.keyDown(handle, {key: 'ArrowRight'});++ fireEvent.keyDown(handle, {key: 'ArrowRight'});++ fireEvent.keyDown(handle, {key: 'Enter'});++++ expect(onResize).toHaveBeenCalledWith({++ columnKey: 'name',++ newWidth: 230,++ });++ });++ });++++ // ===========================================================================++ // 6.5 ARIA Tests++ // ===========================================================================++++ describe('ARIA attributes', () => {++ it('handle has role="separator"', () => {++ render(<ResizeTable />);++ const handles = getResizeHandles();++ expect(handles[0]).toHaveAttribute('role', 'separator');++ });++++ it('handle has aria-orientation="vertical"', () => {++ render(<ResizeTable />);++ const handle = getResizeHandles()[0];++ expect(handle).toHaveAttribute('aria-orientation', 'vertical');++ });++++ it('handle has aria-valuenow matching column width', () => {++ render(<ResizeTable columnWidths={{name: 200}} />);++ const handle = getResizeHandles()[0];++ expect(handle).toHaveAttribute('aria-valuenow', '200');++ });++++ it('handle has aria-label with column header text', () => {++ render(<ResizeTable />);++ const handle = getResizeHandles()[0];++ expect(handle).toHaveAttribute('aria-label', 'Resize column Name');++ });++++ it('handle has aria-valuemin', () => {++ render(<ResizeTable minWidth={80} />);++ const handle = getResizeHandles()[0];++ expect(handle).toHaveAttribute('aria-valuemin', '80');++ });++++ it('handle has aria-valuemax when finite', () => {++ render(<ResizeTable maxWidth={500} />);++ const handle = getResizeHandles()[0];++ expect(handle).toHaveAttribute('aria-valuemax', '500');++ });++ });++++ // ===========================================================================++ // 6.6 Edge Cases++ // ===========================================================================++++ describe('edge cases', () => {++ it('no columns → no crash', () => {++ function EmptyTable() {++ const resizePlugin = useXDSTableColumnResize<TestItem>({});++ return (++ <XDSTable++ data={[]}++ columns={[]}++ plugins={{resize: resizePlugin}}++ />++ );++ }++++ expect(() => render(<EmptyTable />)).not.toThrow();++ });++++ it('single column resize works', () => {++ const singleColumn: XDSTableColumn<TestItem>[] = [++ {key: 'name', header: 'Name'},++ ];++++ function SingleColumnTable() {++ const resizePlugin = useXDSTableColumnResize<TestItem>({++ columnWidths: {name: 300},++ });++ return (++ <XDSTable++ data={testData}++ columns={singleColumn}++ idKey="id"++ plugins={{resize: resizePlugin}}++ />++ );++ }++++ render(<SingleColumnTable />);++ const handles = getResizeHandles();++ expect(handles).toHaveLength(1);++ });++++ it('column reorder after resize — widths map correctly', () => {++ function ReorderTable() {++ const [cols, setCols] = useState(testColumns);++ const resizePlugin = useXDSTableColumnResize<TestItem>({++ columnWidths: {name: 200, role: 150},++ });++ return (++ <div>++ <button onClick={() => setCols([...cols].reverse())}>++ Reorder++ </button>++ <XDSTable++ data={testData}++ columns={cols}++ idKey="id"++ plugins={{resize: resizePlugin}}++ />++ </div>++ );++ }++++ render(<ReorderTable />);++ let headers = within(screen.getAllByRole('row')[0]).getAllByRole(++ 'columnheader',++ );++ expect(headers[0].style.width).toBe('200px');++ expect(headers[1].style.width).toBe('150px');++++ // Reorder columns++ fireEvent.click(screen.getByText('Reorder'));++++ headers = within(screen.getAllByRole('row')[0]).getAllByRole(++ 'columnheader',++ );++ // After reorder, Role is first, Name is second++ expect(headers[0].style.width).toBe('150px');++ expect(headers[1].style.width).toBe('200px');++ });++ });++});+diff --git a/packages/core/src/Table/plugins/columnResize/useXDSTableColumnResize.tsx b/packages/core/src/Table/plugins/columnResize/useXDSTableColumnResize.tsx+new file mode 100644+index 000000000..02b957c47+--- /dev/null++++ b/packages/core/src/Table/plugins/columnResize/useXDSTableColumnResize.tsx+@@ -0,0 +1,445 @@++'use client';++++/**++ * @file useXDSTableColumnResize.tsx++ * @input React, types, StyleX, theme tokens++ * @output Exports useXDSTableColumnResize hook and UseXDSTableColumnResizeConfig type++ * @position Column resize plugin; consumed by XDSTable via plugins prop++ *++ * SYNC: When modified, update these files to stay in sync:++ * - /packages/core/src/Table/Table.doc.mjs (resize documentation)++ * - /packages/core/src/Table/index.ts (exports)++ */++++import {useRef, useMemo, useCallback, type ReactNode} from 'react';++import * as stylex from '@stylexjs/stylex';++import {colorVars} from '../../../theme/tokens.stylex';++import type {++ TablePlugin,++ TableRenderProps,++ HeaderCellRenderProps,++ XDSTableColumn,++} from '../../types';++++// =============================================================================++// Config Type++// =============================================================================++++export interface UseXDSTableColumnResizeConfig {++ /**++ * Column width overrides from resize operations.++ * Keys are column `key` strings. Values are pixel widths.++ * When a column key is present here, it overrides the column's++ * declared `width` (proportional or pixel).++ *++ * Controlled: consumer owns this state and persists as needed.++ */++ columnWidths?: Record<string, number>;++++ /**++ * Called when a resize operation completes (pointerup / Enter key).++ * Consumer updates their `columnWidths` state here.++ */++ onColumnResizeEnd?: (event: {columnKey: string; newWidth: number}) => void;++++ /**++ * Minimum column width in pixels during resize.++ * @default 50++ */++ minWidth?: number;++++ /**++ * Maximum column width in pixels during resize.++ * @default Infinity (no max)++ */++ maxWidth?: number;++}++++// =============================================================================++// Constants++// =============================================================================++++const DEFAULT_MIN_WIDTH = 50;++const KEYBOARD_STEP = 10;++const KEYBOARD_LARGE_STEP = 50;++++// =============================================================================++// Styles++// =============================================================================++++const handleStyles = stylex.create({++ base: {++ position: 'absolute',++ insetInlineEnd: '-3px',++ top: 0,++ bottom: 0,++ width: '6px',++ cursor: 'ew-resize',++ zIndex: 1,++ touchAction: 'none',++ userSelect: 'none',++ '::after': {++ content: '""',++ position: 'absolute',++ top: 0,++ bottom: 0,++ insetInlineStart: '2.5px',++ width: '1px',++ backgroundColor: colorVars['--color-accent'],++ opacity: {++ default: 0,++ ':hover': 1,++ ':focus-visible': 1,++ },++ transition: 'opacity 150ms ease',++ },++ '@media (pointer: coarse)': {++ width: '16px',++ insetInlineEnd: '-8px',++ },++ },++});++++const headerCellRelative = stylex.create({++ base: {++ position: 'relative',++ overflow: 'visible',++ },++});++++// =============================================================================++// Drag State (ref-based, not React state — avoids re-renders during drag)++// =============================================================================++++interface DragState {++ columnKey: string;++ startX: number;++ initialWidth: number;++ thElement: HTMLTableCellElement;++}++++// =============================================================================++// Resize Handle Component++// =============================================================================++++interface ResizeHandleProps {++ columnKey: string;++ columnHeader: ReactNode;++ currentWidth: number | undefined;++ minWidth: number;++ maxWidth: number;++ configRef: React.RefObject<UseXDSTableColumnResizeConfig>;++ dragStateRef: React.RefObject<DragState | null>;++ isDraggingRef: React.RefObject<boolean>;++ tableRef: React.RefObject<HTMLTableElement | null>;++}++++function ResizeHandle({++ columnKey,++ columnHeader,++ currentWidth,++ minWidth,++ maxWidth,++ configRef,++ dragStateRef,++ isDraggingRef,++ tableRef,++}: ResizeHandleProps) {++ const keyboardActiveRef = useRef(false);++ const keyboardInitialWidthRef = useRef(0);++++ const resolveCurrentWidth = useCallback(++ (handle: HTMLElement): number => {++ if (currentWidth != null) return currentWidth;++ const th = handle.closest('th');++ if (th) return th.getBoundingClientRect().width;++ return minWidth;++ },++ [currentWidth, minWidth],++ );++++ const clamp = useCallback(++ (value: number) => Math.max(minWidth, Math.min(maxWidth, value)),++ [minWidth, maxWidth],++ );++++ const applyWidth = useCallback(++ (th: HTMLTableCellElement, width: number) => {++ const clamped = clamp(width);++ const px = `${clamped}px`;++ th.style.width = px;++ th.style.minWidth = px;++ th.style.maxWidth = px;++ },++ [clamp],++ );++++ const clearWidth = useCallback(++ (th: HTMLTableCellElement, key: string) => {++ const override = configRef.current.columnWidths?.[key];++ if (override != null) {++ const px = `${override}px`;++ th.style.width = px;++ th.style.minWidth = px;++ th.style.maxWidth = px;++ } else {++ th.style.width = '';++ th.style.minWidth = '';++ th.style.maxWidth = '';++ }++ },++ [configRef],++ );++++ const setTableDragging = useCallback(++ (dragging: boolean) => {++ const table = tableRef.current;++ if (table) {++ table.style.userSelect = dragging ? 'none' : '';++ }++ },++ [tableRef],++ );++++ const getRTLMultiplier = useCallback((el: HTMLElement): number => {++ const dir = getComputedStyle(el).direction;++ return dir === 'rtl' ? -1 : 1;++ }, []);++++ const handlePointerDown = useCallback(++ (e: React.PointerEvent<HTMLDivElement>) => {++ e.preventDefault();++ e.stopPropagation();++++ const handle = e.currentTarget;++ const th = handle.closest('th') as HTMLTableCellElement | null;++ if (!th) return;++++ const table = th.closest('table');++ if (table) tableRef.current = table;++++ const initialWidth = resolveCurrentWidth(handle);++ if (handle.setPointerCapture) handle.setPointerCapture(e.pointerId);++++ dragStateRef.current = {columnKey, startX: e.clientX, initialWidth, thElement: th};++ isDraggingRef.current = true;++ handle.setAttribute('data-resizing', 'true');++++ applyWidth(th, initialWidth);++ setTableDragging(true);++ },++ [columnKey, resolveCurrentWidth, dragStateRef, isDraggingRef, tableRef, applyWidth, setTableDragging],++ );++++ const handlePointerMove = useCallback(++ (e: React.PointerEvent<HTMLDivElement>) => {++ const drag = dragStateRef.current;++ if (!drag || !isDraggingRef.current) return;++++ const delta = (e.clientX - drag.startX) * getRTLMultiplier(drag.thElement);++ applyWidth(drag.thElement, drag.initialWidth + delta);++ },++ [dragStateRef, isDraggingRef, getRTLMultiplier, applyWidth],++ );++++ const handlePointerUp = useCallback(++ (e: React.PointerEvent<HTMLDivElement>) => {++ const drag = dragStateRef.current;++ if (!drag || !isDraggingRef.current) return;++++ e.currentTarget.removeAttribute('data-resizing');++ const delta = (e.clientX - drag.startX) * getRTLMultiplier(drag.thElement);++ const newWidth = clamp(drag.initialWidth + delta);++++ isDraggingRef.current = false;++ dragStateRef.current = null;++ setTableDragging(false);++++ configRef.current.onColumnResizeEnd?.({columnKey, newWidth});++ },++ [columnKey, dragStateRef, isDraggingRef, getRTLMultiplier, clamp, setTableDragging, configRef],++ );++++ const handlePointerCancel = useCallback(++ () => {++ const drag = dragStateRef.current;++ if (!drag || !isDraggingRef.current) return;++++ // Revert to width before drag++ clearWidth(drag.thElement, drag.columnKey);++++ isDraggingRef.current = false;++ dragStateRef.current = null;++ setTableDragging(false);++ },++ [dragStateRef, isDraggingRef, clearWidth, setTableDragging],++ );++++ const handleKeyDown = useCallback(++ (e: React.KeyboardEvent<HTMLDivElement>) => {++ const handle = e.currentTarget;++ const th = handle.closest('th') as HTMLTableCellElement | null;++ if (!th) return;++++ // Activate keyboard resize mode++ if (!keyboardActiveRef.current) {++ if (e.key === 'Enter' || e.key === ' ') {++ e.preventDefault();++ keyboardActiveRef.current = true;++ keyboardInitialWidthRef.current = resolveCurrentWidth(handle);++ handle.setAttribute('data-resizing', 'true');++++ const table = th.closest('table');++ if (table) tableRef.current = table;++++ applyWidth(th, keyboardInitialWidthRef.current);++ return;++ }++ return;++ }++++ const step = e.shiftKey ? KEYBOARD_LARGE_STEP : KEYBOARD_STEP;++ const rtl = getRTLMultiplier(th);++++ switch (e.key) {++ case 'ArrowRight': {++ e.preventDefault();++ const cur = parseFloat(th.style.width) || keyboardInitialWidthRef.current;++ applyWidth(th, cur + step * rtl);++ break;++ }++ case 'ArrowLeft': {++ e.preventDefault();++ const cur = parseFloat(th.style.width) || keyboardInitialWidthRef.current;++ applyWidth(th, cur - step * rtl);++ break;++ }++ case 'Escape':++ e.preventDefault();++ clearWidth(th, columnKey);++ keyboardActiveRef.current = false;++ handle.removeAttribute('data-resizing');++ break;++ case 'Enter': {++ e.preventDefault();++ const finalWidth = parseFloat(th.style.width) || keyboardInitialWidthRef.current;++ keyboardActiveRef.current = false;++ handle.removeAttribute('data-resizing');++ configRef.current.onColumnResizeEnd?.({++ columnKey,++ newWidth: clamp(finalWidth),++ });++ break;++ }++ }++ },++ [columnKey, resolveCurrentWidth, getRTLMultiplier, clamp, applyWidth, clearWidth, configRef, tableRef],++ );++++ const ariaLabel =++ typeof columnHeader === 'string'++ ? `Resize column ${columnHeader}`++ : `Resize column ${columnKey}`;++++ return (++ <div++ role="separator"++ aria-orientation="vertical"++ aria-valuenow={currentWidth ?? undefined}++ aria-valuemin={minWidth}++ aria-valuemax={maxWidth === Infinity ? undefined : maxWidth}++ aria-label={ariaLabel}++ tabIndex={0}++ onPointerDown={handlePointerDown}++ onPointerMove={handlePointerMove}++ onPointerUp={handlePointerUp}++ onPointerCancel={handlePointerCancel}++ onKeyDown={handleKeyDown}++ {...stylex.props(handleStyles.base)}++ />++ );++}++++// =============================================================================++// Hook++// =============================================================================++++export function useXDSTableColumnResize<++ T extends Record<string, unknown>,++>(config: UseXDSTableColumnResizeConfig): TablePlugin<T> {++ const configRef = useRef(config);++ configRef.current = config;++++ const dragStateRef = useRef<DragState | null>(null);++ const isDraggingRef = useRef(false);++ const tableRef = useRef<HTMLTableElement | null>(null);++++ const minWidth = config.minWidth ?? DEFAULT_MIN_WIDTH;++ const maxWidth = config.maxWidth ?? Infinity;++ const columnWidths = config.columnWidths;++++ return useMemo(++ (): TablePlugin<T> => ({++ transformHeaderCell(++ props: HeaderCellRenderProps,++ column: XDSTableColumn<T>,++ ): HeaderCellRenderProps {++ const overrideWidth = columnWidths?.[column.key];++++ const widthStyle: React.CSSProperties | undefined =++ overrideWidth != null++ ? {++ width: `${overrideWidth}px`,++ minWidth: `${overrideWidth}px`,++ maxWidth: `${overrideWidth}px`,++ }++ : undefined;++++ const existingStyle = props.htmlProps.style as++ | React.CSSProperties++ | undefined;++ const mergedStyle = widthStyle++ ? existingStyle++ ? {...existingStyle, ...widthStyle}++ : widthStyle++ : existingStyle;++++ const existingChildren = (props.htmlProps as {children?: ReactNode}).children;++ const handle = (++ <ResizeHandle++ key={`resize-${column.key}`}++ columnKey={column.key}++ columnHeader={column.header ?? column.key}++ currentWidth={overrideWidth}++ minWidth={minWidth}++ maxWidth={maxWidth}++ configRef={configRef}++ dragStateRef={dragStateRef}++ isDraggingRef={isDraggingRef}++ tableRef={tableRef}++ />++ );++++ return {++ ...props,++ htmlProps: {++ ...props.htmlProps,++ style: mergedStyle,++ children: (++ <>++ {existingChildren}++ {handle}++ </>++ ),++ },++ styles: [...props.styles, headerCellRelative.base],++ };++ },++++ transformTable(props: TableRenderProps): TableRenderProps {++ return props;++ },++ }),++ [columnWidths, minWidth, maxWidth],++ );++}+--+2.31.1+diff --git a/apps/storybook/stories/TableColumnResize.stories.tsx b/apps/storybook/stories/TableColumnResize.stories.tsxnew file mode 100644index 0000000000..e72b3fc4b9--- /dev/null+++ b/apps/storybook/stories/TableColumnResize.stories.tsx@@ -0,0 +1,291 @@+import {useState} from 'react';+import type {Meta, StoryObj} from '@storybook/react';+import {+ XDSTable,+ useXDSTableColumnResize,+ useXDSTableSelection,+ useXDSTableSelectionState,+ proportional,+ pixel,+} 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/ColumnResize',+ tags: ['autodocs'],+};++export default meta;+type Story = StoryObj;++export const Default: Story = {+ render: () => {+ const [columnWidths, setColumnWidths] = useState<Record<string, number>>(+ {},+ );++ const resizePlugin = useXDSTableColumnResize<User>({+ columnWidths,+ columns,+ onColumnResizeEnd: updates => {+ setColumnWidths(prev => ({...prev, ...updates}));+ },+ });++ return (+ <div style={{maxWidth: 600}}>+ <p style={{marginBottom: 8, fontSize: 14, color: '#666'}}>+ Drag the right edge of any column header to resize. The last+ proportional column has no handle — it flexes to fill remaining space.+ </p>+ <XDSTable+ data={users}+ columns={columns}+ idKey="id"+ plugins={{columnResize: resizePlugin}}+ />+ </div>+ );+ },+};++export const WithMinMaxConstraints: Story = {+ render: () => {+ const [columnWidths, setColumnWidths] = useState<Record<string, number>>(+ {},+ );++ const resizePlugin = useXDSTableColumnResize<User>({+ columnWidths,+ onColumnResizeEnd: updates => {+ setColumnWidths(prev => ({...prev, ...updates}));+ },+ columns,+ minWidth: 80,+ maxWidth: 300,+ });++ return (+ <div style={{maxWidth: 600}}>+ <p style={{marginBottom: 8, fontSize: 14, color: '#666'}}>+ Columns are constrained between 80px and 300px.+ </p>+ <XDSTable+ data={users}+ columns={columns}+ idKey="id"+ plugins={{columnResize: resizePlugin}}+ />+ </div>+ );+ },+};++export const PersistingWidths: Story = {+ render: () => {+ const [columnWidths, setColumnWidths] = useState<Record<string, number>>(+ {},+ );++ const resizePlugin = useXDSTableColumnResize<User>({+ columnWidths,+ columns,+ onColumnResizeEnd: updates => {+ setColumnWidths(prev => ({...prev, ...updates}));+ },+ });++ return (+ <div style={{maxWidth: 600}}>+ <p style={{marginBottom: 8, fontSize: 14, color: '#666'}}>+ Current widths:{' '}+ {Object.keys(columnWidths).length > 0+ ? Object.entries(columnWidths)+ .map(([key, width]) => `${key}: ${width}px`)+ .join(', ')+ : 'none set (resize a column to see)'}+ </p>+ <button+ onClick={() => setColumnWidths({})}+ style={{marginBottom: 8, fontSize: 14}}>+ Reset all widths+ </button>+ <XDSTable+ data={users}+ columns={columns}+ idKey="id"+ plugins={{columnResize: resizePlugin}}+ />+ </div>+ );+ },+};++export const KeyboardResize: Story = {+ render: () => {+ const [columnWidths, setColumnWidths] = useState<Record<string, number>>(+ {},+ );++ const resizePlugin = useXDSTableColumnResize<User>({+ columnWidths,+ columns,+ onColumnResizeEnd: updates => {+ setColumnWidths(prev => ({...prev, ...updates}));+ },+ });++ return (+ <div style={{maxWidth: 600}}>+ <p style={{marginBottom: 8, fontSize: 14, color: '#666'}}>+ Tab to a resize handle, press Enter to activate, use Arrow keys to+ resize (Shift for larger steps), Enter to commit, Escape to cancel.+ </p>+ <XDSTable+ data={users}+ columns={columns}+ idKey="id"+ plugins={{columnResize: resizePlugin}}+ />+ </div>+ );+ },+};++export const WithSelectionAndResize: Story = {+ render: () => {+ const [selectedKeys, setSelectedKeys] = useState<Set<string>>(new Set());+ const [columnWidths, setColumnWidths] = useState<Record<string, number>>(+ {},+ );++ const {selectionConfig} = useXDSTableSelectionState<User>({+ data: users,+ idKey: 'id',+ selectedKeys,+ setSelectedKeys,+ });+ const selectionPlugin = useXDSTableSelection<User>(selectionConfig);++ const resizePlugin = useXDSTableColumnResize<User>({+ columnWidths,+ columns,+ onColumnResizeEnd: updates => {+ setColumnWidths(prev => ({...prev, ...updates}));+ },+ });++ return (+ <div style={{maxWidth: 600}}>+ <p style={{marginBottom: 8, fontSize: 14, color: '#666'}}>+ Selection and column resize plugins composed together. Selected:{' '}+ {selectedKeys.size} of {users.length}+ </p>+ <XDSTable+ data={users}+ columns={columns}+ idKey="id"+ plugins={{selection: selectionPlugin, columnResize: resizePlugin}}+ />+ </div>+ );+ },+};++const pixelColumns: XDSTableColumn<User>[] = [+ {key: 'name', header: 'Name', width: pixel(200)},+ {key: 'email', header: 'Email', width: pixel(250)},+ {key: 'role', header: 'Role', width: pixel(150)},+];++export const AllPixelColumns: Story = {+ render: () => {+ const [columnWidths, setColumnWidths] = useState<Record<string, number>>(+ {},+ );++ const resizePlugin = useXDSTableColumnResize<User>({+ columnWidths,+ columns: pixelColumns,+ onColumnResizeEnd: updates => {+ setColumnWidths(prev => ({...prev, ...updates}));+ },+ });++ return (+ <div style={{maxWidth: 600}}>+ <p style={{marginBottom: 8, fontSize: 14, color: '#666'}}>+ All columns are pixel-width. Every column gets a resize handle,+ including the last one. Min width defaults to the column's+ declared pixel value.+ </p>+ <XDSTable+ data={users}+ columns={pixelColumns}+ idKey="id"+ plugins={{columnResize: resizePlugin}}+ />+ </div>+ );+ },+};diff --git a/packages/core/src/Table/XDSBaseTable.tsx b/packages/core/src/Table/XDSBaseTable.tsxindex 6a1b332d4d..84defc2d9b 100644--- a/packages/core/src/Table/XDSBaseTable.tsx+++ b/packages/core/src/Table/XDSBaseTable.tsx@@ -282,7 +282,7 @@ function XDSBaseTableInner<T extends Record<string, unknown>>({plugins,p => p.transformHeaderCell,{- htmlProps: {},+ htmlProps: {'data-column-key': col.key},styles: [],content: headerContent,} as HeaderCellRenderProps,@@ -298,7 +298,7 @@ function XDSBaseTableInner<T extends Record<string, unknown>>({| undefined;const mergedHtmlProps = {...cellRenderProps.htmlProps,- style: existingStyle ? {...existingStyle, ...widthStyle} : widthStyle,+ style: existingStyle ? {...widthStyle, ...existingStyle} : widthStyle,};// Resolve header content from slots — plugins write to named slotsdiff --git a/packages/core/src/Table/index.ts b/packages/core/src/Table/index.tsindex b45d00cc02..95cc9685b9 100644--- a/packages/core/src/Table/index.ts+++ b/packages/core/src/Table/index.ts@@ -20,6 +20,7 @@ export {useXDSTableSelectionState} from './plugins/selection';export {useXDSTableSortable} from './plugins/sortable';export {useXDSTablePagination} from './plugins/pagination';export {useXDSTableColumnSettings} from './plugins/columnSettings';+export {useXDSTableColumnResize} from './plugins/columnResize';export {useXDSBaseTablePlugins} from './useXDSBaseTablePlugins';export {proportional,@@ -74,3 +75,4 @@ export type {UseXDSTableColumnSettingsReturn,XDSColumnSettingsOption,} from './plugins/columnSettings';+export type {UseXDSTableColumnResizeConfig} from './plugins/columnResize';diff --git a/packages/core/src/Table/plugins/columnResize/index.ts b/packages/core/src/Table/plugins/columnResize/index.tsnew file mode 100644index 0000000000..8f03392039--- /dev/null+++ b/packages/core/src/Table/plugins/columnResize/index.ts@@ -0,0 +1,2 @@+export {useXDSTableColumnResize} from './useXDSTableColumnResize';+export type {UseXDSTableColumnResizeConfig} from './useXDSTableColumnResize';diff --git a/packages/core/src/Table/plugins/columnResize/useXDSTableColumnResize.test.tsx b/packages/core/src/Table/plugins/columnResize/useXDSTableColumnResize.test.tsxnew file mode 100644index 0000000000..e4f01482cb--- /dev/null+++ b/packages/core/src/Table/plugins/columnResize/useXDSTableColumnResize.test.tsx@@ -0,0 +1,759 @@+/**+ * @file useXDSTableColumnResize.test.tsx+ * @input useXDSTableColumnResize, XDSTable, React testing utilities+ * @output Functional tests for the column resize plugin+ * @position Test file; validates resize behavior (handle, drag, keyboard, aria)+ */++import {describe, it, expect, vi, beforeAll} from 'vitest';+import {useState} from 'react';+import {render, screen, within, fireEvent} from '@testing-library/react';+import userEvent from '@testing-library/user-event';+import {XDSTable} from '../../XDSTable';+import {useXDSTableColumnResize} from './useXDSTableColumnResize';+import {useXDSTableSelection} from '../selection/useXDSTableSelection';+import {proportional, pixel} from '../../columnUtils';+import type {XDSTableColumn} from '../../types';++// JSDOM doesn't implement pointer capture+beforeAll(() => {+ HTMLElement.prototype.setPointerCapture = vi.fn();+ HTMLElement.prototype.releasePointerCapture = vi.fn();+});++// =============================================================================+// Test Data+// =============================================================================++interface TestItem extends Record<string, unknown> {+ id: string;+ name: string;+ role: string;+}++const testData: TestItem[] = [+ {id: '1', name: 'Alice', role: 'engineer'},+ {id: '2', name: 'Bob', role: 'admin'},+ {id: '3', name: 'Charlie', role: 'designer'},+];++const testColumns: XDSTableColumn<TestItem>[] = [+ {key: 'name', header: 'Name'},+ {key: 'role', header: 'Role'},+];++/** Pixel columns — both columns get handles and resize directly */+const pixelColumns: XDSTableColumn<TestItem>[] = [+ {key: 'name', header: 'Name', width: pixel(200)},+ {key: 'role', header: 'Role', width: pixel(200)},+];++// =============================================================================+// Test Helpers+// =============================================================================++function ResizeTable({+ columnWidths: initialWidths = {},+ onColumnResizeEnd,+ minWidth,+ maxWidth,+ columns: columnsProp = testColumns,+}: {+ columnWidths?: Record<string, number>;+ onColumnResizeEnd?: (event: {columnKey: string; newWidth: number}) => void; // spy receives single entry+ minWidth?: number;+ maxWidth?: number;+ columns?: XDSTableColumn<TestItem>[];+}) {+ const [columnWidths, setColumnWidths] = useState(initialWidths);++ const resizePlugin = useXDSTableColumnResize<TestItem>({+ columnWidths,+ onColumnResizeEnd: updates => {+ setColumnWidths(prev => ({...prev, ...updates}));+ // Forward the first update entry to the single-column spy for test assertions+ const [[columnKey, newWidth]] = Object.entries(updates);+ onColumnResizeEnd?.({columnKey, newWidth});+ },+ minWidth,+ maxWidth,+ columns: columnsProp,+ });++ return (+ <XDSTable+ data={testData}+ columns={columnsProp}+ idKey="id"+ plugins={{resize: resizePlugin}}+ />+ );+}++function getResizeHandles() {+ return screen.getAllByRole('separator');+}++// =============================================================================+// 6.1 Unit Tests — Hook Behavior+// =============================================================================++describe('useXDSTableColumnResize', () => {+ describe('hook behavior', () => {+ it('renders resize handles in each header cell (pixel columns)', () => {+ render(<ResizeTable columns={pixelColumns} />);+ const handles = getResizeHandles();+ expect(handles).toHaveLength(2);+ });++ it('applies width override when columnWidths has entry', () => {+ render(<ResizeTable columnWidths={{name: 200}} />);+ const headerRow = screen.getAllByRole('row')[0];+ const headers = within(headerRow).getAllByRole('columnheader');+ // The first header (Name) should have width and maxWidth override+ // Note: minWidth may be overridden by XDSBaseTable's column min-width logic+ expect(headers[0].style.width).toBe('200px');+ expect(headers[0].style.maxWidth).toBe('200px');+ });++ it('does not override width when columnWidths is empty', () => {+ render(<ResizeTable />);+ const headerRow = screen.getAllByRole('row')[0];+ const headers = within(headerRow).getAllByRole('columnheader');+ // No pixel override from the plugin — XDSBaseTable sets a percentage width+ // for table-layout:fixed distribution, so width is not empty+ expect(headers[0].style.width).not.toBe('');+ expect(headers[0].style.width).not.toContain('px');+ });++ it('does not add user-select: none when not dragging', () => {+ render(<ResizeTable />);+ const table = screen.getByRole('table');+ expect(table.style.userSelect).not.toBe('none');+ });+ });++ // ===========================================================================+ // 6.2 Integration Tests — Resize Interaction+ // ===========================================================================++ describe('resize interaction', () => {+ it('calls onColumnResizeEnd after pointer drag', () => {+ const onResize = vi.fn();+ render(+ <ResizeTable+ columns={pixelColumns}+ columnWidths={{name: 200}}+ onColumnResizeEnd={onResize}+ />,+ );+ const handle = getResizeHandles()[0];++ fireEvent.pointerDown(handle, {clientX: 200, pointerId: 1});+ window.dispatchEvent(+ new PointerEvent('pointermove', {+ clientX: 300,+ pointerId: 1,+ bubbles: true,+ }),+ );+ window.dispatchEvent(+ new PointerEvent('pointerup', {+ clientX: 300,+ pointerId: 1,+ bubbles: true,+ }),+ );++ expect(onResize).toHaveBeenCalledWith({+ columnKey: 'name',+ newWidth: 300,+ });+ });++ it('respects minWidth during drag', () => {+ const onResize = vi.fn();+ render(+ <ResizeTable+ columns={pixelColumns}+ columnWidths={{name: 100}}+ onColumnResizeEnd={onResize}+ minWidth={80}+ />,+ );+ const handle = getResizeHandles()[0];++ // Drag left past minWidth+ fireEvent.pointerDown(handle, {clientX: 200, pointerId: 1});+ window.dispatchEvent(+ new PointerEvent('pointermove', {+ clientX: 50,+ pointerId: 1,+ bubbles: true,+ }),+ );+ window.dispatchEvent(+ new PointerEvent('pointerup', {+ clientX: 50,+ pointerId: 1,+ bubbles: true,+ }),+ );++ expect(onResize).toHaveBeenCalledWith({+ columnKey: 'name',+ newWidth: 80,+ });+ });++ it('respects maxWidth during drag', () => {+ const onResize = vi.fn();+ render(+ <ResizeTable+ columns={pixelColumns}+ columnWidths={{name: 200}}+ onColumnResizeEnd={onResize}+ maxWidth={300}+ />,+ );+ const handle = getResizeHandles()[0];++ fireEvent.pointerDown(handle, {clientX: 200, pointerId: 1});+ window.dispatchEvent(+ new PointerEvent('pointermove', {+ clientX: 600,+ pointerId: 1,+ bubbles: true,+ }),+ );+ window.dispatchEvent(+ new PointerEvent('pointerup', {+ clientX: 600,+ pointerId: 1,+ bubbles: true,+ }),+ );++ expect(onResize).toHaveBeenCalledWith({+ columnKey: 'name',+ newWidth: 300,+ });+ });++ it('does not call onColumnResizeEnd on Escape during drag', () => {+ const onResize = vi.fn();+ render(+ <ResizeTable columnWidths={{name: 200}} onColumnResizeEnd={onResize} />,+ );+ const handle = getResizeHandles()[0];++ fireEvent.pointerDown(handle, {clientX: 200, pointerId: 1});+ window.dispatchEvent(+ new PointerEvent('pointermove', {+ clientX: 300,+ pointerId: 1,+ bubbles: true,+ }),+ );+ // Cancel via pointerCancel+ window.dispatchEvent(+ new PointerEvent('pointercancel', {pointerId: 1, bubbles: true}),+ );++ expect(onResize).not.toHaveBeenCalled();+ });+ });++ // ===========================================================================+ // 6.3 Integration Tests — Table Rendering+ // ===========================================================================++ describe('table rendering', () => {+ it('composes with selection plugin', () => {+ function ComposedTable() {+ const [columnWidths, setColumnWidths] = useState<+ Record<string, number>+ >({});++ const resizePlugin = useXDSTableColumnResize<TestItem>({+ columnWidths,+ onColumnResizeEnd: ({columnKey, newWidth}) => {+ setColumnWidths(prev => ({...prev, [columnKey]: newWidth}));+ },+ });++ const selectionPlugin = useXDSTableSelection<TestItem>({+ getIsItemSelected: () => false,+ onSelectItem: () => {},+ onSelectAll: () => {},+ getIsAllSelected: () => false,+ });++ return (+ <XDSTable+ data={testData}+ columns={testColumns}+ idKey="id"+ plugins={{resize: resizePlugin, selection: selectionPlugin}}+ />+ );+ }++ render(<ComposedTable />);++ // Both selection checkboxes and resize handles should be present+ const checkboxes = screen.getAllByRole('checkbox');+ expect(checkboxes.length).toBeGreaterThan(0);++ const handles = getResizeHandles();+ expect(handles).toHaveLength(2);+ });++ it('resized column persists across re-renders', () => {+ const {rerender} = render(<ResizeTable columnWidths={{name: 250}} />);+ const headerRow = screen.getAllByRole('row')[0];+ const headers = within(headerRow).getAllByRole('columnheader');+ expect(headers[0].style.width).toBe('250px');++ // Trigger re-render+ rerender(<ResizeTable columnWidths={{name: 250}} />);+ const headersAfter = within(screen.getAllByRole('row')[0]).getAllByRole(+ 'columnheader',+ );+ expect(headersAfter[0].style.width).toBe('250px');+ });++ it('resets column width when key removed from columnWidths', () => {+ // Use a controlled component that passes columnWidths directly+ function ControlledResizeTable({+ columnWidths,+ }: {+ columnWidths: Record<string, number>;+ }) {+ const resizePlugin = useXDSTableColumnResize<TestItem>({+ columnWidths,+ });+ return (+ <XDSTable+ data={testData}+ columns={testColumns}+ idKey="id"+ plugins={{resize: resizePlugin}}+ />+ );+ }++ const {rerender} = render(+ <ControlledResizeTable columnWidths={{name: 250}} />,+ );+ const headers = within(screen.getAllByRole('row')[0]).getAllByRole(+ 'columnheader',+ );+ expect(headers[0].style.width).toBe('250px');++ rerender(<ControlledResizeTable columnWidths={{}} />);+ const headersAfter = within(screen.getAllByRole('row')[0]).getAllByRole(+ 'columnheader',+ );+ // Plugin override removed — falls back to XDSBaseTable's percentage width+ expect(headersAfter[0].style.width).not.toContain('px');+ });+ });++ // ===========================================================================+ // 6.4 Keyboard Accessibility Tests+ // ===========================================================================++ describe('keyboard accessibility', () => {+ it('handle is focusable via Tab', async () => {+ const user = userEvent.setup();+ render(<ResizeTable />);+ const handle = getResizeHandles()[0];++ await user.tab();+ // Explicitly focus the handle+ handle.focus();+ expect(document.activeElement).toBe(handle);+ });++ it('ArrowRight resizes immediately on focus (no activation step)', () => {+ const onResize = vi.fn();+ render(+ <ResizeTable+ columns={pixelColumns}+ columnWidths={{name: 200}}+ onColumnResizeEnd={onResize}+ />,+ );+ const handle = getResizeHandles()[0];+ handle.focus();++ // Arrow right commits immediately — no Enter activation needed+ fireEvent.keyDown(handle, {key: 'ArrowRight'});++ expect(onResize).toHaveBeenCalledWith({+ columnKey: 'name',+ newWidth: 210,+ });+ });++ it('ArrowLeft decreases width by 10px immediately', () => {+ const smallPixelColumns: XDSTableColumn<TestItem>[] = [+ {key: 'name', header: 'Name', width: pixel(100)},+ {key: 'role', header: 'Role', width: pixel(100)},+ ];+ const onResize = vi.fn();+ render(+ <ResizeTable+ columns={smallPixelColumns}+ columnWidths={{name: 200}}+ onColumnResizeEnd={onResize}+ />,+ );+ const handle = getResizeHandles()[0];+ handle.focus();++ fireEvent.keyDown(handle, {key: 'ArrowLeft'});++ expect(onResize).toHaveBeenCalledWith({+ columnKey: 'name',+ newWidth: 190,+ });+ });++ it('Shift+ArrowRight increases by 50px', () => {+ const onResize = vi.fn();+ render(+ <ResizeTable+ columns={pixelColumns}+ columnWidths={{name: 200}}+ onColumnResizeEnd={onResize}+ />,+ );+ const handle = getResizeHandles()[0];+ handle.focus();++ fireEvent.keyDown(handle, {key: 'ArrowRight', shiftKey: true});++ expect(onResize).toHaveBeenCalledWith({+ columnKey: 'name',+ newWidth: 250,+ });+ });++ it('multiple arrow presses accumulate', () => {+ const onResize = vi.fn();+ render(+ <ResizeTable+ columns={pixelColumns}+ columnWidths={{name: 200}}+ onColumnResizeEnd={onResize}+ />,+ );+ const handle = getResizeHandles()[0];+ handle.focus();++ fireEvent.keyDown(handle, {key: 'ArrowRight'});+ fireEvent.keyDown(handle, {key: 'ArrowRight'});+ fireEvent.keyDown(handle, {key: 'ArrowRight'});++ // Each press commits independently, building on the previous+ expect(onResize).toHaveBeenCalledTimes(3);+ expect(onResize).toHaveBeenLastCalledWith({+ columnKey: 'name',+ newWidth: 230, // 200 + 10 + 10 + 10+ });+ });++ it('Home key jumps to minimum width', () => {+ const onResize = vi.fn();+ render(+ <ResizeTable+ columns={pixelColumns}+ columnWidths={{name: 300}}+ onColumnResizeEnd={onResize}+ />,+ );+ const handle = getResizeHandles()[0];+ handle.focus();++ fireEvent.keyDown(handle, {key: 'Home'});++ expect(onResize).toHaveBeenCalledWith({+ columnKey: 'name',+ newWidth: 200, // pixel(200) column min+ });+ });++ it('End key jumps to maximum width when finite', () => {+ const onResize = vi.fn();+ render(+ <ResizeTable+ columns={pixelColumns}+ columnWidths={{name: 200}}+ onColumnResizeEnd={onResize}+ maxWidth={500}+ />,+ );+ const handle = getResizeHandles()[0];+ handle.focus();++ fireEvent.keyDown(handle, {key: 'End'});++ expect(onResize).toHaveBeenCalledWith({+ columnKey: 'name',+ newWidth: 500,+ });+ });++ it('End key does nothing when maxWidth is Infinity', () => {+ const onResize = vi.fn();+ render(+ <ResizeTable+ columns={pixelColumns}+ columnWidths={{name: 200}}+ onColumnResizeEnd={onResize}+ />,+ );+ const handle = getResizeHandles()[0];+ handle.focus();++ fireEvent.keyDown(handle, {key: 'End'});++ expect(onResize).not.toHaveBeenCalled();+ });+ });++ // ===========================================================================+ // 6.5 ARIA Tests+ // ===========================================================================++ describe('ARIA attributes', () => {+ it('handle has role="separator"', () => {+ render(<ResizeTable />);+ const handles = getResizeHandles();+ expect(handles[0]).toHaveAttribute('role', 'separator');+ });++ it('handle has aria-orientation="vertical"', () => {+ render(<ResizeTable />);+ const handle = getResizeHandles()[0];+ expect(handle).toHaveAttribute('aria-orientation', 'vertical');+ });++ it('handle has aria-valuenow matching column width', () => {+ render(<ResizeTable columnWidths={{name: 200}} />);+ const handle = getResizeHandles()[0];+ expect(handle).toHaveAttribute('aria-valuenow', '200');+ });++ it('handle has aria-label with column header text', () => {+ render(<ResizeTable />);+ const handle = getResizeHandles()[0];+ expect(handle).toHaveAttribute('aria-label', 'Resize column Name');+ });++ it('handle has aria-valuemin', () => {+ render(<ResizeTable minWidth={80} />);+ const handle = getResizeHandles()[0];+ expect(handle).toHaveAttribute('aria-valuemin', '80');+ });++ it('handle has aria-valuemax when finite', () => {+ render(<ResizeTable maxWidth={500} />);+ const handle = getResizeHandles()[0];+ expect(handle).toHaveAttribute('aria-valuemax', '500');+ });+ });++ // ===========================================================================+ // 6.6 Edge Cases+ // ===========================================================================++ describe('edge cases', () => {+ it('no columns → no crash', () => {+ function EmptyTable() {+ const resizePlugin = useXDSTableColumnResize<TestItem>({});+ return (+ <XDSTable data={[]} columns={[]} plugins={{resize: resizePlugin}} />+ );+ }++ expect(() => render(<EmptyTable />)).not.toThrow();+ });++ it('single column resize works', () => {+ const singleColumn: XDSTableColumn<TestItem>[] = [+ {key: 'name', header: 'Name'},+ ];++ function SingleColumnTable() {+ const resizePlugin = useXDSTableColumnResize<TestItem>({+ columnWidths: {name: 300},+ });+ return (+ <XDSTable+ data={testData}+ columns={singleColumn}+ idKey="id"+ plugins={{resize: resizePlugin}}+ />+ );+ }++ render(<SingleColumnTable />);+ const handles = getResizeHandles();+ expect(handles).toHaveLength(1);+ });++ it('column reorder after resize — widths map correctly', () => {+ function ReorderTable() {+ const [cols, setCols] = useState(testColumns);+ const resizePlugin = useXDSTableColumnResize<TestItem>({+ columnWidths: {name: 200, role: 150},+ });+ return (+ <div>+ <button onClick={() => setCols([...cols].reverse())}>+ Reorder+ </button>+ <XDSTable+ data={testData}+ columns={cols}+ idKey="id"+ plugins={{resize: resizePlugin}}+ />+ </div>+ );+ }++ render(<ReorderTable />);+ let headers = within(screen.getAllByRole('row')[0]).getAllByRole(+ 'columnheader',+ );+ expect(headers[0].style.width).toBe('200px');+ expect(headers[1].style.width).toBe('150px');++ // Reorder columns+ fireEvent.click(screen.getByText('Reorder'));++ headers = within(screen.getAllByRole('row')[0]).getAllByRole(+ 'columnheader',+ );+ // After reorder, Role is first, Name is second+ expect(headers[0].style.width).toBe('150px');+ expect(headers[1].style.width).toBe('200px');+ });+ });++ // ===========================================================================+ // 6.7 Per-Column Min Width+ // ===========================================================================++ describe('per-column min width', () => {+ it('uses proportional column minWidth as resize minimum', () => {+ const columnsWithMinWidth: XDSTableColumn<TestItem>[] = [+ {key: 'name', header: 'Name', width: proportional(1, {minWidth: 150})},+ {key: 'role', header: 'Role', width: pixel(200)},+ ];++ render(<ResizeTable columns={columnsWithMinWidth} />);+ const handle = getResizeHandles()[0];+ // The handle's aria-valuemin should reflect the column's minWidth+ expect(handle).toHaveAttribute('aria-valuemin', '150');+ });++ it('uses pixel column value as resize minimum', () => {+ const columnsWithPixel: XDSTableColumn<TestItem>[] = [+ {key: 'name', header: 'Name', width: pixel(180)},+ {key: 'role', header: 'Role', width: pixel(200)},+ ];++ render(<ResizeTable columns={columnsWithPixel} />);+ const handle = getResizeHandles()[0];+ expect(handle).toHaveAttribute('aria-valuemin', '180');+ });++ it('global minWidth overrides per-column minimum', () => {+ const columnsWithMinWidth: XDSTableColumn<TestItem>[] = [+ {key: 'name', header: 'Name', width: proportional(1, {minWidth: 150})},+ {key: 'role', header: 'Role'},+ ];++ render(<ResizeTable columns={columnsWithMinWidth} minWidth={60} />);+ const handle = getResizeHandles()[0];+ // Global override wins+ expect(handle).toHaveAttribute('aria-valuemin', '60');+ });++ it('defaults to DEFAULT_MIN_COLUMN_WIDTH (120) for proportional without explicit minWidth', () => {+ const defaultColumns: XDSTableColumn<TestItem>[] = [+ {key: 'name', header: 'Name', width: proportional(1)},+ {key: 'role', header: 'Role', width: pixel(200)},+ ];++ render(<ResizeTable columns={defaultColumns} />);+ const handle = getResizeHandles()[0];+ // proportional() helper defaults minWidth to 120+ expect(handle).toHaveAttribute('aria-valuemin', '120');+ });+ });++ // ===========================================================================+ // 6.8 Proportional-Preserving Resize+ // ===========================================================================++ describe('proportional-preserving resize', () => {+ it('does not render resize handle on last proportional column', () => {+ // Default columns have no explicit width → proportional+ // The last column (role) should have no handle+ render(<ResizeTable />);+ const handles = getResizeHandles();+ // Only the first column should get a handle (proportional with a neighbor)+ // The last proportional column has no handle+ expect(handles).toHaveLength(1);+ });++ it('renders resize handle on last column if it is pixel', () => {+ const columnsWithPixelLast: XDSTableColumn<TestItem>[] = [+ {key: 'name', header: 'Name'},+ {key: 'role', header: 'Role', width: pixel(200)},+ ];++ render(<ResizeTable columns={columnsWithPixelLast} />);+ const handles = getResizeHandles();+ // Both columns get handles — last is pixel, not proportional+ expect(handles).toHaveLength(2);+ });++ it('all pixel columns get handles including last', () => {+ const allPixel: XDSTableColumn<TestItem>[] = [+ {key: 'name', header: 'Name', width: pixel(200)},+ {key: 'role', header: 'Role', width: pixel(200)},+ ];++ render(<ResizeTable columns={allPixel} />);+ const handles = getResizeHandles();+ expect(handles).toHaveLength(2);+ });++ it('without columns config, all columns get handles (backward compat)', () => {+ // Don't pass columns to the plugin — falls back to old behavior+ function LegacyResizeTable() {+ const resizePlugin = useXDSTableColumnResize<TestItem>({});+ return (+ <XDSTable+ data={testData}+ columns={testColumns}+ idKey="id"+ plugins={{resize: resizePlugin}}+ />+ );+ }++ render(<LegacyResizeTable />);+ const handles = getResizeHandles();+ expect(handles).toHaveLength(2);+ });+ });+});diff --git a/packages/core/src/Table/plugins/columnResize/useXDSTableColumnResize.tsx b/packages/core/src/Table/plugins/columnResize/useXDSTableColumnResize.tsxnew file mode 100644index 0000000000..d9eeee30e1--- /dev/null+++ b/packages/core/src/Table/plugins/columnResize/useXDSTableColumnResize.tsx@@ -0,0 +1,743 @@+'use client';++/**+ * @file useXDSTableColumnResize.tsx+ * @input React, types, StyleX, theme tokens+ * @output Exports useXDSTableColumnResize hook and UseXDSTableColumnResizeConfig type+ * @position Column resize plugin; consumed by XDSTable via plugins prop+ *+ * SYNC: When modified, update these files to stay in sync:+ * - /packages/core/src/Table/Table.doc.mjs (resize documentation)+ * - /packages/core/src/Table/index.ts (exports)+ */++import {useRef, useMemo, useCallback, type ReactNode} from 'react';+import * as stylex from '@stylexjs/stylex';+import {colorVars} from '../../../theme/tokens.stylex';+import type {+ TablePlugin,+ HeaderCellRenderProps,+ XDSTableColumn,+ ColumnWidth,+} from '../../types';+import {DEFAULT_MIN_COLUMN_WIDTH} from '../../columnUtils';++// =============================================================================+// Config Type+// =============================================================================++export interface UseXDSTableColumnResizeConfig {+ /**+ * Column width overrides from resize operations.+ * Keys are column `key` strings. Values are pixel widths.+ * When a column key is present here, it overrides the column's+ * declared `width` (proportional or pixel).+ *+ * Controlled: consumer owns this state and persists as needed.+ */+ columnWidths?: Record<string, number>;++ /**+ * Called when a resize operation completes (pointerup / Enter key).+ * Consumer updates their `columnWidths` state here.+ */+ /**+ * Called when a resize operation completes (pointerup / Enter key).+ * Receives a map of ALL column keys that changed width — the resized column+ * plus any other columns that were committed to pixel widths to prevent+ * layout shift. Consumer should merge these into their columnWidths state.+ */+ onColumnResizeEnd?: (updates: Record<string, number>) => void;++ /**+ * Global minimum column width in pixels during resize.+ * Overrides per-column defaults when set.+ * @default undefined (uses column-specific minimum)+ */+ minWidth?: number;++ /**+ * Global maximum column width in pixels during resize.+ * @default Infinity (no max)+ */+ maxWidth?: number;++ /**+ * Column definitions — needed to derive per-column min widths+ * and detect proportional vs pixel columns for last-column behavior.+ *+ * When proportional columns are detected, the resize handle+ * automatically adjusts the neighboring column instead of the+ * proportional column itself. The last proportional column has+ * no resize handle (it flexes to fill remaining space).+ *+ * When not provided, all columns are treated as pixel columns+ * and the global minWidth fallback (50px) is used.+ */+ columns?: XDSTableColumn<Record<string, unknown>>[];+}++// =============================================================================+// Constants+// =============================================================================++const FALLBACK_MIN_WIDTH = 50;+const KEYBOARD_STEP = 10;+const KEYBOARD_LARGE_STEP = 50;++// =============================================================================+// Width Helpers+// =============================================================================++/**+ * Derive the effective minimum width for a column based on its width config.+ * - Proportional columns: use their declared minWidth (default 120px)+ * - Pixel columns: use their declared value (you set 200px, min is 200px)+ * - No width / unknown: use DEFAULT_MIN_COLUMN_WIDTH+ *+ * A global override (from config.minWidth) takes precedence when set.+ */+function resolveColumnMinWidth(+ colWidth: ColumnWidth | undefined,+ globalOverride: number | undefined,+): number {+ if (globalOverride != null) return globalOverride;+ if (!colWidth) return DEFAULT_MIN_COLUMN_WIDTH;+ if (colWidth.type === 'proportional') {+ return colWidth.minWidth ?? DEFAULT_MIN_COLUMN_WIDTH;+ }+ if (colWidth.type === 'pixel') {+ return colWidth.value;+ }+ return FALLBACK_MIN_WIDTH;+}++/**+ * Check whether a column is proportional (or has no explicit width,+ * which defaults to proportional(1) in XDSBaseTable).+ */+function isProportionalColumn(colWidth: ColumnWidth | undefined): boolean {+ return !colWidth || colWidth.type === 'proportional';+}++// =============================================================================+// Central width computation+// =============================================================================++/**+ * Given a drag delta, compute pixel widths for ALL columns.+ * Only the target column (or neighbor in proportional mode) changes;+ * all others stay at their snapshot values. The last column gets the+ * remainder (tableWidth - sum of others).+ *+ * Every width is clamped to its column's min. This is the single source+ * of truth for column widths during drag — no other code path should+ * compute widths independently.+ */+function computeColumnWidths(drag: DragState, delta: number): number[] {+ const {snapshots, resizeIndex, neighborIndex, tableWidth} = drag;+ const widths = snapshots.map(s => s.initialWidth);+ const lastIndex = snapshots.length - 1;++ if (neighborIndex != null) {+ // Proportional-preserving: adjust the neighbor column inversely.+ const neighbor = snapshots[neighborIndex];+ const self = snapshots[resizeIndex];++ // Clamp: neighbor can't go below its min+ const maxDelta = neighbor.initialWidth - neighbor.minWidth;+ // Clamp: self can't go below its min+ const minDelta = self.minWidth - self.initialWidth;+ const clampedDelta = Math.max(minDelta, Math.min(delta, maxDelta));++ widths[neighborIndex] = neighbor.initialWidth - clampedDelta;+ widths[resizeIndex] = self.initialWidth + clampedDelta;+ } else {+ // Direct resize: clamp to min/max+ const self = snapshots[resizeIndex];+ const newWidth = Math.min(+ self.maxWidth,+ Math.max(self.minWidth, self.initialWidth + delta),+ );+ widths[resizeIndex] = newWidth;+ }++ // Last column = remainder (table can grow horizontally if needed)+ if (lastIndex >= 0 && tableWidth > 0) {+ const sumOthers = widths.reduce(+ (sum, w, i) => (i === lastIndex ? sum : sum + w),+ 0,+ );+ widths[lastIndex] = Math.max(+ snapshots[lastIndex].minWidth,+ tableWidth - sumOthers,+ );+ }++ return widths;+}++// =============================================================================+// Styles+// =============================================================================++const handleStyles = stylex.create({+ base: {+ position: 'absolute',+ // Keep entirely inside the <th> — extending outside gets clipped by the+ // adjacent <th>'s overflow:hidden.+ insetInlineEnd: 0,+ top: 0,+ bottom: 0,+ // Wide transparent hit area; the right 1px becomes the visible indicator.+ width: '8px',+ cursor: 'ew-resize',+ zIndex: 1,+ touchAction: 'none',+ userSelect: 'none',+ // The rightmost 1px acts as the resize indicator line.+ // Use a right border rather than ::after so it reliably renders+ // without needing pseudo-element content/dimensions.+ borderInlineEndWidth: '1px',+ borderInlineEndStyle: 'solid',+ borderInlineEndColor: {+ default: 'transparent',+ ':hover': colorVars['--color-accent'],+ ':focus-visible': colorVars['--color-accent'],+ },+ transition: 'border-color 150ms ease',+ '@media (pointer: coarse)': {+ width: '20px',+ },+ },+});++const headerCellRelative = stylex.create({+ base: {+ position: 'relative',+ overflow: 'visible',+ },+});++// =============================================================================+// Drag State (ref-based, not React state — avoids re-renders during drag)+// =============================================================================++interface ColumnSnapshot {+ key: string;+ th: HTMLTableCellElement;+ initialWidth: number;+ minWidth: number;+ maxWidth: number;+}++interface DragState {+ columnKey: string;+ startX: number;+ /** Index of the column being resized in the snapshots array */+ resizeIndex: number;+ /** When resizing a proportional column, we resize the next column instead */+ neighborIndex: number | null;+ /** Snapshot of ALL columns at drag start */+ snapshots: ColumnSnapshot[];+ /** Table width at drag start — last column fills remainder */+ tableWidth: number;+}++// =============================================================================+// Resize Handle Component+// =============================================================================++interface ResizeHandleProps {+ columnKey: string;+ columnHeader: ReactNode;+ currentWidth: number | undefined;+ minWidth: number;+ maxWidth: number;+ /** For proportional-preserving: the neighbor column to resize instead */+ neighborKey: string | null;+ neighborMinWidth: number;+ configRef: React.RefObject<UseXDSTableColumnResizeConfig>;+ dragStateRef: React.RefObject<DragState | null>;+ isDraggingRef: React.RefObject<boolean>;+ tableRef: React.RefObject<HTMLTableElement | null>;+}++function ResizeHandle({+ columnKey,+ columnHeader,+ currentWidth,+ minWidth,+ maxWidth,+ neighborKey,+ neighborMinWidth,+ configRef,+ dragStateRef,+ isDraggingRef,+ tableRef,+}: ResizeHandleProps) {+ /**+ * Resolve the effective maximum width. When no explicit maxWidth is set,+ * use the table's current width as a natural ceiling — no single column+ * should exceed the table's bounds.+ */+ const clamp = useCallback(+ (value: number, min: number = minWidth, max: number = maxWidth) =>+ Math.max(min, Math.min(max, value)),+ [minWidth, maxWidth],+ );++ const applyWidth = useCallback(+ (th: HTMLTableCellElement, width: number, min?: number, max?: number) => {+ const clamped = clamp(width, min, max);+ const px = `${clamped}px`;+ th.style.width = px;+ th.style.minWidth = px;+ th.style.maxWidth = px;+ },+ [clamp],+ );++ const setTableDragging = useCallback(+ (dragging: boolean) => {+ const table = tableRef.current;+ if (table) {+ table.style.userSelect = dragging ? 'none' : '';+ }+ },+ [tableRef],+ );++ const getRTLMultiplier = useCallback((el: HTMLElement): number => {+ const dir = getComputedStyle(el).direction;+ return dir === 'rtl' ? -1 : 1;+ }, []);++ /**+ * Resolve the neighbor <th> element from the handle's <th>.+ * The neighbor is the next sibling <th> in DOM order.+ */+ const resolveNeighborTh = useCallback(+ (th: HTMLTableCellElement): HTMLTableCellElement | null => {+ if (!neighborKey) return null;+ const row = th.parentElement;+ if (!row) return null;+ return row.querySelector<HTMLTableCellElement>(+ `th[data-column-key="${neighborKey}"]`,+ );+ },+ [neighborKey],+ );++ const handlePointerDown = useCallback(+ (e: React.PointerEvent<HTMLDivElement>) => {+ e.preventDefault();+ e.stopPropagation();++ const handle = e.currentTarget;+ const th = handle.closest('th') as HTMLTableCellElement | null;+ if (!th) return;++ const table = th.closest('table');+ if (table) tableRef.current = table;++ const headerRow = th.parentElement;+ if (!headerRow) return;++ const cols = configRef.current.columns;+ const colsByKey = new Map(cols?.map(c => [c.key, c]));+ const allThs = Array.from(+ headerRow.querySelectorAll<HTMLTableCellElement>(':scope > th'),+ );+ const tableWidth = tableRef.current?.getBoundingClientRect().width ?? 0;++ // Snapshot only resizable columns — skip non-resizable synthetic+ // columns (e.g. selection checkbox) so they don't shift indices+ // or participate in width redistribution during drag.+ const currentWidths = configRef.current.columnWidths ?? {};+ const snapshots: ColumnSnapshot[] = [];+ for (const cell of allThs) {+ const key = cell.getAttribute('data-column-key');+ if (!key) continue;+ const col = colsByKey.get(key);+ if (col?.resizable === false) continue;+ const rendered = cell.getBoundingClientRect().width;+ const override = currentWidths[key];+ snapshots.push({+ key,+ th: cell,+ initialWidth: override ?? (rendered > 0 ? rendered : 0),+ minWidth: col+ ? resolveColumnMinWidth(col.width, configRef.current.minWidth)+ : minWidth,+ maxWidth: configRef.current.maxWidth ?? Infinity,+ });+ }++ // Find our column and neighbor in the snapshots by key+ const resizeIndex = snapshots.findIndex(s => s.key === columnKey);+ let neighborIdx: number | null = null;+ if (neighborKey) {+ const idx = snapshots.findIndex(s => s.key === neighborKey);+ if (idx >= 0) neighborIdx = idx;+ }++ const drag: DragState = {+ columnKey,+ startX: e.clientX,+ resizeIndex,+ neighborIndex: neighborIdx,+ snapshots,+ tableWidth,+ };+ dragStateRef.current = drag;+ isDraggingRef.current = true;+ handle.setAttribute('data-resizing', 'true');++ // Apply initial snapshot widths to ALL columns (freezes layout)+ const initialWidths = computeColumnWidths(drag, 0);+ snapshots.forEach((s, i) => {+ const px = `${initialWidths[i]}px`;+ s.th.style.width = px;+ s.th.style.minWidth = px;+ s.th.style.maxWidth = px;+ });+ setTableDragging(true);++ // --- Window-level listeners ---++ function onMove(ev: PointerEvent) {+ const d = dragStateRef.current;+ if (!d || !isDraggingRef.current) return;++ const rawDelta =+ (ev.clientX - d.startX) *+ getRTLMultiplier(d.snapshots[d.resizeIndex].th);+ const widths = computeColumnWidths(d, rawDelta);++ d.snapshots.forEach((s, i) => {+ const px = `${widths[i]}px`;+ s.th.style.width = px;+ s.th.style.minWidth = px;+ s.th.style.maxWidth = px;+ });+ }++ function onUp(ev: PointerEvent) {+ cleanup();+ const d = dragStateRef.current;+ if (!d || !isDraggingRef.current) return;++ handle.removeAttribute('data-resizing');+ isDraggingRef.current = false;+ dragStateRef.current = null;+ setTableDragging(false);++ const rawDelta =+ (ev.clientX - d.startX) *+ getRTLMultiplier(d.snapshots[d.resizeIndex].th);+ const widths = computeColumnWidths(d, rawDelta);++ // Build updates map — all columns except the last+ const updates: Record<string, number> = {};+ const lastIndex = d.snapshots.length - 1;+ d.snapshots.forEach((s, i) => {+ if (i === lastIndex) return;+ updates[s.key] = widths[i];+ });++ // Don't clear inline styles — leave them in place so there's no flash+ // between clearing and React re-rendering with the new columnWidths.+ // The plugin's transformHeaderCell will set the same pixel values on+ // the next render, seamlessly replacing these inline styles.++ if (Object.keys(updates).length > 0) {+ configRef.current.onColumnResizeEnd?.(updates);+ }+ }++ function onCancel() {+ cleanup();+ const d = dragStateRef.current;+ if (!d || !isDraggingRef.current) return;++ handle.removeAttribute('data-resizing');+ isDraggingRef.current = false;+ dragStateRef.current = null;+ setTableDragging(false);++ // Restore to pre-drag state by clearing all inline styles+ d.snapshots.forEach(s => {+ s.th.style.width = '';+ s.th.style.minWidth = '';+ s.th.style.maxWidth = '';+ });+ }++ function cleanup() {+ window.removeEventListener('pointermove', onMove);+ window.removeEventListener('pointerup', onUp);+ window.removeEventListener('pointercancel', onCancel);+ }++ window.addEventListener('pointermove', onMove);+ window.addEventListener('pointerup', onUp);+ window.addEventListener('pointercancel', onCancel);+ },+ [+ columnKey,+ neighborKey,+ minWidth,+ resolveNeighborTh,+ getRTLMultiplier,+ dragStateRef,+ isDraggingRef,+ tableRef,+ configRef,+ setTableDragging,+ ],+ );++ /**+ * Keyboard resize per WAI-ARIA Window Splitter pattern.+ * Arrow keys resize immediately on focus — no activation step.+ * Each keypress commits the new width directly.+ * Home/End jump to min/max width.+ */+ const handleKeyDown = useCallback(+ (e: React.KeyboardEvent<HTMLDivElement>) => {+ const handle = e.currentTarget;+ const th = handle.closest('th') as HTMLTableCellElement | null;+ if (!th) return;++ const table = th.closest('table');+ if (table) tableRef.current = table;++ const step = e.shiftKey ? KEYBOARD_LARGE_STEP : KEYBOARD_STEP;+ const rtl = getRTLMultiplier(th);++ switch (e.key) {+ case 'ArrowRight':+ case 'ArrowLeft': {+ e.preventDefault();+ const direction = e.key === 'ArrowRight' ? 1 : -1;+ const delta = step * direction * rtl;++ if (neighborKey) {+ // Proportional-preserving: adjust neighbor inversely, clamped so+ // it never drops below its min (which also prevents this column+ // from growing into the last column's reserved minimum space).+ const nTh = resolveNeighborTh(th);+ if (nTh) {+ const curNeighbor = nTh.getBoundingClientRect().width;+ const newWidth = Math.max(neighborMinWidth, curNeighbor - delta);+ applyWidth(nTh, newWidth, neighborMinWidth);+ configRef.current.onColumnResizeEnd?.({[neighborKey]: newWidth});+ }+ } else {+ const curWidth = currentWidth ?? th.getBoundingClientRect().width;+ const newWidth = clamp(curWidth + delta);+ applyWidth(th, newWidth);+ configRef.current.onColumnResizeEnd?.({[columnKey]: newWidth});+ }+ break;+ }+ case 'Home': {+ e.preventDefault();+ if (neighborKey) {+ const nTh = resolveNeighborTh(th);+ if (nTh) {+ applyWidth(nTh, neighborMinWidth, neighborMinWidth);+ configRef.current.onColumnResizeEnd?.({+ [neighborKey]: neighborMinWidth,+ });+ }+ } else {+ applyWidth(th, minWidth);+ configRef.current.onColumnResizeEnd?.({[columnKey]: minWidth});+ }+ break;+ }+ case 'End': {+ e.preventDefault();+ if (maxWidth !== Infinity) {+ applyWidth(th, maxWidth);+ configRef.current.onColumnResizeEnd?.({[columnKey]: maxWidth});+ }+ break;+ }+ }+ },+ [+ columnKey,+ currentWidth,+ neighborKey,+ neighborMinWidth,+ resolveNeighborTh,+ getRTLMultiplier,+ clamp,+ minWidth,+ maxWidth,+ applyWidth,+ configRef,+ tableRef,+ ],+ );++ const ariaLabel =+ typeof columnHeader === 'string'+ ? `Resize column ${columnHeader}`+ : `Resize column ${columnKey}`;++ return (+ <div+ role="separator"+ aria-orientation="vertical"+ aria-valuenow={currentWidth ?? undefined}+ aria-valuemin={minWidth}+ aria-valuemax={maxWidth === Infinity ? undefined : maxWidth}+ aria-label={ariaLabel}+ tabIndex={0}+ onPointerDown={handlePointerDown}+ onKeyDown={handleKeyDown}+ {...stylex.props(handleStyles.base)}+ />+ );+}++// =============================================================================+// Hook+// =============================================================================++export function useXDSTableColumnResize<T extends Record<string, unknown>>(+ config: UseXDSTableColumnResizeConfig,+): TablePlugin<T> {+ const configRef = useRef(config);+ configRef.current = config;++ const dragStateRef = useRef<DragState | null>(null);+ const isDraggingRef = useRef(false);+ const tableRef = useRef<HTMLTableElement | null>(null);++ const globalMinWidth = config.minWidth;+ const maxWidth = config.maxWidth ?? Infinity;+ const columnWidths = config.columnWidths;+ const columns = config.columns;++ // Central list of resizable columns — filters out non-resizable columns+ // (e.g. selection checkbox) once so that all index-based logic (neighbor+ // detection, last-column checks, drag snapshots) operates on a consistent+ // set. Without this, synthetic columns injected by other plugins shift+ // indices and break width computation.+ const resizableColumns = useMemo(+ () => columns?.filter(c => c.resizable !== false),+ [columns],+ );++ return useMemo(+ (): TablePlugin<T> => ({+ transformHeaderCell(+ props: HeaderCellRenderProps,+ column: XDSTableColumn<T>,+ ): HeaderCellRenderProps {+ // Skip columns that opt out of resizing+ if (column.resizable === false) return props;++ const overrideWidth = columnWidths?.[column.key];++ // Derive per-column min width from the column's own width config+ const effectiveMinWidth = resolveColumnMinWidth(+ column.width,+ globalMinWidth,+ );++ // Determine if this is a proportional column that should+ // delegate resize to its neighbor (the next column).+ // This prevents weird behavior when the table is 100% width+ // and the last column is proportional — it just flexes.+ // Uses resizableColumns so indices aren't shifted by non-resizable+ // synthetic columns (e.g. selection).+ let neighborKey: string | null = null;+ let neighborMinWidth = FALLBACK_MIN_WIDTH;++ if (resizableColumns && isProportionalColumn(column.width)) {+ const colIndex = resizableColumns.findIndex(+ c => c.key === column.key,+ );+ if (colIndex >= 0 && colIndex < resizableColumns.length - 1) {+ const nextCol = resizableColumns[colIndex + 1];+ neighborKey = nextCol.key;+ neighborMinWidth = resolveColumnMinWidth(+ nextCol.width,+ globalMinWidth,+ );+ }+ }++ // If this is the last resizable column and it's proportional, skip+ // the handle. There's no neighbor to resize and resizing a flex+ // column in a full-width table produces unpredictable results.+ if (resizableColumns) {+ const colIndex = resizableColumns.findIndex(+ c => c.key === column.key,+ );+ const isLastResizable = colIndex === resizableColumns.length - 1;+ if (isLastResizable && isProportionalColumn(column.width)) {+ return props;+ }+ }++ const widthStyle: React.CSSProperties | undefined =+ overrideWidth != null+ ? {+ width: `${overrideWidth}px`,+ minWidth: `${overrideWidth}px`,+ maxWidth: `${overrideWidth}px`,+ }+ : undefined;++ const existingStyle = props.htmlProps.style as+ | React.CSSProperties+ | undefined;+ const mergedStyle = widthStyle+ ? existingStyle+ ? {...existingStyle, ...widthStyle}+ : widthStyle+ : existingStyle;++ const handle = (+ <ResizeHandle+ key={`resize-${column.key}`}+ columnKey={column.key}+ columnHeader={column.header ?? column.key}+ currentWidth={overrideWidth}+ minWidth={effectiveMinWidth}+ maxWidth={maxWidth}+ neighborKey={neighborKey}+ neighborMinWidth={neighborMinWidth}+ configRef={configRef}+ dragStateRef={dragStateRef}+ isDraggingRef={isDraggingRef}+ tableRef={tableRef}+ />+ );++ return {+ ...props,+ htmlProps: {+ ...props.htmlProps,+ style: mergedStyle,+ },+ overlay: (+ <>+ {props.overlay}+ {handle}+ </>+ ),+ styles: [...props.styles, headerCellRelative.base],+ };+ },+ }),+ [columnWidths, globalMinWidth, maxWidth, resizableColumns],+ );+}diff --git a/packages/core/src/Table/plugins/selection/useXDSTableSelection.tsx b/packages/core/src/Table/plugins/selection/useXDSTableSelection.tsxindex 2da866c3b6..aea1398b47 100644--- a/packages/core/src/Table/plugins/selection/useXDSTableSelection.tsx+++ b/packages/core/src/Table/plugins/selection/useXDSTableSelection.tsx@@ -318,6 +318,7 @@ export function useXDSTableSelection<T extends Record<string, unknown>>(</div>),width: SELECTION_COLUMN_WIDTH,+ resizable: false,renderCell: (item: T) => (<div {...stylex.props(selectionColumnStyles.center)}><SelectionCellContent item={item} />diff --git a/packages/core/src/Table/types.ts b/packages/core/src/Table/types.tsindex 538a31be8f..cf84c1e566 100644--- a/packages/core/src/Table/types.ts+++ b/packages/core/src/Table/types.ts@@ -96,6 +96,17 @@ export interface XDSTableColumn<T extends Record<string, unknown>> {* { key: 'fullName', header: 'Full Name', sortable: { sortKey: 'lastName' } }* ```*/+ /**+ * Whether this column can be resized by dragging its header border.+ * Defaults to `true`. Set to `false` to lock the column width.+ *+ * @example+ * ```+ * // Non-resizable fixed column+ * { key: 'actions', header: '', width: pixel(48), resizable: false }+ * ```+ */+ resizable?: boolean;sortable?: boolean | XDSTableSortableColumnConfig;/*** Custom cell renderer. Receives the row item and returns rich JSX content.