Skip to content

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

TypeScript

feat(Table): useXDSTableSortable — multi-sort plugin #978 (#1010)

Cindy Zhang45a592a66218
diff --git a/apps/storybook/stories/TableSortable.stories.tsx b/apps/storybook/stories/TableSortable.stories.tsx
new file mode 100644
index 0000000000..ef326e13a3
--- /dev/null
+++ b/apps/storybook/stories/TableSortable.stories.tsx
@@ -0,0 +1,306 @@
+import {useState} from 'react';
+import type {Meta, StoryObj} from '@storybook/react';
+import {
+ XDSTable,
+ useXDSTableSortable,
+ useXDSTableSelection,
+ useXDSTableSelectionState,
+} from '@xds/core/Table';
+import type {
+ XDSTableColumn,
+ XDSTableSortState,
+} from '@xds/core/Table';
+
+// =============================================================================
+// Sample Data
+// =============================================================================
+
+interface Employee extends Record<string, unknown> {
+ id: string;
+ name: string;
+ email: string;
+ role: string;
+ age: number;
+ isLocked: boolean;
+}
+
+const employees: Employee[] = [
+ {
+ id: '1',
+ name: 'Alice',
+ email: '[email protected]',
+ role: 'Engineer',
+ age: 32,
+ isLocked: false,
+ },
+ {
+ id: '2',
+ name: 'Bob',
+ email: '[email protected]',
+ role: 'Designer',
+ age: 28,
+ isLocked: false,
+ },
+ {
+ id: '3',
+ name: 'Charlie',
+ email: '[email protected]',
+ role: 'Manager',
+ age: 45,
+ isLocked: false,
+ },
+ {
+ id: '4',
+ name: 'Diana',
+ email: '[email protected]',
+ role: 'Engineer',
+ age: 37,
+ isLocked: true,
+ },
+ {
+ id: '5',
+ name: 'Eve',
+ email: '[email protected]',
+ role: 'Admin',
+ age: 29,
+ isLocked: false,
+ },
+];
+
+const columns: XDSTableColumn<Employee>[] = [
+ {key: 'name', header: 'Name', sortable: true},
+ {key: 'email', header: 'Email', sortable: true},
+ {key: 'role', header: 'Role', sortable: true},
+ {key: 'age', header: 'Age', sortable: true},
+];
+
+// =============================================================================
+// Stories
+// =============================================================================
+
+const meta: Meta = {
+ title: 'Core/XDSTable/Sortable',
+ tags: ['autodocs'],
+};
+
+export default meta;
+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;
+ });
+
+ 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'}
+ </p>
+ <XDSTable
+ data={sorted}
+ columns={columns}
+ idKey="id"
+ plugins={{sortable: sortablePlugin}}
+ />
+ </div>
+ );
+ },
+};
+
+export const MultiSort: Story = {
+ render: () => {
+ const [sort, setSort] = useState<XDSTableSortState>([
+ {sortKey: 'role', direction: 'ascending'},
+ ]);
+
+ const sortablePlugin = useXDSTableSortable({
+ sort,
+ onSortChange: setSort,
+ 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;
+ });
+
+ return (
+ <div style={{maxWidth: 700}}>
+ <p style={{marginBottom: 8, fontSize: 14, color: '#666'}}>
+ Shift+click column headers to add secondary sorts. Active sorts:{' '}
+ {sort.map(s => `${s.sortKey} (${s.direction})`).join(', ') || 'none'}
+ </p>
+ <XDSTable
+ data={sorted}
+ columns={columns}
+ idKey="id"
+ plugins={{sortable: sortablePlugin}}
+ />
+ </div>
+ );
+ },
+};
+
+export const CustomSortKey: Story = {
+ render: () => {
+ const customColumns: XDSTableColumn<Employee>[] = [
+ {key: 'name', header: 'Name', sortable: true},
+ {key: 'email', header: 'Email', sortable: {sortKey: 'emailSort'}},
+ {key: 'role', header: 'Role', sortable: true},
+ {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;
+ });
+
+ return (
+ <div style={{maxWidth: 700}}>
+ <p style={{marginBottom: 8, fontSize: 14, color: '#666'}}>
+ Age column uses sortKey &quot;yearsOld&quot;, Email uses
+ &quot;emailSort&quot;. Current:{' '}
+ {sort.length > 0
+ ? `${sort[0].sortKey} ${sort[0].direction}`
+ : 'none'}
+ </p>
+ <XDSTable
+ data={sorted}
+ columns={customColumns}
+ idKey="id"
+ plugins={{sortable: sortablePlugin}}
+ />
+ </div>
+ );
+ },
+};
+
+export const AllowUnsortedState: Story = {
+ render: () => {
+ const [sort, setSort] = useState<XDSTableSortState>([]);
+
+ const sortablePlugin = useXDSTableSortable({
+ sort,
+ onSortChange: setSort,
+ 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;
+ });
+
+ return (
+ <div style={{maxWidth: 700}}>
+ <p style={{marginBottom: 8, fontSize: 14, color: '#666'}}>
+ Cycles: ascending → descending → unsorted. Current:{' '}
+ {sort.length > 0
+ ? `${sort[0].sortKey} ${sort[0].direction}`
+ : 'unsorted'}
+ </p>
+ <XDSTable
+ data={sorted}
+ columns={columns}
+ idKey="id"
+ plugins={{sortable: sortablePlugin}}
+ />
+ </div>
+ );
+ },
+};
+
+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 {selectionConfig} = useXDSTableSelectionState<Employee>({
+ data: sorted,
+ idKey: 'id',
+ selectedKeys,
+ setSelectedKeys,
+ });
+ const selectionPlugin = useXDSTableSelection<Employee>(selectionConfig);
+
+ 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'}
+ </p>
+ <XDSTable
+ data={sorted}
+ columns={columns}
+ idKey="id"
+ plugins={{sortable: sortablePlugin, selection: selectionPlugin}}
+ />
+ </div>
+ );
+ },
+};
diff --git a/packages/core/src/Table/index.ts b/packages/core/src/Table/index.ts
index 577da692bc..5bea5415ed 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 {useXDSTableSortable} from './plugins/sortable';
export {useXDSBaseTablePlugins} from './useXDSBaseTablePlugins';
export {
proportional,
@@ -54,3 +55,10 @@ export type {
UseXDSTableSelectionStateConfig,
UseXDSTableSelectionStateResult,
} from './plugins/selection';
+export type {
+ UseXDSTableSortableConfig,
+ XDSTableSortDirection,
+ XDSTableSortEntry,
+ XDSTableSortState,
+} from './plugins/sortable';
+export type {XDSTableSortableColumnConfig} from './types';
diff --git a/packages/core/src/Table/plugins/sortable/index.ts b/packages/core/src/Table/plugins/sortable/index.ts
new file mode 100644
index 0000000000..e90d6178fb
--- /dev/null
+++ b/packages/core/src/Table/plugins/sortable/index.ts
@@ -0,0 +1,7 @@
+export {useXDSTableSortable} from './useXDSTableSortable';
+export type {
+ UseXDSTableSortableConfig,
+ XDSTableSortDirection,
+ XDSTableSortEntry,
+ XDSTableSortState,
+} from './useXDSTableSortable';
diff --git a/packages/core/src/Table/plugins/sortable/useXDSTableSortable.test.tsx b/packages/core/src/Table/plugins/sortable/useXDSTableSortable.test.tsx
new file mode 100644
index 0000000000..66cc66d6aa
--- /dev/null
+++ b/packages/core/src/Table/plugins/sortable/useXDSTableSortable.test.tsx
@@ -0,0 +1,619 @@
+/**
+ * @file useXDSTableSortable.test.tsx
+ * @input Uses vitest, @testing-library/react, Table components
+ * @output Unit tests for useXDSTableSortable plugin
+ * @position Testing; validates sortable plugin implementation
+ */
+
+import {describe, it, expect, vi} from 'vitest';
+import {render, screen} 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,
+ type XDSTableSortState,
+ type UseXDSTableSortableConfig,
+} from './useXDSTableSortable';
+
+// =============================================================================
+// Test Data
+// =============================================================================
+
+interface User extends Record<string, unknown> {
+ name: string;
+ age: number;
+ email: string;
+}
+
+const users: User[] = [
+ {name: 'Alice', age: 30, email: '[email protected]'},
+ {name: 'Bob', age: 25, email: '[email protected]'},
+];
+
+const sortableColumns: XDSTableColumn<User>[] = [
+ {key: 'name', header: 'Name', sortable: true},
+ {key: 'age', header: 'Age', sortable: true},
+ {key: 'email', header: 'Email'},
+];
+
+// =============================================================================
+// Test Helpers
+// =============================================================================
+
+function SortableTable({
+ columns = sortableColumns,
+ data = users,
+ initialSort = [] as XDSTableSortState,
+ allowUnsortedState = false,
+ isMultiSortEnabled = false,
+ onSortChange: externalOnSortChange,
+}: {
+ columns?: XDSTableColumn<User>[];
+ data?: User[];
+ initialSort?: XDSTableSortState;
+ allowUnsortedState?: boolean;
+ isMultiSortEnabled?: boolean;
+ onSortChange?: (sort: XDSTableSortState) => void;
+}) {
+ const [sort, setSort] = useState<XDSTableSortState>(initialSort);
+ const handleSortChange = (newSort: XDSTableSortState) => {
+ setSort(newSort);
+ externalOnSortChange?.(newSort);
+ };
+
+ const sortPlugin = useXDSTableSortable<User>({
+ sort,
+ onSortChange: handleSortChange,
+ allowUnsortedState,
+ isMultiSortEnabled,
+ });
+
+ return (
+ <XDSTable data={data} columns={columns} plugins={{sort: sortPlugin}} />
+ );
+}
+
+// =============================================================================
+// Rendering Tests
+// =============================================================================
+
+describe('useXDSTableSortable', () => {
+ describe('rendering', () => {
+ it('renders sort icon for sortable columns', () => {
+ render(<SortableTable />);
+
+ // Sortable columns should have sort buttons
+ expect(
+ screen.getByRole('button', {name: /sort by name/i}),
+ ).toBeInTheDocument();
+ expect(
+ screen.getByRole('button', {name: /sort by age/i}),
+ ).toBeInTheDocument();
+
+ // Non-sortable column should not have a sort button
+ expect(
+ screen.queryByRole('button', {name: /sort by email/i}),
+ ).not.toBeInTheDocument();
+ });
+
+ it('renders ascending icon when sort state is ascending', () => {
+ render(
+ <SortableTable
+ initialSort={[{sortKey: 'name', direction: 'ascending'}]}
+ />,
+ );
+
+ const button = screen.getByRole('button', {name: /sort by name/i});
+ expect(button).toBeInTheDocument();
+ expect(button.getAttribute('aria-label')).toContain('sorted ascending');
+ });
+
+ it('renders descending icon when sort state is descending', () => {
+ render(
+ <SortableTable
+ initialSort={[{sortKey: 'name', direction: 'descending'}]}
+ />,
+ );
+
+ const button = screen.getByRole('button', {name: /sort by name/i});
+ expect(button.getAttribute('aria-label')).toContain('sorted descending');
+ });
+
+ it('renders unsorted icon when column is sortable but not in sort state', () => {
+ render(<SortableTable />);
+
+ const button = screen.getByRole('button', {name: /sort by name/i});
+ expect(button.getAttribute('aria-label')).toBe('Sort by Name');
+ });
+
+ it('renders no sort UI for columns without sortable config', () => {
+ render(<SortableTable />);
+
+ // Email column is not sortable
+ expect(
+ screen.queryByRole('button', {name: /sort by email/i}),
+ ).not.toBeInTheDocument();
+ });
+
+ it('renders sort button wrapping header content', () => {
+ render(<SortableTable />);
+
+ const button = screen.getByRole('button', {name: /sort by name/i});
+ expect(button.tagName).toBe('BUTTON');
+ expect(button).toHaveAttribute('type', 'button');
+ expect(button.textContent).toContain('Name');
+ });
+
+ it('renders rank badge in multi-sort mode', () => {
+ render(
+ <SortableTable
+ isMultiSortEnabled
+ initialSort={[
+ {sortKey: 'name', direction: 'ascending'},
+ {sortKey: 'age', direction: 'descending'},
+ ]}
+ />,
+ );
+
+ const nameButton = screen.getByRole('button', {name: /sort by name/i});
+ const ageButton = screen.getByRole('button', {name: /sort by age/i});
+
+ // Rank badges should be present
+ expect(nameButton.textContent).toContain('1');
+ expect(ageButton.textContent).toContain('2');
+ });
+
+ it('does not render rank badge in single-sort mode', () => {
+ render(
+ <SortableTable
+ initialSort={[{sortKey: 'name', direction: 'ascending'}]}
+ />,
+ );
+
+ const nameButton = screen.getByRole('button', {name: /sort by name/i});
+ // Should not contain a rank badge — just "Name" text + icon
+ expect(nameButton.getAttribute('aria-label')).toBe(
+ 'Sort by Name, sorted ascending',
+ );
+ });
+
+ it('renders sort indicators when data is empty', () => {
+ render(<SortableTable data={[]} />);
+
+ expect(
+ screen.getByRole('button', {name: /sort by name/i}),
+ ).toBeInTheDocument();
+ });
+
+ it('uses custom sortKey from column config', () => {
+ const columns: XDSTableColumn<User>[] = [
+ {key: 'name', header: 'Full Name', sortable: {sortKey: 'lastName'}},
+ ];
+
+ render(
+ <SortableTable
+ columns={columns}
+ initialSort={[{sortKey: 'lastName', direction: 'ascending'}]}
+ />,
+ );
+
+ const button = screen.getByRole('button', {
+ name: /sort by full name/i,
+ });
+ expect(button.getAttribute('aria-label')).toContain('sorted ascending');
+ });
+
+ it('uses column key as default sortKey', () => {
+ render(
+ <SortableTable
+ initialSort={[{sortKey: 'name', direction: 'ascending'}]}
+ />,
+ );
+
+ const button = screen.getByRole('button', {name: /sort by name/i});
+ expect(button.getAttribute('aria-label')).toContain('sorted ascending');
+ });
+ });
+
+ // =============================================================================
+ // Interaction Tests
+ // =============================================================================
+
+ describe('interactions', () => {
+ it('clicking unsorted column calls onSortChange with ascending', async () => {
+ const onSortChange = vi.fn();
+ render(<SortableTable onSortChange={onSortChange} />);
+
+ await userEvent.click(
+ screen.getByRole('button', {name: /sort by name/i}),
+ );
+
+ expect(onSortChange).toHaveBeenCalledWith([
+ {sortKey: 'name', direction: 'ascending'},
+ ]);
+ });
+
+ it('clicking ascending column toggles to descending', async () => {
+ const onSortChange = vi.fn();
+ render(
+ <SortableTable
+ initialSort={[{sortKey: 'name', direction: 'ascending'}]}
+ onSortChange={onSortChange}
+ />,
+ );
+
+ await userEvent.click(
+ screen.getByRole('button', {name: /sort by name/i}),
+ );
+
+ expect(onSortChange).toHaveBeenCalledWith([
+ {sortKey: 'name', direction: 'descending'},
+ ]);
+ });
+
+ it('clicking descending column toggles to ascending (allowUnsortedState=false)', async () => {
+ const onSortChange = vi.fn();
+ render(
+ <SortableTable
+ initialSort={[{sortKey: 'name', direction: 'descending'}]}
+ onSortChange={onSortChange}
+ />,
+ );
+
+ await userEvent.click(
+ screen.getByRole('button', {name: /sort by name/i}),
+ );
+
+ expect(onSortChange).toHaveBeenCalledWith([
+ {sortKey: 'name', direction: 'ascending'},
+ ]);
+ });
+
+ it('clicking descending column clears sort (allowUnsortedState=true)', async () => {
+ const onSortChange = vi.fn();
+ render(
+ <SortableTable
+ initialSort={[{sortKey: 'name', direction: 'descending'}]}
+ allowUnsortedState
+ onSortChange={onSortChange}
+ />,
+ );
+
+ await userEvent.click(
+ screen.getByRole('button', {name: /sort by name/i}),
+ );
+
+ expect(onSortChange).toHaveBeenCalledWith([]);
+ });
+
+ it('clicking different column replaces sort in single-sort mode', async () => {
+ const onSortChange = vi.fn();
+ render(
+ <SortableTable
+ initialSort={[{sortKey: 'name', direction: 'ascending'}]}
+ onSortChange={onSortChange}
+ />,
+ );
+
+ await userEvent.click(screen.getByRole('button', {name: /sort by age/i}));
+
+ expect(onSortChange).toHaveBeenCalledWith([
+ {sortKey: 'age', direction: 'ascending'},
+ ]);
+ });
+
+ it('shift+click adds column to multi-sort', async () => {
+ const user = userEvent.setup();
+ const onSortChange = vi.fn();
+ render(
+ <SortableTable
+ initialSort={[{sortKey: 'name', direction: 'ascending'}]}
+ isMultiSortEnabled
+ onSortChange={onSortChange}
+ />,
+ );
+
+ await user.keyboard('{Shift>}');
+ await user.click(screen.getByRole('button', {name: /sort by age/i}));
+ await user.keyboard('{/Shift}');
+
+ expect(onSortChange).toHaveBeenCalledWith([
+ {sortKey: 'name', direction: 'ascending'},
+ {sortKey: 'age', direction: 'ascending'},
+ ]);
+ });
+
+ it('shift+click toggles existing column in multi-sort', async () => {
+ const user = userEvent.setup();
+ const onSortChange = vi.fn();
+ render(
+ <SortableTable
+ initialSort={[
+ {sortKey: 'name', direction: 'ascending'},
+ {sortKey: 'age', direction: 'ascending'},
+ ]}
+ isMultiSortEnabled
+ onSortChange={onSortChange}
+ />,
+ );
+
+ await user.keyboard('{Shift>}');
+ await user.click(screen.getByRole('button', {name: /sort by age/i}));
+ await user.keyboard('{/Shift}');
+
+ expect(onSortChange).toHaveBeenCalledWith([
+ {sortKey: 'name', direction: 'ascending'},
+ {sortKey: 'age', direction: 'descending'},
+ ]);
+ });
+
+ it('shift+click removes descending column in multi-sort (allowUnsortedState=true)', async () => {
+ const user = userEvent.setup();
+ const onSortChange = vi.fn();
+ render(
+ <SortableTable
+ initialSort={[
+ {sortKey: 'name', direction: 'ascending'},
+ {sortKey: 'age', direction: 'descending'},
+ ]}
+ isMultiSortEnabled
+ allowUnsortedState
+ onSortChange={onSortChange}
+ />,
+ );
+
+ await user.keyboard('{Shift>}');
+ await user.click(screen.getByRole('button', {name: /sort by age/i}));
+ await user.keyboard('{/Shift}');
+
+ expect(onSortChange).toHaveBeenCalledWith([
+ {sortKey: 'name', direction: 'ascending'},
+ ]);
+ });
+
+ it('regular click in multi-sort mode replaces entire sort', async () => {
+ const onSortChange = vi.fn();
+ render(
+ <SortableTable
+ initialSort={[
+ {sortKey: 'name', direction: 'ascending'},
+ {sortKey: 'age', direction: 'descending'},
+ ]}
+ isMultiSortEnabled
+ onSortChange={onSortChange}
+ />,
+ );
+
+ await userEvent.click(screen.getByRole('button', {name: /sort by age/i}));
+
+ expect(onSortChange).toHaveBeenCalledWith([
+ {sortKey: 'age', direction: 'ascending'},
+ ]);
+ });
+
+ it('clicking non-sortable column header does nothing', () => {
+ const onSortChange = vi.fn();
+ render(<SortableTable onSortChange={onSortChange} />);
+
+ // Email column header text should exist but not as a button
+ expect(
+ screen.queryByRole('button', {name: /sort by email/i}),
+ ).not.toBeInTheDocument();
+ expect(onSortChange).not.toHaveBeenCalled();
+ });
+ });
+
+ // =============================================================================
+ // Accessibility Tests
+ // =============================================================================
+
+ describe('accessibility', () => {
+ it('sets aria-sort="ascending" on sorted ascending th', () => {
+ render(
+ <SortableTable
+ initialSort={[{sortKey: 'name', direction: 'ascending'}]}
+ />,
+ );
+
+ const headers = screen.getAllByRole('columnheader');
+ const nameHeader = headers.find(h => h.textContent?.includes('Name'));
+ expect(nameHeader).toHaveAttribute('aria-sort', 'ascending');
+ });
+
+ it('sets aria-sort="descending" on sorted descending th', () => {
+ render(
+ <SortableTable
+ initialSort={[{sortKey: 'name', direction: 'descending'}]}
+ />,
+ );
+
+ const headers = screen.getAllByRole('columnheader');
+ const nameHeader = headers.find(h => h.textContent?.includes('Name'));
+ expect(nameHeader).toHaveAttribute('aria-sort', 'descending');
+ });
+
+ it('does not set aria-sort on unsorted columns', () => {
+ render(
+ <SortableTable
+ initialSort={[{sortKey: 'name', direction: 'ascending'}]}
+ />,
+ );
+
+ const headers = screen.getAllByRole('columnheader');
+ const ageHeader = headers.find(h => h.textContent?.includes('Age'));
+ expect(ageHeader).not.toHaveAttribute('aria-sort');
+ });
+
+ it('does not set aria-sort on non-sortable columns', () => {
+ render(
+ <SortableTable
+ initialSort={[{sortKey: 'name', direction: 'ascending'}]}
+ />,
+ );
+
+ const headers = screen.getAllByRole('columnheader');
+ const emailHeader = headers.find(h => h.textContent?.includes('Email'));
+ expect(emailHeader).not.toHaveAttribute('aria-sort');
+ });
+
+ it('sort button has accessible aria-label', () => {
+ render(
+ <SortableTable
+ initialSort={[{sortKey: 'name', direction: 'ascending'}]}
+ />,
+ );
+
+ expect(
+ screen.getByRole('button', {
+ name: 'Sort by Name, sorted ascending',
+ }),
+ ).toBeInTheDocument();
+ });
+
+ it('sort button is keyboard accessible (Enter)', async () => {
+ const onSortChange = vi.fn();
+ render(<SortableTable onSortChange={onSortChange} />);
+
+ const button = screen.getByRole('button', {name: /sort by name/i});
+ button.focus();
+ await userEvent.keyboard('{Enter}');
+
+ expect(onSortChange).toHaveBeenCalledWith([
+ {sortKey: 'name', direction: 'ascending'},
+ ]);
+ });
+
+ it('sort button is keyboard accessible (Space)', async () => {
+ const onSortChange = vi.fn();
+ render(<SortableTable onSortChange={onSortChange} />);
+
+ const button = screen.getByRole('button', {name: /sort by name/i});
+ button.focus();
+ await userEvent.keyboard(' ');
+
+ expect(onSortChange).toHaveBeenCalledWith([
+ {sortKey: 'name', direction: 'ascending'},
+ ]);
+ });
+
+ it('multi-sort aria-label includes priority', () => {
+ render(
+ <SortableTable
+ isMultiSortEnabled
+ initialSort={[
+ {sortKey: 'name', direction: 'ascending'},
+ {sortKey: 'age', direction: 'descending'},
+ ]}
+ />,
+ );
+
+ expect(
+ screen.getByRole('button', {
+ name: 'Sort by Name, sorted ascending, priority 1 of 2',
+ }),
+ ).toBeInTheDocument();
+ expect(
+ screen.getByRole('button', {
+ name: 'Sort by Age, sorted descending, priority 2 of 2',
+ }),
+ ).toBeInTheDocument();
+ });
+ });
+
+ // =============================================================================
+ // Edge Case Tests
+ // =============================================================================
+
+ describe('edge cases', () => {
+ it('handles sort state with key not matching any column', () => {
+ expect(() =>
+ render(
+ <SortableTable
+ initialSort={[{sortKey: 'nonexistent', direction: 'ascending'}]}
+ />,
+ ),
+ ).not.toThrow();
+ });
+
+ it('handles empty sort array', () => {
+ render(<SortableTable initialSort={[]} />);
+
+ // All sortable columns should show unsorted state
+ const nameButton = screen.getByRole('button', {name: 'Sort by Name'});
+ const ageButton = screen.getByRole('button', {name: 'Sort by Age'});
+ expect(nameButton).toBeInTheDocument();
+ expect(ageButton).toBeInTheDocument();
+ });
+
+ it('plugin object is referentially stable across renders', () => {
+ const plugins: ReturnType<typeof useXDSTableSortable>[] = [];
+
+ function Capture() {
+ const plugin = useXDSTableSortable<User>({
+ sort: [],
+ onSortChange: () => {},
+ });
+ plugins.push(plugin);
+ return null;
+ }
+
+ const {rerender} = render(<Capture />);
+ rerender(<Capture />);
+
+ expect(plugins[0]).toBe(plugins[1]);
+ });
+
+ it('works with no sortable columns', () => {
+ const columns: XDSTableColumn<User>[] = [
+ {key: 'name', header: 'Name'},
+ {key: 'age', header: 'Age'},
+ ];
+
+ expect(() => render(<SortableTable columns={columns} />)).not.toThrow();
+
+ expect(screen.queryByRole('button')).not.toBeInTheDocument();
+ });
+
+ it('works with ReactNode header content', () => {
+ const columns: XDSTableColumn<User>[] = [
+ {
+ key: 'name',
+ header: <span data-testid="custom-header">Custom Name</span>,
+ sortable: true,
+ },
+ ];
+
+ render(<SortableTable columns={columns} />);
+
+ const button = screen.getByRole('button', {name: /sort by name/i});
+ expect(button).toBeInTheDocument();
+ expect(screen.getByTestId('custom-header')).toBeInTheDocument();
+ });
+
+ it('sort state with multiple entries but isMultiSortEnabled=false', () => {
+ // State is source of truth — renders all entries even in single-sort mode
+ // but click behavior is single-sort
+ render(
+ <SortableTable
+ isMultiSortEnabled={false}
+ initialSort={[
+ {sortKey: 'name', direction: 'ascending'},
+ {sortKey: 'age', direction: 'descending'},
+ ]}
+ />,
+ );
+
+ // Both columns should show their sort state
+ const nameButton = screen.getByRole('button', {name: /sort by name/i});
+ const ageButton = screen.getByRole('button', {name: /sort by age/i});
+ expect(nameButton.getAttribute('aria-label')).toContain(
+ 'sorted ascending',
+ );
+ expect(ageButton.getAttribute('aria-label')).toContain(
+ 'sorted descending',
+ );
+ });
+ });
+});
diff --git a/packages/core/src/Table/plugins/sortable/useXDSTableSortable.tsx b/packages/core/src/Table/plugins/sortable/useXDSTableSortable.tsx
new file mode 100644
index 0000000000..bc7e04be30
--- /dev/null
+++ b/packages/core/src/Table/plugins/sortable/useXDSTableSortable.tsx
@@ -0,0 +1,377 @@
+'use client';
+
+/**
+ * @file useXDSTableSortable.tsx
+ * @input React, types, XDSIcon, theme tokens
+ * @output Exports useXDSTableSortable hook and sort-related types
+ * @position Sortable plugin; consumed by XDSTable via plugins prop
+ *
+ * SYNC: When modified, update these files to stay in sync:
+ * - /packages/core/src/Table/Table.doc.mjs (sort documentation)
+ * - /packages/core/src/Table/index.ts (exports)
+ */
+
+import {useRef, useMemo, type ReactNode} from 'react';
+import * as stylex from '@stylexjs/stylex';
+import {colorVars, spacingVars, radiusVars} from '../../../theme/tokens.stylex';
+import {XDSIcon} from '../../../Icon';
+import type {
+ TablePlugin,
+ HeaderCellRenderProps,
+ XDSTableColumn,
+} from '../../types';
+
+// =============================================================================
+// Sort Types
+// =============================================================================
+
+/**
+ * Sort direction for a single column.
+ */
+export type XDSTableSortDirection = 'ascending' | 'descending';
+
+/**
+ * A single sort entry in the sort state array.
+ */
+export interface XDSTableSortEntry<TSortKey extends string = string> {
+ /** The sort key identifying which column (or derived value) to sort by. */
+ sortKey: TSortKey;
+ /** The sort direction. */
+ direction: XDSTableSortDirection;
+}
+
+/**
+ * Complete sort state — an ordered array of sort entries.
+ * The first entry is the primary sort; subsequent entries are tiebreakers.
+ * Empty array = no sort applied.
+ *
+ * @example
+ * ```
+ * const sort: XDSTableSortState = [
+ * { sortKey: 'name', direction: 'ascending' },
+ * { sortKey: 'age', direction: 'descending' },
+ * ];
+ * ```
+ */
+export type XDSTableSortState<TSortKey extends string = string> =
+ XDSTableSortEntry<TSortKey>[];
+
+// =============================================================================
+// Hook Config
+// =============================================================================
+
+/**
+ * Configuration for useXDSTableSortable.
+ *
+ * Follows XDS headless plugin conventions: the consumer owns all state
+ * and provides callbacks. The plugin never holds internal sort state.
+ *
+ * @template TSortKey - Union of valid sort key strings
+ *
+ * @example
+ * ```
+ * const [sort, setSort] = useState<XDSTableSortState>([
+ * { sortKey: 'name', direction: 'ascending' },
+ * ]);
+ *
+ * const sortPlugin = useXDSTableSortable({
+ * sort,
+ * onSortChange: setSort,
+ * });
+ *
+ * <XDSTable plugins={{ sort: sortPlugin }} ... />
+ * ```
+ */
+export interface UseXDSTableSortableConfig<TSortKey extends string = string> {
+ /** Current sort state — ordered array of active sort entries. */
+ sort: XDSTableSortState<TSortKey>;
+
+ /**
+ * Called when the user changes sort via header click.
+ * Receives the complete new sort state array.
+ */
+ onSortChange: (sort: XDSTableSortState<TSortKey>) => void;
+
+ /**
+ * Allow returning to unsorted state.
+ * When true, clicking a sorted column cycles: asc → desc → unsorted.
+ * When false, clicking cycles: asc → desc → asc.
+ *
+ * @default false
+ */
+ allowUnsortedState?: boolean;
+
+ /**
+ * Enable multi-sort via modifier key (Shift+click).
+ * When true, Shift+click adds/toggles a column as a secondary sort.
+ * Regular click still replaces the entire sort state (single-sort behavior).
+ *
+ * @default false
+ */
+ isMultiSortEnabled?: boolean;
+}
+
+// =============================================================================
+// Styles
+// =============================================================================
+
+const sortStyles = stylex.create({
+ button: {
+ display: 'flex',
+ alignItems: 'center',
+ gap: spacingVars['--spacing-1'],
+ background: 'transparent',
+ border: 'none',
+ padding: 0,
+ margin: 0,
+ cursor: 'pointer',
+ font: 'inherit',
+ color: 'inherit',
+ width: '100%',
+ height: '100%',
+ textAlign: 'inherit',
+ outline: {
+ default: 'none',
+ ':focus-visible': `2px solid ${colorVars['--color-accent']}`,
+ },
+ outlineOffset: '2px',
+ borderRadius: radiusVars['--radius-inner'],
+ },
+ iconWrapperUnsorted: {
+ display: 'inline-flex',
+ opacity: 0,
+ [stylex.when.ancestor(':hover')]: {
+ opacity: 1,
+ },
+ [stylex.when.ancestor(':focus-within')]: {
+ opacity: 1,
+ },
+ },
+ iconWrapperActive: {
+ display: 'inline-flex',
+ },
+ rank: {
+ fontSize: 10,
+ // eslint-disable-next-line @xds/no-hardcoded-styles -- no token for lineHeight:1 (tight badge)
+ lineHeight: '1',
+ color: colorVars['--color-accent'],
+ },
+});
+
+// =============================================================================
+// Helpers
+// =============================================================================
+
+function resolveSortKey<T extends Record<string, unknown>>(
+ column: XDSTableColumn<T>,
+): string | null {
+ const {sortable} = column;
+ if (!sortable) return null;
+ if (sortable === true) return column.key;
+ return sortable.sortKey ?? column.key;
+}
+
+function getHeaderLabel<T extends Record<string, unknown>>(
+ column: XDSTableColumn<T>,
+): string {
+ const {header} = column;
+ if (typeof header === 'string') return header;
+ return column.key;
+}
+
+function buildAriaLabel<T extends Record<string, unknown>>(
+ column: XDSTableColumn<T>,
+ direction: XDSTableSortDirection | null,
+ rank: number | null,
+ total: number,
+): string {
+ const label = getHeaderLabel(column);
+ if (direction == null) {
+ return `Sort by ${label}`;
+ }
+ let ariaLabel = `Sort by ${label}, sorted ${direction}`;
+ if (rank != null && total > 1) {
+ ariaLabel += `, priority ${rank} of ${total}`;
+ }
+ return ariaLabel;
+}
+
+function getNextDirection(
+ current: XDSTableSortDirection | null,
+ allowUnsortedState: boolean,
+): XDSTableSortDirection | null {
+ if (current == null) return 'ascending';
+ if (current === 'ascending') return 'descending';
+ // current === 'descending'
+ return allowUnsortedState ? null : 'ascending';
+}
+
+// =============================================================================
+// Sort Header Button Component
+// =============================================================================
+
+function SortHeaderButton<T extends Record<string, unknown>>({
+ column,
+ children,
+ configRef,
+}: {
+ column: XDSTableColumn<T>;
+ children: ReactNode;
+ configRef: React.RefObject<UseXDSTableSortableConfig>;
+}) {
+ const config = configRef.current;
+ const sortKey = resolveSortKey(column)!;
+ const entryIndex = config.sort.findIndex(e => e.sortKey === sortKey);
+ const entry = entryIndex >= 0 ? config.sort[entryIndex] : null;
+ const direction = entry?.direction ?? null;
+
+ const isMultiSort =
+ config.isMultiSortEnabled === true && config.sort.length > 1;
+ const rank = isMultiSort && entryIndex >= 0 ? entryIndex + 1 : null;
+
+ const iconName =
+ direction === 'ascending'
+ ? 'arrowUp'
+ : direction === 'descending'
+ ? 'arrowDown'
+ : 'arrowsUpDown';
+
+ const ariaLabel = buildAriaLabel(column, direction, rank, config.sort.length);
+
+ const handleClick = (e: React.MouseEvent | React.KeyboardEvent) => {
+ const cfg = configRef.current;
+ const isShift = e.shiftKey && cfg.isMultiSortEnabled;
+ const allowUnsorted = cfg.allowUnsortedState ?? false;
+
+ if (isShift) {
+ // Multi-sort: toggle in place or append
+ const idx = cfg.sort.findIndex(s => s.sortKey === sortKey);
+ if (idx >= 0) {
+ const nextDir = getNextDirection(
+ cfg.sort[idx].direction,
+ allowUnsorted,
+ );
+ if (nextDir == null) {
+ // Remove from array
+ const newSort = [...cfg.sort];
+ newSort.splice(idx, 1);
+ cfg.onSortChange(newSort);
+ } else {
+ const newSort = [...cfg.sort];
+ newSort[idx] = {...newSort[idx], direction: nextDir};
+ cfg.onSortChange(newSort);
+ }
+ } else {
+ // Append new entry
+ cfg.onSortChange([...cfg.sort, {sortKey, direction: 'ascending'}]);
+ }
+ } else {
+ // Single-sort: replace entire array
+ const currentEntry = cfg.sort.find(s => s.sortKey === sortKey);
+ const nextDir = getNextDirection(
+ currentEntry?.direction ?? null,
+ allowUnsorted,
+ );
+ if (nextDir == null) {
+ cfg.onSortChange([]);
+ } else {
+ cfg.onSortChange([{sortKey, direction: nextDir}]);
+ }
+ }
+ };
+
+ return (
+ <button
+ type="button"
+ {...stylex.props(sortStyles.button)}
+ aria-label={ariaLabel}
+ onClick={handleClick}>
+ <span>{children}</span>
+ <span
+ {...stylex.props(
+ direction != null
+ ? sortStyles.iconWrapperActive
+ : sortStyles.iconWrapperUnsorted,
+ )}>
+ <XDSIcon
+ icon={iconName}
+ size="xsm"
+ color={direction != null ? 'accent' : 'secondary'}
+ />
+ </span>
+ {rank != null && (
+ <span {...stylex.props(sortStyles.rank)} aria-hidden="true">
+ {rank}
+ </span>
+ )}
+ </button>
+ );
+}
+
+// =============================================================================
+// Hook
+// =============================================================================
+
+/**
+ * useXDSTableSortable — table plugin for column sorting.
+ *
+ * Returns a stable TablePlugin<T> that transforms header cells to add
+ * clickable sort indicators. Follows the headless pattern: consumer owns
+ * sort state, plugin provides UI and interaction.
+ *
+ * @example
+ * ```
+ * const [sort, setSort] = useState<XDSTableSortState>([]);
+ * const sortPlugin = useXDSTableSortable({ sort, onSortChange: setSort });
+ *
+ * <XDSTable
+ * data={users}
+ * columns={[
+ * { key: 'name', header: 'Name', sortable: true },
+ * { key: 'age', header: 'Age', sortable: true },
+ * ]}
+ * plugins={{ sort: sortPlugin }}
+ * />
+ * ```
+ */
+export function useXDSTableSortable<
+ T extends Record<string, unknown>,
+ TSortKey extends string = string,
+>(config: UseXDSTableSortableConfig<TSortKey>): TablePlugin<T> {
+ const configRef = useRef(config);
+ configRef.current = config;
+
+ return useMemo(
+ (): TablePlugin<T> => ({
+ transformHeaderCell(
+ props: HeaderCellRenderProps,
+ column: XDSTableColumn<T>,
+ ): HeaderCellRenderProps {
+ const sortKey = resolveSortKey(column);
+ if (sortKey == null) return props;
+
+ // Find sort entry for this column
+ const cfg = configRef.current;
+ const entry = cfg.sort.find(e => e.sortKey === sortKey);
+
+ return {
+ ...props,
+ htmlProps: {
+ ...props.htmlProps,
+ ...(entry != null ? {'aria-sort': entry.direction} : {}),
+ },
+ content: (
+ <SortHeaderButton
+ column={column}
+ configRef={
+ configRef as unknown as React.RefObject<UseXDSTableSortableConfig>
+ }>
+ {props.content}
+ </SortHeaderButton>
+ ),
+ };
+ },
+ }),
+ [],
+ );
+}
diff --git a/packages/core/src/Table/types.ts b/packages/core/src/Table/types.ts
index 287e880cab..b27cb5df07 100644
--- a/packages/core/src/Table/types.ts
+++ b/packages/core/src/Table/types.ts
@@ -45,6 +45,25 @@ export interface PixelWidth {
/** Column width — either proportional or fixed pixel */
export type ColumnWidth = ProportionalWidth | PixelWidth;
+// =============================================================================
+// Sortable Column Config
+// =============================================================================
+
+/**
+ * Sortable column configuration.
+ * Added to XDSTableColumn<T> via the `sortable` field.
+ */
+export interface XDSTableSortableColumnConfig {
+ /**
+ * The sort key for this column. Must match a key used in XDSTableSortState.
+ * Allows decoupling column identity from sort identity (e.g., a "Full Name"
+ * column might sort by `'lastName'`).
+ *
+ * @default column.key — if omitted, uses the column's `key` property
+ */
+ sortKey?: string;
+}
+
// =============================================================================
// Column Definition
// =============================================================================
@@ -61,6 +80,22 @@ export interface XDSTableColumn<T extends Record<string, unknown>> {
header?: ReactNode;
/** Column width. Defaults to `proportional(1)`. */
width?: ColumnWidth;
+ /**
+ * Sortable configuration for this column.
+ * Set to `true` for default behavior (sortKey = column.key),
+ * or provide an object with a custom sortKey.
+ * Omit or set to `undefined`/`false` to make the column non-sortable.
+ *
+ * @example
+ * ```
+ * // Simple: sort key matches column key
+ * { key: 'name', header: 'Name', sortable: true }
+ *
+ * // Custom sort key
+ * { key: 'fullName', header: 'Full Name', sortable: { sortKey: 'lastName' } }
+ * ```
+ */
+ sortable?: boolean | XDSTableSortableColumnConfig;
/**
* Custom cell renderer. Receives the row item and returns rich JSX content.
* Defaults to `String(item[key])` — use renderCell for rich content like