An open source design system that's fully customizable and agent ready
TypeScript
feat(table): add useXDSTableSortableState convenience hook (#1160)
Cindy Zhangc433f7ceb9a8
diff --git a/apps/storybook/stories/TableFiltering.stories.tsx b/apps/storybook/stories/TableFiltering.stories.tsxindex 02baf6768c..9be996956d 100644--- a/apps/storybook/stories/TableFiltering.stories.tsx+++ b/apps/storybook/stories/TableFiltering.stories.tsx@@ -7,10 +7,11 @@ import {useXDSTableSelection,useXDSTableSelectionState,useXDSTableSortable,+ useXDSTableSortableState,useXDSTableColumnResize,toSearchFilters,} from '@xds/core/Table';-import type {XDSTableColumn, XDSTableSortState} from '@xds/core/Table';+import type {XDSTableColumn} from '@xds/core/Table';import {usePowerSearchConfig} from '@xds/core/PowerSearch';import {XDSEmptyState} from '@xds/core/EmptyState';import type {PowerSearchFilter} from '@xds/core/PowerSearch';@@ -95,23 +96,6 @@ const fieldDefs = [{key: 'level', type: 'number', label: 'Level'},] as const;-function applySorting<T extends Record<string, unknown>>(- data: T[],- sort: XDSTableSortState,-): T[] {- if (sort.length === 0) return data;- return [...data].sort((a, b) => {- for (const {sortKey, direction} of sort) {- const aVal = a[sortKey];- const bVal = b[sortKey];- const cmp = String(aVal).localeCompare(String(bVal), undefined, {- numeric: true,- });- if (cmp !== 0) return direction === 'ascending' ? cmp : -cmp;- }- return 0;- });-}const meta: Meta = {title: 'Core/XDSTable/Filtering',tags: ['autodocs'],@@ -346,7 +330,14 @@ export const WithSorting: Story = {render: () => {const {config, applyFilters} = usePowerSearchConfig(fieldDefs);const {filters, onFilterChange} = useXDSTableFilterState();- const [sort, setSort] = useState<XDSTableSortState>([]);+ const {+ sortedData: _unused,+ sort,+ sortConfig,+ applySort,+ } = useXDSTableSortableState<Employee>({+ data: employees,+ });const columns: XDSTableColumn<Employee>[] = [{key: 'name', header: 'Name', sortable: true, filter: 'name'},{key: 'role', header: 'Role', sortable: true, filter: 'role'},@@ -358,15 +349,12 @@ export const WithSorting: Story = {onFilterChange,searchConfig: config,});- const sortPlugin = useXDSTableSortable<Employee>({- sort,- onSortChange: setSort,- });+ const sortPlugin = useXDSTableSortable<Employee>(sortConfig);const filtered = applyFilters(toSearchFilters(filters, columns, config) as PowerSearchFilter[],employees,);- const data = applySorting(filtered, sort);+ const data = applySort(filtered);return (<div style={{maxWidth: 800}}><p style={{marginBottom: 8, fontSize: 14, color: '#666'}}>@@ -433,7 +421,9 @@ export const WithAllPlugins: Story = {render: () => {const {config, applyFilters} = usePowerSearchConfig(fieldDefs);const {filters, onFilterChange} = useXDSTableFilterState();- const [sort, setSort] = useState<XDSTableSortState>([]);+ const {sortConfig, applySort} = useXDSTableSortableState<Employee>({+ data: employees,+ });const [columnWidths, setColumnWidths] = useState<Record<string, number>>({},);@@ -449,10 +439,7 @@ export const WithAllPlugins: Story = {onFilterChange,searchConfig: config,});- const sortPlugin = useXDSTableSortable<Employee>({- sort,- onSortChange: setSort,- });+ const sortPlugin = useXDSTableSortable<Employee>(sortConfig);const resizePlugin = useXDSTableColumnResize<Employee>({columnWidths,onColumnResizeEnd: updates =>@@ -463,7 +450,7 @@ export const WithAllPlugins: Story = {toSearchFilters(filters, columns, config) as PowerSearchFilter[],employees,);- const data = applySorting(filtered, sort);+ const data = applySort(filtered);const {selectionConfig} = useXDSTableSelectionState({data,idKey: 'id',diff --git a/apps/storybook/stories/TableSortable.stories.tsx b/apps/storybook/stories/TableSortable.stories.tsxindex ef326e13a3..f50c7c66d3 100644--- a/apps/storybook/stories/TableSortable.stories.tsx+++ b/apps/storybook/stories/TableSortable.stories.tsx@@ -3,13 +3,11 @@ import type {Meta, StoryObj} from '@storybook/react';import {XDSTable,useXDSTableSortable,+ useXDSTableSortableState,useXDSTableSelection,useXDSTableSelectionState,} from '@xds/core/Table';-import type {- XDSTableColumn,- XDSTableSortState,-} from '@xds/core/Table';+import type {XDSTableColumn, XDSTableSortState} from '@xds/core/Table';// =============================================================================// Sample Data@@ -88,33 +86,21 @@ type Story = StoryObj;export const SingleSort: Story = {render: () => {- const [sort, setSort] = useState<XDSTableSortState>([- {sortKey: 'name', direction: 'ascending'},- ]);-- const sortablePlugin = useXDSTableSortable({sort, onSortChange: setSort});-- const sorted = [...employees].sort((a, b) => {- if (sort.length === 0) return 0;- const {sortKey, direction} = sort[0];- const aVal = a[sortKey];- const bVal = b[sortKey];- const cmp = String(aVal).localeCompare(String(bVal), undefined, {- numeric: true,- });- return direction === 'ascending' ? cmp : -cmp;+ const {sortedData, sort, sortConfig} = useXDSTableSortableState<Employee>({+ data: employees,+ defaultSort: [{sortKey: 'name', direction: 'ascending'}],});+ const sortablePlugin = useXDSTableSortable(sortConfig);+return (<div style={{maxWidth: 700}}><p style={{marginBottom: 8, fontSize: 14, color: '#666'}}>Click a column header to sort. Current:{' '}- {sort.length > 0- ? `${sort[0].sortKey} ${sort[0].direction}`- : 'none'}+ {sort.length > 0 ? `${sort[0].sortKey} ${sort[0].direction}` : 'none'}</p><XDSTable- data={sorted}+ data={sortedData}columns={columns}idKey="id"plugins={{sortable: sortablePlugin}}@@ -126,27 +112,13 @@ export const SingleSort: Story = {export const MultiSort: Story = {render: () => {- const [sort, setSort] = useState<XDSTableSortState>([- {sortKey: 'role', direction: 'ascending'},- ]);-- const sortablePlugin = useXDSTableSortable({- sort,- onSortChange: setSort,+ const {sortedData, sort, sortConfig} = useXDSTableSortableState<Employee>({+ data: employees,+ defaultSort: [{sortKey: 'role', direction: 'ascending'}],isMultiSortEnabled: true,});- const sorted = [...employees].sort((a, b) => {- for (const {sortKey, direction} of sort) {- const aVal = a[sortKey];- const bVal = b[sortKey];- const cmp = String(aVal).localeCompare(String(bVal), undefined, {- numeric: true,- });- if (cmp !== 0) return direction === 'ascending' ? cmp : -cmp;- }- return 0;- });+ const sortablePlugin = useXDSTableSortable(sortConfig);return (<div style={{maxWidth: 700}}>@@ -155,7 +127,7 @@ export const MultiSort: Story = {{sort.map(s => `${s.sortKey} (${s.direction})`).join(', ') || 'none'}</p><XDSTable- data={sorted}+ data={sortedData}columns={columns}idKey="id"plugins={{sortable: sortablePlugin}}@@ -174,40 +146,26 @@ export const CustomSortKey: Story = {{key: 'age', header: 'Age', sortable: {sortKey: 'yearsOld'}},];- const [sort, setSort] = useState<XDSTableSortState>([- {sortKey: 'yearsOld', direction: 'ascending'},- ]);-- const sortablePlugin = useXDSTableSortable({sort, onSortChange: setSort});-- const sorted = [...employees].sort((a, b) => {- if (sort.length === 0) return 0;- const {sortKey, direction} = sort[0];- // Map custom sortKeys back to data fields- const fieldMap: Record<string, string> = {- yearsOld: 'age',- emailSort: 'email',- };- const field = fieldMap[sortKey] ?? sortKey;- const aVal = a[field];- const bVal = b[field];- const cmp = String(aVal).localeCompare(String(bVal), undefined, {- numeric: true,- });- return direction === 'ascending' ? cmp : -cmp;+ const {sortedData, sort, sortConfig} = useXDSTableSortableState<Employee>({+ data: employees,+ defaultSort: [{sortKey: 'yearsOld', direction: 'ascending'}],+ comparators: {+ yearsOld: (a, b) => a.age - b.age,+ emailSort: (a, b) => a.email.localeCompare(b.email),+ },});+ const sortablePlugin = useXDSTableSortable(sortConfig);+return (<div style={{maxWidth: 700}}><p style={{marginBottom: 8, fontSize: 14, color: '#666'}}>Age column uses sortKey "yearsOld", Email uses"emailSort". Current:{' '}- {sort.length > 0- ? `${sort[0].sortKey} ${sort[0].direction}`- : 'none'}+ {sort.length > 0 ? `${sort[0].sortKey} ${sort[0].direction}` : 'none'}</p><XDSTable- data={sorted}+ data={sortedData}columns={customColumns}idKey="id"plugins={{sortable: sortablePlugin}}@@ -219,24 +177,12 @@ export const CustomSortKey: Story = {export const AllowUnsortedState: Story = {render: () => {- const [sort, setSort] = useState<XDSTableSortState>([]);-- const sortablePlugin = useXDSTableSortable({- sort,- onSortChange: setSort,+ const {sortedData, sort, sortConfig} = useXDSTableSortableState<Employee>({+ data: employees,allowUnsortedState: true,});- const sorted = [...employees].sort((a, b) => {- if (sort.length === 0) return 0;- const {sortKey, direction} = sort[0];- const aVal = a[sortKey];- const bVal = b[sortKey];- const cmp = String(aVal).localeCompare(String(bVal), undefined, {- numeric: true,- });- return direction === 'ascending' ? cmp : -cmp;- });+ const sortablePlugin = useXDSTableSortable(sortConfig);return (<div style={{maxWidth: 700}}>@@ -247,7 +193,7 @@ export const AllowUnsortedState: Story = {: 'unsorted'}</p><XDSTable- data={sorted}+ data={sortedData}columns={columns}idKey="id"plugins={{sortable: sortablePlugin}}@@ -259,26 +205,17 @@ export const AllowUnsortedState: Story = {export const WithSelection: Story = {render: () => {- const [sort, setSort] = useState<XDSTableSortState>([- {sortKey: 'name', direction: 'ascending'},- ]);const [selectedKeys, setSelectedKeys] = useState<Set<string>>(new Set());- const sortablePlugin = useXDSTableSortable({sort, onSortChange: setSort});-- const sorted = [...employees].sort((a, b) => {- if (sort.length === 0) return 0;- const {sortKey, direction} = sort[0];- const aVal = a[sortKey];- const bVal = b[sortKey];- const cmp = String(aVal).localeCompare(String(bVal), undefined, {- numeric: true,- });- return direction === 'ascending' ? cmp : -cmp;+ const {sortedData, sort, sortConfig} = useXDSTableSortableState<Employee>({+ data: employees,+ defaultSort: [{sortKey: 'name', direction: 'ascending'}],});+ const sortablePlugin = useXDSTableSortable(sortConfig);+const {selectionConfig} = useXDSTableSelectionState<Employee>({- data: sorted,+ data: sortedData,idKey: 'id',selectedKeys,setSelectedKeys,@@ -288,14 +225,12 @@ export const WithSelection: Story = {return (<div style={{maxWidth: 700}}><p style={{marginBottom: 8, fontSize: 14, color: '#666'}}>- Sorting + Selection composed together. Selected: {selectedKeys.size} of{' '}- {employees.length}. Sort:{' '}- {sort.length > 0- ? `${sort[0].sortKey} ${sort[0].direction}`- : 'none'}+ Sorting + Selection composed together. Selected: {selectedKeys.size}{' '}+ of {employees.length}. Sort:{' '}+ {sort.length > 0 ? `${sort[0].sortKey} ${sort[0].direction}` : 'none'}</p><XDSTable- data={sorted}+ data={sortedData}columns={columns}idKey="id"plugins={{sortable: sortablePlugin, selection: selectionPlugin}}@@ -304,3 +239,49 @@ export const WithSelection: Story = {);},};++export const Controlled: Story = {+ render: () => {+ const [sort, setSort] = useState<XDSTableSortState>([+ {sortKey: 'age', direction: 'descending'},+ ]);++ const {sortedData, sortConfig} = useXDSTableSortableState<Employee>({+ data: employees,+ sort,+ onSortChange: setSort,+ });++ const sortablePlugin = useXDSTableSortable(sortConfig);++ return (+ <div style={{maxWidth: 700}}>+ <p style={{marginBottom: 8, fontSize: 14, color: '#666'}}>+ Controlled mode — external state. Current:{' '}+ {sort.length > 0 ? `${sort[0].sortKey} ${sort[0].direction}` : 'none'}+ </p>+ <div style={{display: 'flex', gap: 8, marginBottom: 8}}>+ <button+ onClick={() =>+ setSort([{sortKey: 'name', direction: 'ascending'}])+ }>+ Sort by Name ↑+ </button>+ <button+ onClick={() =>+ setSort([{sortKey: 'age', direction: 'descending'}])+ }>+ Sort by Age ↓+ </button>+ <button onClick={() => setSort([])}>Clear Sort</button>+ </div>+ <XDSTable+ data={sortedData}+ columns={columns}+ idKey="id"+ plugins={{sortable: sortablePlugin}}+ />+ </div>+ );+ },+};diff --git a/packages/core/src/Table/index.ts b/packages/core/src/Table/index.tsindex 69e557d453..6eec638dfc 100644--- a/packages/core/src/Table/index.ts+++ b/packages/core/src/Table/index.ts@@ -18,6 +18,7 @@ export {XDSTableContext} from './XDSTableContext';export {useXDSTableSelection} from './plugins/selection';export {useXDSTableSelectionState} from './plugins/selection';export {useXDSTableSortable} from './plugins/sortable';+export {useXDSTableSortableState} from './plugins/sortable';export {useXDSTablePagination} from './plugins/pagination';export {useXDSTableColumnSettings} from './plugins/columnSettings';export {useXDSTableColumnSettingsState} from './plugins/columnSettings';@@ -67,6 +68,9 @@ export type {} from './plugins/selection';export type {UseXDSTableSortableConfig,+ UseXDSTableSortableStateConfig,+ UseXDSTableSortableStateResult,+ XDSTableSortComparator,XDSTableSortDirection,XDSTableSortEntry,XDSTableSortState,diff --git a/packages/core/src/Table/plugins/sortable/index.ts b/packages/core/src/Table/plugins/sortable/index.tsindex e90d6178fb..c4753212f1 100644--- a/packages/core/src/Table/plugins/sortable/index.ts+++ b/packages/core/src/Table/plugins/sortable/index.ts@@ -5,3 +5,9 @@ export type {XDSTableSortEntry,XDSTableSortState,} from './useXDSTableSortable';+export {useXDSTableSortableState} from './useXDSTableSortableState';+export type {+ UseXDSTableSortableStateConfig,+ UseXDSTableSortableStateResult,+ XDSTableSortComparator,+} from './useXDSTableSortableState';diff --git a/packages/core/src/Table/plugins/sortable/useXDSTableSortableState.test.tsx b/packages/core/src/Table/plugins/sortable/useXDSTableSortableState.test.tsxnew file mode 100644index 0000000000..4d6f23b152--- /dev/null+++ b/packages/core/src/Table/plugins/sortable/useXDSTableSortableState.test.tsx@@ -0,0 +1,518 @@+/**+ * @file useXDSTableSortableState.test.tsx+ * @input Uses vitest, @testing-library/react, Table components+ * @output Unit tests for useXDSTableSortableState hook+ * @position Testing; validates sortable state + data sorting+ */++import {describe, it, expect, vi} from 'vitest';+import {render, screen, within} from '@testing-library/react';+import userEvent from '@testing-library/user-event';+import {useState} from 'react';+import {XDSTable} from '../../XDSTable';+import type {XDSTableColumn} from '../../types';+import {useXDSTableSortable} from './useXDSTableSortable';+import type {XDSTableSortState} from './useXDSTableSortable';+import {useXDSTableSortableState} from './useXDSTableSortableState';+import type {UseXDSTableSortableStateConfig} from './useXDSTableSortableState';++// =============================================================================+// Test Data+// =============================================================================++interface Employee extends Record<string, unknown> {+ id: string;+ name: string;+ age: number;+ department: string;+ salary: number;+}++const employees: Employee[] = [+ {+ id: '1',+ name: 'Charlie',+ age: 35,+ department: 'Engineering',+ salary: 120000,+ },+ {id: '2', name: 'Alice', age: 28, department: 'Design', salary: 95000},+ {id: '3', name: 'Bob', age: 42, department: 'Engineering', salary: 140000},+ {id: '4', name: 'Diana', age: 31, department: 'PM', salary: 110000},+];++const columns: XDSTableColumn<Employee>[] = [+ {key: 'name', header: 'Name', sortable: true},+ {key: 'age', header: 'Age', sortable: true},+ {key: 'department', header: 'Department', sortable: true},+ {key: 'salary', header: 'Salary', sortable: true},+];++// =============================================================================+// Test Helpers+// =============================================================================++/** Reads the text content of every first-column cell in order. */+function getNameColumnValues(): string[] {+ const rows = screen.getAllByRole('row');+ // Skip header row+ return rows.slice(1).map(row => {+ const cells = within(row).getAllByRole('cell');+ return cells[0].textContent ?? '';+ });+}++function SortableStateTable({+ data = employees,+ columns: cols = columns,+ defaultSort,+ sort: controlledSort,+ onSortChange: controlledOnSortChange,+ comparators,+ allowUnsortedState,+ isMultiSortEnabled,+}: Partial<UseXDSTableSortableStateConfig<Employee>> & {+ columns?: XDSTableColumn<Employee>[];+}) {+ const {sortedData, sortConfig} = useXDSTableSortableState<Employee>({+ data,+ defaultSort,+ sort: controlledSort,+ onSortChange: controlledOnSortChange,+ comparators,+ allowUnsortedState,+ isMultiSortEnabled,+ });++ const sortPlugin = useXDSTableSortable<Employee>(sortConfig);++ return (+ <XDSTable+ data={sortedData}+ columns={cols}+ idKey="id"+ plugins={{sort: sortPlugin}}+ />+ );+}++// =============================================================================+// Sorting Tests+// =============================================================================++describe('useXDSTableSortableState', () => {+ describe('default sort', () => {+ it('applies defaultSort on initial render', () => {+ render(+ <SortableStateTable+ defaultSort={[{sortKey: 'name', direction: 'ascending'}]}+ />,+ );++ expect(getNameColumnValues()).toEqual([+ 'Alice',+ 'Bob',+ 'Charlie',+ 'Diana',+ ]);+ });++ it('renders unsorted when no defaultSort', () => {+ render(<SortableStateTable />);++ // Original order+ expect(getNameColumnValues()).toEqual([+ 'Charlie',+ 'Alice',+ 'Bob',+ 'Diana',+ ]);+ });++ it('applies descending defaultSort', () => {+ render(+ <SortableStateTable+ defaultSort={[{sortKey: 'name', direction: 'descending'}]}+ />,+ );++ expect(getNameColumnValues()).toEqual([+ 'Diana',+ 'Charlie',+ 'Bob',+ 'Alice',+ ]);+ });+ });++ describe('interactive sorting', () => {+ it('clicking a header sorts ascending then descending', async () => {+ render(<SortableStateTable />);++ // Click Name header to sort ascending+ await userEvent.click(+ screen.getByRole('button', {name: /sort by name/i}),+ );+ expect(getNameColumnValues()).toEqual([+ 'Alice',+ 'Bob',+ 'Charlie',+ 'Diana',+ ]);++ // Click again to sort descending+ await userEvent.click(+ screen.getByRole('button', {name: /sort by name/i}),+ );+ expect(getNameColumnValues()).toEqual([+ 'Diana',+ 'Charlie',+ 'Bob',+ 'Alice',+ ]);+ });++ it('clicking a different column replaces sort', async () => {+ render(+ <SortableStateTable+ defaultSort={[{sortKey: 'name', direction: 'ascending'}]}+ />,+ );++ expect(getNameColumnValues()).toEqual([+ 'Alice',+ 'Bob',+ 'Charlie',+ 'Diana',+ ]);++ // Sort by age instead+ await userEvent.click(screen.getByRole('button', {name: /sort by age/i}));++ // Age ascending: Alice(28), Diana(31), Charlie(35), Bob(42)+ expect(getNameColumnValues()).toEqual([+ 'Alice',+ 'Diana',+ 'Charlie',+ 'Bob',+ ]);+ });++ it('unsorted state clears sort (allowUnsortedState=true)', async () => {+ render(+ <SortableStateTable+ defaultSort={[{sortKey: 'name', direction: 'ascending'}]}+ allowUnsortedState+ />,+ );++ // Click to descending+ await userEvent.click(+ screen.getByRole('button', {name: /sort by name/i}),+ );+ // Click to unsorted+ await userEvent.click(+ screen.getByRole('button', {name: /sort by name/i}),+ );++ // Back to original order+ expect(getNameColumnValues()).toEqual([+ 'Charlie',+ 'Alice',+ 'Bob',+ 'Diana',+ ]);+ });+ });++ describe('numeric sorting', () => {+ it('sorts numbers correctly without custom comparator', async () => {+ render(<SortableStateTable />);++ await userEvent.click(screen.getByRole('button', {name: /sort by age/i}));++ // Age ascending: 28, 31, 35, 42+ expect(getNameColumnValues()).toEqual([+ 'Alice',+ 'Diana',+ 'Charlie',+ 'Bob',+ ]);+ });+ });++ describe('custom comparators', () => {+ it('uses custom comparator when provided', () => {+ render(+ <SortableStateTable+ defaultSort={[{sortKey: 'salary', direction: 'ascending'}]}+ comparators={{+ salary: (a, b) => a.salary - b.salary,+ }}+ />,+ );++ // Salary ascending: Alice(95k), Diana(110k), Charlie(120k), Bob(140k)+ expect(getNameColumnValues()).toEqual([+ 'Alice',+ 'Diana',+ 'Charlie',+ 'Bob',+ ]);+ });++ it('falls back to default compare for keys without custom comparator', () => {+ render(+ <SortableStateTable+ defaultSort={[{sortKey: 'name', direction: 'ascending'}]}+ comparators={{+ salary: (a, b) => a.salary - b.salary,+ }}+ />,+ );++ // Name uses default string compare+ expect(getNameColumnValues()).toEqual([+ 'Alice',+ 'Bob',+ 'Charlie',+ 'Diana',+ ]);+ });+ });++ describe('controlled mode', () => {+ function ControlledWrapper() {+ const [sort, setSort] = useState<XDSTableSortState>([+ {sortKey: 'name', direction: 'ascending'},+ ]);++ return (+ <>+ <button+ data-testid="external-sort"+ onClick={() =>+ setSort([{sortKey: 'age', direction: 'descending'}])+ }>+ Sort by age desc+ </button>+ <button data-testid="clear-sort" onClick={() => setSort([])}>+ Clear sort+ </button>+ <SortableStateTable sort={sort} onSortChange={setSort} />+ </>+ );+ }++ it('uses controlled sort state', () => {+ render(<ControlledWrapper />);++ expect(getNameColumnValues()).toEqual([+ 'Alice',+ 'Bob',+ 'Charlie',+ 'Diana',+ ]);+ });++ it('responds to external sort state changes', async () => {+ render(<ControlledWrapper />);++ await userEvent.click(screen.getByTestId('external-sort'));++ // Age descending: Bob(42), Charlie(35), Diana(31), Alice(28)+ expect(getNameColumnValues()).toEqual([+ 'Bob',+ 'Charlie',+ 'Diana',+ 'Alice',+ ]);+ });++ it('responds to sort clear', async () => {+ render(<ControlledWrapper />);++ await userEvent.click(screen.getByTestId('clear-sort'));++ // Original order+ expect(getNameColumnValues()).toEqual([+ 'Charlie',+ 'Alice',+ 'Bob',+ 'Diana',+ ]);+ });++ it('header clicks update controlled state', async () => {+ const onSortChange = vi.fn();++ function ControlledWithSpy() {+ const [sort, setSort] = useState<XDSTableSortState>([]);+ const handleChange = (newSort: XDSTableSortState) => {+ setSort(newSort);+ onSortChange(newSort);+ };+ return <SortableStateTable sort={sort} onSortChange={handleChange} />;+ }++ render(<ControlledWithSpy />);++ await userEvent.click(+ screen.getByRole('button', {name: /sort by name/i}),+ );++ expect(onSortChange).toHaveBeenCalledWith([+ {sortKey: 'name', direction: 'ascending'},+ ]);+ });+ });++ describe('multi-sort', () => {+ it('supports multi-sort via shift+click', async () => {+ const user = userEvent.setup();++ // Employees with same department+ const data: Employee[] = [+ {+ id: '1',+ name: 'Charlie',+ age: 35,+ department: 'Engineering',+ salary: 120000,+ },+ {+ id: '2',+ name: 'Alice',+ age: 28,+ department: 'Engineering',+ salary: 95000,+ },+ {id: '3', name: 'Bob', age: 42, department: 'Design', salary: 140000},+ {id: '4', name: 'Diana', age: 31, department: 'Design', salary: 110000},+ ];++ render(+ <SortableStateTable+ data={data}+ defaultSort={[{sortKey: 'department', direction: 'ascending'}]}+ isMultiSortEnabled+ />,+ );++ // Department ascending: Design(Bob, Diana), Engineering(Alice, Charlie)+ // Now shift+click Name to add secondary sort+ await user.keyboard('{Shift>}');+ await user.click(screen.getByRole('button', {name: /sort by name/i}));+ await user.keyboard('{/Shift}');++ // Design: Bob, Diana; Engineering: Alice, Charlie+ expect(getNameColumnValues()).toEqual([+ 'Bob',+ 'Diana',+ 'Alice',+ 'Charlie',+ ]);+ });+ });++ describe('null/undefined handling', () => {+ it('sorts null values to the end', () => {+ const data: Employee[] = [+ {+ id: '1',+ name: 'Charlie',+ age: 35,+ department: 'Engineering',+ salary: 120000,+ },+ {+ id: '2',+ name: null as unknown as string,+ age: 28,+ department: 'Design',+ salary: 95000,+ },+ {+ id: '3',+ name: 'Alice',+ age: 42,+ department: 'Engineering',+ salary: 140000,+ },+ ];++ render(+ <SortableStateTable+ data={data}+ defaultSort={[{sortKey: 'name', direction: 'ascending'}]}+ />,+ );++ const names = getNameColumnValues();+ // Alice, Charlie first; null last+ expect(names[0]).toBe('Alice');+ expect(names[1]).toBe('Charlie');+ });+ });++ describe('empty data', () => {+ it('handles empty data array', () => {+ render(+ <SortableStateTable+ data={[]}+ defaultSort={[{sortKey: 'name', direction: 'ascending'}]}+ />,+ );++ // Should render without throwing — table still mounts with empty data+ expect(screen.getByRole('table')).toBeInTheDocument();+ // Sort headers should still be interactive+ expect(+ screen.getByRole('button', {name: /sort by name/i}),+ ).toBeInTheDocument();+ });+ });++ describe('applySort', () => {+ it('exposes applySort for external use', () => {+ let capturedApplySort: ((data: Employee[]) => Employee[]) | null = null;++ function Capture() {+ const {sortedData, sortConfig, applySort} =+ useXDSTableSortableState<Employee>({+ data: employees,+ defaultSort: [{sortKey: 'name', direction: 'ascending'}],+ });++ capturedApplySort = applySort;+ const sortPlugin = useXDSTableSortable<Employee>(sortConfig);++ return (+ <XDSTable+ data={sortedData}+ columns={columns}+ idKey="id"+ plugins={{sort: sortPlugin}}+ />+ );+ }++ render(<Capture />);++ // Use applySort on a different dataset+ const subset: Employee[] = [+ {id: '10', name: 'Zara', age: 25, department: 'PM', salary: 90000},+ {+ id: '11',+ name: 'Aaron',+ age: 30,+ department: 'Design',+ salary: 100000,+ },+ ];++ const sorted = capturedApplySort!(subset);+ expect(sorted.map(e => e.name)).toEqual(['Aaron', 'Zara']);+ });+ });+});diff --git a/packages/core/src/Table/plugins/sortable/useXDSTableSortableState.tsx b/packages/core/src/Table/plugins/sortable/useXDSTableSortableState.tsxnew file mode 100644index 0000000000..306b6d3a21--- /dev/null+++ b/packages/core/src/Table/plugins/sortable/useXDSTableSortableState.tsx@@ -0,0 +1,292 @@+'use client';++/**+ * @file useXDSTableSortableState.tsx+ * @input React, XDSTableSortState types+ * @output Exports useXDSTableSortableState hook and config types+ * @position Sort state helper; manages sort state + applies local sort to data.+ * Pairs with useXDSTableSortable (the headless sort plugin).+ *+ * Modeled after useXDSTableSelectionState — a convenience layer that owns state+ * and produces a ready-to-use config for the headless plugin.+ *+ * SYNC: When modified, update these files to stay in sync:+ * - /packages/core/src/Table/plugins/sortable/index.ts (exports)+ * - /packages/core/src/Table/Table.doc.mjs (sort documentation)+ */++import {useState, useMemo, useCallback, useRef} from 'react';+import type {+ XDSTableSortState,+ UseXDSTableSortableConfig,+} from './useXDSTableSortable';++// =============================================================================+// Comparator Types+// =============================================================================++/**+ * Custom comparator for a single sort key.+ * Receives two row values and returns a standard comparison number.+ * Direction (ascending/descending) is applied automatically by the hook —+ * comparators should always sort in ascending order.+ */+export type XDSTableSortComparator<T> = (a: T, b: T) => number;++// =============================================================================+// Hook Config+// =============================================================================++/**+ * Configuration for useXDSTableSortableState.+ *+ * @template T - The row data type+ * @template TSortKey - Union of valid sort key strings+ *+ * @example+ * ```+ * const { sortedData, sortConfig } = useXDSTableSortableState({+ * data: users,+ * defaultSort: [{ sortKey: 'name', direction: 'ascending' }],+ * });+ *+ * const sortPlugin = useXDSTableSortable(sortConfig);+ * <XDSTable data={sortedData} plugins={{ sort: sortPlugin }} />+ * ```+ *+ * @example+ * ```+ * const [sort, setSort] = useState<XDSTableSortState>([]);+ * const { sortedData, sortConfig } = useXDSTableSortableState({+ * data: users,+ * sort,+ * onSortChange: setSort,+ * });+ * ```+ */+export interface UseXDSTableSortableStateConfig<+ T extends Record<string, unknown>,+ TSortKey extends string = string,+> {+ /**+ * The data array to sort.+ * The hook returns a new sorted copy — the original is never mutated.+ */+ data: T[];++ /**+ * Initial sort state for uncontrolled mode.+ * Ignored when `sort` is provided.+ * @default []+ */+ defaultSort?: XDSTableSortState<TSortKey>;++ /**+ * Controlled sort state. When provided, the hook uses this instead of+ * internal state. Must be paired with `onSortChange`.+ */+ sort?: XDSTableSortState<TSortKey>;++ /**+ * Called when the sort state changes. Required when `sort` is provided.+ */+ onSortChange?: (sort: XDSTableSortState<TSortKey>) => void;++ /**+ * Custom comparators per sort key.+ * Keys are sort key strings; values are comparator functions that receive+ * two row items. Comparators should sort ascending — the hook flips the+ * sign for descending.+ *+ * For keys not in this map, the hook falls back to `localeCompare` with+ * `{ numeric: true }` on the stringified values.+ *+ * @example+ * ```+ * comparators: {+ * age: (a, b) => a.age - b.age,+ * name: (a, b) => a.name.localeCompare(b.name),+ * }+ * ```+ */+ comparators?: Partial<Record<TSortKey, XDSTableSortComparator<T>>>;++ /**+ * Allow returning to unsorted state.+ * Passed through to the sortable plugin config.+ * @default true+ */+ allowUnsortedState?: boolean;++ /**+ * Enable multi-sort via modifier key.+ * Passed through to the sortable plugin config.+ * @default false+ */+ isMultiSortEnabled?: boolean;+}++// =============================================================================+// Hook Result+// =============================================================================++export interface UseXDSTableSortableStateResult<+ T extends Record<string, unknown>,+ TSortKey extends string = string,+> {+ /** Sorted copy of the input data. Memoized — stable when sort state and data don't change. */+ sortedData: T[];++ /** Current sort state. */+ sort: XDSTableSortState<TSortKey>;++ /** Ready-to-use config for useXDSTableSortable. */+ sortConfig: UseXDSTableSortableConfig<TSortKey>;++ /**+ * Apply the current sort state to arbitrary data.+ * Useful when you have multiple data sources or need to sort a subset.+ */+ applySort: (data: T[]) => T[];+}++// =============================================================================+// Default Comparator+// =============================================================================++function defaultCompare<T extends Record<string, unknown>>(+ a: T,+ b: T,+ sortKey: string,+): number {+ const aVal = a[sortKey];+ const bVal = b[sortKey];++ // null/undefined sort to the end+ if (aVal == null && bVal == null) return 0;+ if (aVal == null) return 1;+ if (bVal == null) return -1;++ // number fast path+ if (typeof aVal === 'number' && typeof bVal === 'number') {+ return aVal - bVal;+ }++ // string comparison with numeric collation+ return String(aVal).localeCompare(String(bVal), undefined, {numeric: true});+}++// =============================================================================+// Sort Logic+// =============================================================================++function sortData<+ T extends Record<string, unknown>,+ TSortKey extends string = string,+>(+ data: T[],+ sortState: XDSTableSortState<TSortKey>,+ comparators?: Partial<Record<TSortKey, XDSTableSortComparator<T>>>,+): T[] {+ if (sortState.length === 0) return data;++ return [...data].sort((a, b) => {+ for (const entry of sortState) {+ const {sortKey, direction} = entry;+ const customCmp = comparators?.[sortKey];+ const cmp = customCmp ? customCmp(a, b) : defaultCompare(a, b, sortKey);++ if (cmp !== 0) {+ return direction === 'ascending' ? cmp : -cmp;+ }+ }+ return 0;+ });+}++// =============================================================================+// Hook+// =============================================================================++/**+ * useXDSTableSortableState — manages sort state and applies local sort to data.+ *+ * Convenience layer over useXDSTableSortable. Owns sort state internally+ * (or accepts controlled state), sorts the data, and produces a ready-to-use+ * config for the headless sortable plugin.+ *+ * @example+ * ```+ * const { sortedData, sortConfig } = useXDSTableSortableState({+ * data: employees,+ * defaultSort: [{ sortKey: 'name', direction: 'ascending' }],+ * comparators: {+ * age: (a, b) => a.age - b.age,+ * },+ * });+ *+ * const sortPlugin = useXDSTableSortable(sortConfig);+ *+ * <XDSTable+ * data={sortedData}+ * columns={columns}+ * plugins={{ sort: sortPlugin }}+ * />+ * ```+ */+export function useXDSTableSortableState<+ T extends Record<string, unknown>,+ TSortKey extends string = string,+>(+ config: UseXDSTableSortableStateConfig<T, TSortKey>,+): UseXDSTableSortableStateResult<T, TSortKey> {+ const {+ data,+ defaultSort = [] as unknown as XDSTableSortState<TSortKey>,+ sort: controlledSort,+ onSortChange: controlledOnSortChange,+ comparators,+ allowUnsortedState,+ isMultiSortEnabled,+ } = config;++ // Internal state (used in uncontrolled mode)+ const [internalSort, setInternalSort] =+ useState<XDSTableSortState<TSortKey>>(defaultSort);++ // Resolve controlled vs uncontrolled+ const isControlled = controlledSort !== undefined;+ const sort = isControlled ? controlledSort : internalSort;+ const onSortChange = isControlled+ ? (controlledOnSortChange ?? (() => {}))+ : setInternalSort;++ // Stable ref for comparators to avoid re-sorting on inline object identity changes+ const comparatorsRef = useRef(comparators);+ comparatorsRef.current = comparators;++ // Sorted data — memoized on sort state + data identity+ const sortedData = useMemo(+ () => sortData(data, sort, comparatorsRef.current),+ [data, sort],+ );++ // applySort — lets consumers sort arbitrary data with the current state+ const applySort = useCallback(+ (inputData: T[]): T[] => sortData(inputData, sort, comparatorsRef.current),+ [sort],+ );++ // Config ready for useXDSTableSortable+ const sortConfig = useMemo(+ (): UseXDSTableSortableConfig<TSortKey> => ({+ sort,+ onSortChange,+ allowUnsortedState,+ isMultiSortEnabled,+ }),+ [sort, onSortChange, allowUnsortedState, isMultiSortEnabled],+ );++ return {sortedData, sort, sortConfig, applySort};+}