Skip to content

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

TypeScript

feat(Table): add useXDSTableSelectionState helper for managed selection (#1005)

Cindy Zhang3881c2825e4e
diff --git a/apps/storybook/stories/TableSelection.stories.tsx b/apps/storybook/stories/TableSelection.stories.tsx
index 735857ca8b..32a4eae6b9 100644
--- a/apps/storybook/stories/TableSelection.stories.tsx
+++ b/apps/storybook/stories/TableSelection.stories.tsx
@@ -1,6 +1,10 @@
-import {useState, useMemo} from 'react';
+import {useState} from 'react';
import type {Meta, StoryObj} from '@storybook/react';
-import {XDSTable, useXDSTableSelection} from '@xds/core/Table';
+import {
+ XDSTable,
+ useXDSTableSelection,
+ useXDSTableSelectionState,
+} from '@xds/core/Table';
import type {XDSTableColumn} from '@xds/core/Table';
// =============================================================================
@@ -75,29 +79,13 @@ export const Default: Story = {
render: () => {
const [selectedKeys, setSelectedKeys] = useState<Set<string>>(new Set());
- const selectionPlugin = useXDSTableSelection<User>({
- getIsItemSelected: item => selectedKeys.has(item.id),
- onSelectItem: ({item, isSelected}) => {
- const next = new Set(selectedKeys);
- if (isSelected) {
- next.add(item.id);
- } else {
- next.delete(item.id);
- }
- setSelectedKeys(next);
- },
- onSelectAll: ({isAllSelected}) => {
- setSelectedKeys(
- isAllSelected ? new Set(users.map(u => u.id)) : new Set(),
- );
- },
- getIsAllSelected: () =>
- users.length > 0 && users.every(u => selectedKeys.has(u.id)),
- getIsIndeterminate: () => {
- const count = users.filter(u => selectedKeys.has(u.id)).length;
- return count > 0 && count < users.length;
- },
+ const {selectionConfig} = useXDSTableSelectionState<User>({
+ data: users,
+ idKey: 'id',
+ selectedKeys,
+ setSelectedKeys,
});
+ const selectionPlugin = useXDSTableSelection<User>(selectionConfig);
return (
<div style={{maxWidth: 600}}>
@@ -121,29 +109,13 @@ export const WithPreselection: Story = {
new Set(['1', '3']),
);
- const selectionPlugin = useXDSTableSelection<User>({
- getIsItemSelected: item => selectedKeys.has(item.id),
- onSelectItem: ({item, isSelected}) => {
- const next = new Set(selectedKeys);
- if (isSelected) {
- next.add(item.id);
- } else {
- next.delete(item.id);
- }
- setSelectedKeys(next);
- },
- onSelectAll: ({isAllSelected}) => {
- setSelectedKeys(
- isAllSelected ? new Set(users.map(u => u.id)) : new Set(),
- );
- },
- getIsAllSelected: () =>
- users.length > 0 && users.every(u => selectedKeys.has(u.id)),
- getIsIndeterminate: () => {
- const count = users.filter(u => selectedKeys.has(u.id)).length;
- return count > 0 && count < users.length;
- },
+ const {selectionConfig} = useXDSTableSelectionState<User>({
+ data: users,
+ idKey: 'id',
+ selectedKeys,
+ setSelectedKeys,
});
+ const selectionPlugin = useXDSTableSelection<User>(selectionConfig);
return (
<div style={{maxWidth: 600}}>
@@ -165,38 +137,14 @@ export const NonSelectableRows: Story = {
render: () => {
const [selectedKeys, setSelectedKeys] = useState<Set<string>>(new Set());
- const selectableUsers = useMemo(
- () => users.filter(u => u.role !== 'Admin'),
- [],
- );
-
- const selectionPlugin = useXDSTableSelection<User>({
- getIsItemSelected: item => selectedKeys.has(item.id),
- onSelectItem: ({item, isSelected}) => {
- const next = new Set(selectedKeys);
- if (isSelected) {
- next.add(item.id);
- } else {
- next.delete(item.id);
- }
- setSelectedKeys(next);
- },
- onSelectAll: ({isAllSelected}) => {
- setSelectedKeys(
- isAllSelected ? new Set(selectableUsers.map(u => u.id)) : new Set(),
- );
- },
- getIsAllSelected: () =>
- selectableUsers.length > 0 &&
- selectableUsers.every(u => selectedKeys.has(u.id)),
- getIsIndeterminate: () => {
- const count = selectableUsers.filter(u =>
- selectedKeys.has(u.id),
- ).length;
- return count > 0 && count < selectableUsers.length;
- },
+ const {selectionConfig} = useXDSTableSelectionState<User>({
+ data: users,
+ idKey: 'id',
+ selectedKeys,
+ setSelectedKeys,
getIsItemSelectable: item => item.role !== 'Admin',
});
+ const selectionPlugin = useXDSTableSelection<User>(selectionConfig);
return (
<div style={{maxWidth: 600}}>
@@ -218,36 +166,20 @@ export const DisabledRows: Story = {
render: () => {
const [selectedKeys, setSelectedKeys] = useState<Set<string>>(new Set());
- const selectionPlugin = useXDSTableSelection<User>({
- getIsItemSelected: item => selectedKeys.has(item.id),
- onSelectItem: ({item, isSelected}) => {
- const next = new Set(selectedKeys);
- if (isSelected) {
- next.add(item.id);
- } else {
- next.delete(item.id);
- }
- setSelectedKeys(next);
- },
- onSelectAll: ({isAllSelected}) => {
- setSelectedKeys(
- isAllSelected ? new Set(users.map(u => u.id)) : new Set(),
- );
- },
- getIsAllSelected: () =>
- users.length > 0 && users.every(u => selectedKeys.has(u.id)),
- getIsIndeterminate: () => {
- const count = users.filter(u => selectedKeys.has(u.id)).length;
- return count > 0 && count < users.length;
- },
+ const {selectionConfig} = useXDSTableSelectionState<User>({
+ data: users,
+ idKey: 'id',
+ selectedKeys,
+ setSelectedKeys,
getIsItemEnabled: item => !item.isLocked,
});
+ const selectionPlugin = useXDSTableSelection<User>(selectionConfig);
return (
<div style={{maxWidth: 600}}>
<p style={{marginBottom: 8, fontSize: 14, color: '#666'}}>
- Locked rows (Diana) have a disabled checkbox. Selected:{' '}
- {selectedKeys.size}
+ Locked rows (Diana) have a disabled checkbox. Select-all skips them.
+ Selected: {selectedKeys.size}
</p>
<XDSTable
data={users}
@@ -264,29 +196,13 @@ export const Compact: Story = {
render: () => {
const [selectedKeys, setSelectedKeys] = useState<Set<string>>(new Set());
- const selectionPlugin = useXDSTableSelection<User>({
- getIsItemSelected: item => selectedKeys.has(item.id),
- onSelectItem: ({item, isSelected}) => {
- const next = new Set(selectedKeys);
- if (isSelected) {
- next.add(item.id);
- } else {
- next.delete(item.id);
- }
- setSelectedKeys(next);
- },
- onSelectAll: ({isAllSelected}) => {
- setSelectedKeys(
- isAllSelected ? new Set(users.map(u => u.id)) : new Set(),
- );
- },
- getIsAllSelected: () =>
- users.length > 0 && users.every(u => selectedKeys.has(u.id)),
- getIsIndeterminate: () => {
- const count = users.filter(u => selectedKeys.has(u.id)).length;
- return count > 0 && count < users.length;
- },
+ const {selectionConfig} = useXDSTableSelectionState<User>({
+ data: users,
+ idKey: 'id',
+ selectedKeys,
+ setSelectedKeys,
});
+ const selectionPlugin = useXDSTableSelection<User>(selectionConfig);
return (
<div style={{maxWidth: 600}}>
@@ -306,29 +222,13 @@ export const Spacious: Story = {
render: () => {
const [selectedKeys, setSelectedKeys] = useState<Set<string>>(new Set());
- const selectionPlugin = useXDSTableSelection<User>({
- getIsItemSelected: item => selectedKeys.has(item.id),
- onSelectItem: ({item, isSelected}) => {
- const next = new Set(selectedKeys);
- if (isSelected) {
- next.add(item.id);
- } else {
- next.delete(item.id);
- }
- setSelectedKeys(next);
- },
- onSelectAll: ({isAllSelected}) => {
- setSelectedKeys(
- isAllSelected ? new Set(users.map(u => u.id)) : new Set(),
- );
- },
- getIsAllSelected: () =>
- users.length > 0 && users.every(u => selectedKeys.has(u.id)),
- getIsIndeterminate: () => {
- const count = users.filter(u => selectedKeys.has(u.id)).length;
- return count > 0 && count < users.length;
- },
+ const {selectionConfig} = useXDSTableSelectionState<User>({
+ data: users,
+ idKey: 'id',
+ selectedKeys,
+ setSelectedKeys,
});
+ const selectionPlugin = useXDSTableSelection<User>(selectionConfig);
return (
<div style={{maxWidth: 600}}>
@@ -349,29 +249,13 @@ export const WithStripedRows: Story = {
render: () => {
const [selectedKeys, setSelectedKeys] = useState<Set<string>>(new Set());
- const selectionPlugin = useXDSTableSelection<User>({
- getIsItemSelected: item => selectedKeys.has(item.id),
- onSelectItem: ({item, isSelected}) => {
- const next = new Set(selectedKeys);
- if (isSelected) {
- next.add(item.id);
- } else {
- next.delete(item.id);
- }
- setSelectedKeys(next);
- },
- onSelectAll: ({isAllSelected}) => {
- setSelectedKeys(
- isAllSelected ? new Set(users.map(u => u.id)) : new Set(),
- );
- },
- getIsAllSelected: () =>
- users.length > 0 && users.every(u => selectedKeys.has(u.id)),
- getIsIndeterminate: () => {
- const count = users.filter(u => selectedKeys.has(u.id)).length;
- return count > 0 && count < users.length;
- },
+ const {selectionConfig} = useXDSTableSelectionState<User>({
+ data: users,
+ idKey: 'id',
+ selectedKeys,
+ setSelectedKeys,
});
+ const selectionPlugin = useXDSTableSelection<User>(selectionConfig);
return (
<div style={{maxWidth: 600}}>
diff --git a/packages/core/src/Table/Table.doc.mjs b/packages/core/src/Table/Table.doc.mjs
index 67f9347ac6..30198bde2b 100644
--- a/packages/core/src/Table/Table.doc.mjs
+++ b/packages/core/src/Table/Table.doc.mjs
@@ -12,7 +12,7 @@ export const docs = {
'Density variants: compact, balanced, spacious',
'Divider styles: rows, columns, grid, none',
'Striped even rows and hover highlight via XDSTableContext',
- 'Selection via useXDSTableSelection — checkboxes, select-all, aria-selected',
+ 'Selection via useXDSTableSelectionState + useXDSTableSelection — checkboxes, select-all, disabled row handling',
'Body rows memoized with custom comparison — only changed rows re-render',
'Auto-generated columns from data object keys when columns prop is omitted',
'Themeable via className — target .xds-base-table, .xds-table-row, .xds-table-cell, .xds-table-header-cell',
@@ -142,22 +142,13 @@ export const docs = {
label: 'Selection plugin',
code: `const [selectedKeys, setSelectedKeys] = useState<Set<string>>(new Set());
-const selectionPlugin = useXDSTableSelection<User>({
- getIsItemSelected: item => selectedKeys.has(item.id),
- onSelectItem: ({item, isSelected}) => {
- const next = new Set(selectedKeys);
- isSelected ? next.add(item.id) : next.delete(item.id);
- setSelectedKeys(next);
- },
- onSelectAll: ({isAllSelected}) => {
- setSelectedKeys(isAllSelected ? new Set(users.map(u => u.id)) : new Set());
- },
- getIsAllSelected: () => users.every(u => selectedKeys.has(u.id)),
- getIsIndeterminate: () => {
- const count = users.filter(u => selectedKeys.has(u.id)).length;
- return count > 0 && count < users.length;
- },
+const {selectionConfig} = useXDSTableSelectionState<User>({
+ data: users,
+ idKey: 'id',
+ selectedKeys,
+ setSelectedKeys,
});
+const selectionPlugin = useXDSTableSelection<User>(selectionConfig);
<XDSTable
data={users}
@@ -197,7 +188,7 @@ const selectionPlugin = useXDSTableSelection<User>({
'Two-layer design: XDSBaseTable provides unstyled structure and the plugin pipeline; XDSTable wraps it with XDSTableContext and styled sub-components.',
'Styling is owned by components (XDSTableRow, XDSTableCell, XDSTableHeaderCell), not by plugins — each reads XDSTableContext to apply density, dividers, striped, and hover styles.',
'XDSTable accepts plugins as a named Record<string, TablePlugin<T>> and converts to an ordered array internally; XDSBaseTable accepts an ordered array directly.',
- 'The selection plugin uses React Context so SelectAllCheckbox and SelectionRowCheckbox re-render independently from row content — only the context value updates when selection state changes.',
+ 'The selection plugin uses useSyncExternalStore so only the row whose selection state changed re-renders. useXDSTableSelectionState manages the selection set and handles disabled/selectable row filtering for select-all automatically.',
'Body rows are memoized via React.memo with a custom comparison. For optimal performance, define columns outside the component or memoize them to avoid triggering full re-renders.',
'Columns can be auto-generated from data keys using generateColumns(); column widths are expressed as proportional (fr-like) or fixed pixel values via the proportional() and pixel() helpers.',
'tableProps on XDSBaseTable passes additional HTML attributes directly to the <table> element.',
@@ -466,23 +457,83 @@ const selectionPlugin = useXDSTableSelection<User>({
label: 'Basic selection',
code: `const [selectedKeys, setSelectedKeys] = useState<Set<string>>(new Set());
-const selectionPlugin = useXDSTableSelection<User>({
- getIsItemSelected: item => selectedKeys.has(item.id),
- onSelectItem: ({item, isSelected}) => {
- const next = new Set(selectedKeys);
- isSelected ? next.add(item.id) : next.delete(item.id);
- setSelectedKeys(next);
- },
- onSelectAll: ({isAllSelected}) => {
- setSelectedKeys(isAllSelected ? new Set(users.map(u => u.id)) : new Set());
- },
- getIsAllSelected: () => users.every(u => selectedKeys.has(u.id)),
- getIsIndeterminate: () => {
- const count = users.filter(u => selectedKeys.has(u.id)).length;
- return count > 0 && count < users.length;
- },
+const {selectionConfig} = useXDSTableSelectionState<User>({
+ data: users,
+ idKey: 'id',
+ selectedKeys,
+ setSelectedKeys,
+});
+const selectionPlugin = useXDSTableSelection<User>(selectionConfig);
+
+<XDSTable
+ data={users}
+ columns={columns}
+ plugins={{selection: selectionPlugin}}
+/>`,
+ },
+ ],
+ },
+ {
+ name: 'useXDSTableSelectionState',
+ description:
+ 'State management companion for useXDSTableSelection. Handles disabled/selectable row filtering for select-all automatically — disabled rows are frozen (preserved across select-all/deselect-all), non-selectable rows are excluded.',
+ props: [
+ {
+ name: 'data',
+ type: 'T[]',
+ description: 'The full data array rendered in the table.',
+ required: true,
+ },
+ {
+ name: 'idKey',
+ type: '(keyof T & string) | ((item: T) => string)',
+ description:
+ 'Key extractor — property name or function returning a unique string ID.',
+ required: true,
+ },
+ {
+ name: 'selectedKeys',
+ type: 'Set<string>',
+ description: 'Controlled set of selected item IDs.',
+ required: true,
+ },
+ {
+ name: 'setSelectedKeys',
+ type: 'Dispatch<SetStateAction<Set<string>>>',
+ description: 'Setter for the controlled selected keys.',
+ required: true,
+ },
+ {
+ name: 'getIsItemSelectable',
+ type: '(item: T) => boolean',
+ description:
+ 'Should this row show a checkbox? Non-selectable rows are excluded from select-all.',
+ default: '() => true',
+ },
+ {
+ name: 'getIsItemEnabled',
+ type: '(item: T) => boolean',
+ description:
+ 'Is this row checkbox interactive? Disabled rows are frozen — select-all preserves their state.',
+ default: '() => true',
+ },
+ ],
+ examples: [
+ {
+ label: 'With disabled rows',
+ code: `const [selectedKeys, setSelectedKeys] = useState<Set<string>>(new Set());
+
+const {selectionConfig} = useXDSTableSelectionState<User>({
+ data: users,
+ idKey: 'id',
+ selectedKeys,
+ setSelectedKeys,
+ getIsItemEnabled: item => !item.isLocked,
});
+const selectionPlugin = useXDSTableSelection<User>(selectionConfig);
+// Select-all skips locked rows. A locked row that was
+// previously selected stays selected (frozen).
<XDSTable
data={users}
columns={columns}
@@ -637,22 +688,13 @@ export const docsZh = {
label: '选择插件',
code: `const [selectedKeys, setSelectedKeys] = useState<Set<string>>(new Set());
-const selectionPlugin = useXDSTableSelection<User>({
- getIsItemSelected: item => selectedKeys.has(item.id),
- onSelectItem: ({item, isSelected}) => {
- const next = new Set(selectedKeys);
- isSelected ? next.add(item.id) : next.delete(item.id);
- setSelectedKeys(next);
- },
- onSelectAll: ({isAllSelected}) => {
- setSelectedKeys(isAllSelected ? new Set(users.map(u => u.id)) : new Set());
- },
- getIsAllSelected: () => users.every(u => selectedKeys.has(u.id)),
- getIsIndeterminate: () => {
- const count = users.filter(u => selectedKeys.has(u.id)).length;
- return count > 0 && count < users.length;
- },
+const {selectionConfig} = useXDSTableSelectionState<User>({
+ data: users,
+ idKey: 'id',
+ selectedKeys,
+ setSelectedKeys,
});
+const selectionPlugin = useXDSTableSelection<User>(selectionConfig);
<XDSTable
data={users}
@@ -961,22 +1003,13 @@ const selectionPlugin = useXDSTableSelection<User>({
label: '基础选择',
code: `const [selectedKeys, setSelectedKeys] = useState<Set<string>>(new Set());
-const selectionPlugin = useXDSTableSelection<User>({
- getIsItemSelected: item => selectedKeys.has(item.id),
- onSelectItem: ({item, isSelected}) => {
- const next = new Set(selectedKeys);
- isSelected ? next.add(item.id) : next.delete(item.id);
- setSelectedKeys(next);
- },
- onSelectAll: ({isAllSelected}) => {
- setSelectedKeys(isAllSelected ? new Set(users.map(u => u.id)) : new Set());
- },
- getIsAllSelected: () => users.every(u => selectedKeys.has(u.id)),
- getIsIndeterminate: () => {
- const count = users.filter(u => selectedKeys.has(u.id)).length;
- return count > 0 && count < users.length;
- },
+const {selectionConfig} = useXDSTableSelectionState<User>({
+ data: users,
+ idKey: 'id',
+ selectedKeys,
+ setSelectedKeys,
});
+const selectionPlugin = useXDSTableSelection<User>(selectionConfig);
<XDSTable
data={users}
@@ -1000,7 +1033,7 @@ export const docsDense = {
'Density variants: compact, balanced, spacious',
'Divider styles: rows, columns, grid, none',
'Striped even rows + hover highlight via XDSTableContext',
- 'Selection via useXDSTableSelection; checkboxes, select-all, aria-selected',
+ 'Selection via useXDSTableSelectionState + useXDSTableSelection — checkboxes, select-all, disabled row handling',
'Body rows memoized w/ custom comparison; only changed rows re-render',
'Auto-generated columns from data object keys when columns omitted',
'Themeable via className; target .xds-base-table, .xds-table-row, .xds-table-cell, .xds-table-header-cell',
diff --git a/packages/core/src/Table/index.ts b/packages/core/src/Table/index.ts
index 4eea9202cf..577da692bc 100644
--- a/packages/core/src/Table/index.ts
+++ b/packages/core/src/Table/index.ts
@@ -16,6 +16,7 @@ export {XDSTableCell} from './XDSTableCell';
export {XDSTableHeaderCell} from './XDSTableHeaderCell';
export {XDSTableContext} from './XDSTableContext';
export {useXDSTableSelection} from './plugins/selection';
+export {useXDSTableSelectionState} from './plugins/selection';
export {useXDSBaseTablePlugins} from './useXDSBaseTablePlugins';
export {
proportional,
@@ -49,3 +50,7 @@ export type {XDSTableCellProps} from './XDSTableCell';
export type {XDSTableHeaderCellProps} from './XDSTableHeaderCell';
export type {XDSTableContextValue} from './XDSTableContext';
export type {UseXDSTableSelectionConfig} from './plugins/selection';
+export type {
+ UseXDSTableSelectionStateConfig,
+ UseXDSTableSelectionStateResult,
+} from './plugins/selection';
diff --git a/packages/core/src/Table/plugins/selection/index.ts b/packages/core/src/Table/plugins/selection/index.ts
index 372771cc43..0232fd92e3 100644
--- a/packages/core/src/Table/plugins/selection/index.ts
+++ b/packages/core/src/Table/plugins/selection/index.ts
@@ -1,2 +1,7 @@
export {useXDSTableSelection} from './useXDSTableSelection';
export type {UseXDSTableSelectionConfig} from './useXDSTableSelection';
+export {useXDSTableSelectionState} from './useXDSTableSelectionState';
+export type {
+ UseXDSTableSelectionStateConfig,
+ UseXDSTableSelectionStateResult,
+} from './useXDSTableSelectionState';
diff --git a/packages/core/src/Table/plugins/selection/useXDSTableSelectionState.test.tsx b/packages/core/src/Table/plugins/selection/useXDSTableSelectionState.test.tsx
new file mode 100644
index 0000000000..091979a551
--- /dev/null
+++ b/packages/core/src/Table/plugins/selection/useXDSTableSelectionState.test.tsx
@@ -0,0 +1,227 @@
+/**
+ * @file useXDSTableSelectionState.test.tsx
+ * @input useXDSTableSelectionState, useXDSTableSelection, XDSTable, React testing utilities
+ * @output Tests for the selection state helper
+ * @position Test file; validates disabled/selectable filtering in select-all
+ */
+
+import {describe, it, expect} from 'vitest';
+import {useState} from 'react';
+import {render, screen} from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+import {XDSTable} from '../../XDSTable';
+import {useXDSTableSelection} from './useXDSTableSelection';
+import {useXDSTableSelectionState} from './useXDSTableSelectionState';
+import type {XDSTableColumn} from '../../types';
+
+// =============================================================================
+// Test Data
+// =============================================================================
+
+interface TestItem extends Record<string, unknown> {
+ id: string;
+ name: string;
+ isLocked: boolean;
+ isHidden: boolean;
+}
+
+const testData: TestItem[] = [
+ {id: '1', name: 'Alice', isLocked: false, isHidden: false},
+ {id: '2', name: 'Bob', isLocked: false, isHidden: false},
+ {id: '3', name: 'Charlie', isLocked: true, isHidden: false},
+ {id: '4', name: 'Diana', isLocked: false, isHidden: true},
+];
+
+const columns: XDSTableColumn<TestItem>[] = [{key: 'name', header: 'Name'}];
+
+// =============================================================================
+// Helper
+// =============================================================================
+
+function StateHelperTable({
+ data = testData,
+ getIsItemEnabled,
+ getIsItemSelectable,
+ initialSelected = new Set<string>(),
+}: {
+ data?: TestItem[];
+ getIsItemEnabled?: (item: TestItem) => boolean;
+ getIsItemSelectable?: (item: TestItem) => boolean;
+ initialSelected?: Set<string>;
+}) {
+ const [selectedKeys, setSelectedKeys] =
+ useState<Set<string>>(initialSelected);
+
+ const {selectionConfig} = useXDSTableSelectionState<TestItem>({
+ data,
+ idKey: 'id',
+ selectedKeys,
+ setSelectedKeys,
+ getIsItemEnabled,
+ getIsItemSelectable,
+ });
+
+ const plugin = useXDSTableSelection<TestItem>(selectionConfig);
+
+ return (
+ <XDSTable
+ data={data}
+ columns={columns}
+ idKey="id"
+ plugins={{selection: plugin}}
+ />
+ );
+}
+
+// =============================================================================
+// Tests
+// =============================================================================
+
+describe('useXDSTableSelectionState', () => {
+ it('select-all selects only enabled items', async () => {
+ const user = userEvent.setup();
+ render(<StateHelperTable getIsItemEnabled={item => !item.isLocked} />);
+
+ await user.click(screen.getByLabelText('Select all rows'));
+
+ const rows = screen.getAllByRole('row');
+ // Alice, Bob, Diana selected (enabled)
+ expect(rows[1]).toHaveAttribute('aria-selected', 'true');
+ expect(rows[2]).toHaveAttribute('aria-selected', 'true');
+ // Charlie disabled — NOT selected
+ expect(rows[3]).not.toHaveAttribute('aria-selected');
+ // Diana enabled
+ expect(rows[4]).toHaveAttribute('aria-selected', 'true');
+ });
+
+ it('select-all preserves disabled-but-selected items', async () => {
+ const user = userEvent.setup();
+ // Charlie (id: 3) starts selected but is disabled
+ render(
+ <StateHelperTable
+ getIsItemEnabled={item => !item.isLocked}
+ initialSelected={new Set(['3'])}
+ />,
+ );
+
+ const rows = screen.getAllByRole('row');
+ // Charlie should be selected (was selected before becoming disabled)
+ expect(rows[3]).toHaveAttribute('aria-selected', 'true');
+
+ // Select all — Charlie should stay selected, others get selected
+ await user.click(screen.getByLabelText('Select all rows'));
+
+ expect(rows[1]).toHaveAttribute('aria-selected', 'true');
+ expect(rows[2]).toHaveAttribute('aria-selected', 'true');
+ expect(rows[3]).toHaveAttribute('aria-selected', 'true'); // preserved
+ expect(rows[4]).toHaveAttribute('aria-selected', 'true');
+ });
+
+ it('deselect-all preserves disabled-but-selected items', async () => {
+ const user = userEvent.setup();
+ // Charlie (id: 3) starts selected but is disabled
+ // Alice (id: 1) also starts selected
+ render(
+ <StateHelperTable
+ getIsItemEnabled={item => !item.isLocked}
+ initialSelected={new Set(['1', '3'])}
+ />,
+ );
+
+ // Click select-all first to select all enabled
+ await user.click(screen.getByLabelText('Select all rows'));
+ // Now deselect all
+ await user.click(screen.getByLabelText('Select all rows'));
+
+ const rows = screen.getAllByRole('row');
+ // Enabled items deselected
+ expect(rows[1]).not.toHaveAttribute('aria-selected');
+ expect(rows[2]).not.toHaveAttribute('aria-selected');
+ // Charlie (disabled) stays selected
+ expect(rows[3]).toHaveAttribute('aria-selected', 'true');
+ expect(rows[4]).not.toHaveAttribute('aria-selected');
+ });
+
+ it('non-selectable items are excluded from select-all', async () => {
+ const user = userEvent.setup();
+ render(<StateHelperTable getIsItemSelectable={item => !item.isHidden} />);
+
+ await user.click(screen.getByLabelText('Select all rows'));
+
+ const rows = screen.getAllByRole('row');
+ expect(rows[1]).toHaveAttribute('aria-selected', 'true');
+ expect(rows[2]).toHaveAttribute('aria-selected', 'true');
+ expect(rows[3]).toHaveAttribute('aria-selected', 'true');
+ // Diana (non-selectable) — NOT selected
+ expect(rows[4]).not.toHaveAttribute('aria-selected');
+ });
+
+ it('deselect-all does not affect non-selectable items', async () => {
+ const user = userEvent.setup();
+ // Diana (id: 4, hidden/non-selectable) starts selected somehow
+ render(
+ <StateHelperTable
+ getIsItemSelectable={item => !item.isHidden}
+ initialSelected={new Set(['4'])}
+ />,
+ );
+
+ // Select all enabled+selectable
+ await user.click(screen.getByLabelText('Select all rows'));
+ // Deselect all
+ await user.click(screen.getByLabelText('Select all rows'));
+
+ const rows = screen.getAllByRole('row');
+ expect(rows[1]).not.toHaveAttribute('aria-selected');
+ expect(rows[2]).not.toHaveAttribute('aria-selected');
+ expect(rows[3]).not.toHaveAttribute('aria-selected');
+ // Diana (non-selectable) stays selected — frozen
+ expect(rows[4]).toHaveAttribute('aria-selected', 'true');
+ });
+
+ it('handles both non-selectable and disabled rows together', async () => {
+ const user = userEvent.setup();
+ // Charlie is disabled, Diana is non-selectable, both start selected
+ render(
+ <StateHelperTable
+ getIsItemEnabled={item => !item.isLocked}
+ getIsItemSelectable={item => !item.isHidden}
+ initialSelected={new Set(['3', '4'])}
+ />,
+ );
+
+ const rows = screen.getAllByRole('row');
+ // Both frozen items start selected
+ expect(rows[3]).toHaveAttribute('aria-selected', 'true');
+ expect(rows[4]).toHaveAttribute('aria-selected', 'true');
+
+ // Select all — only Alice and Bob are actionable
+ await user.click(screen.getByLabelText('Select all rows'));
+
+ expect(rows[1]).toHaveAttribute('aria-selected', 'true');
+ expect(rows[2]).toHaveAttribute('aria-selected', 'true');
+ expect(rows[3]).toHaveAttribute('aria-selected', 'true'); // frozen
+ expect(rows[4]).toHaveAttribute('aria-selected', 'true'); // frozen
+
+ // Deselect all — only Alice and Bob deselected
+ await user.click(screen.getByLabelText('Select all rows'));
+
+ expect(rows[1]).not.toHaveAttribute('aria-selected');
+ expect(rows[2]).not.toHaveAttribute('aria-selected');
+ expect(rows[3]).toHaveAttribute('aria-selected', 'true'); // still frozen
+ expect(rows[4]).toHaveAttribute('aria-selected', 'true'); // still frozen
+ });
+
+ it('individual selection works normally', async () => {
+ const user = userEvent.setup();
+ render(<StateHelperTable />);
+
+ const checkboxes = screen.getAllByLabelText('Select row');
+ await user.click(checkboxes[1]); // Bob
+
+ const rows = screen.getAllByRole('row');
+ expect(rows[1]).not.toHaveAttribute('aria-selected');
+ expect(rows[2]).toHaveAttribute('aria-selected', 'true');
+ expect(rows[3]).not.toHaveAttribute('aria-selected');
+ });
+});
diff --git a/packages/core/src/Table/plugins/selection/useXDSTableSelectionState.tsx b/packages/core/src/Table/plugins/selection/useXDSTableSelectionState.tsx
new file mode 100644
index 0000000000..fa72b8be64
--- /dev/null
+++ b/packages/core/src/Table/plugins/selection/useXDSTableSelectionState.tsx
@@ -0,0 +1,197 @@
+'use client';
+
+/**
+ * @file useXDSTableSelectionState.tsx
+ * @input React, UseXDSTableSelectionConfig type
+ * @output Exports useXDSTableSelectionState hook and config types
+ * @position Selection state helper; manages selection set with correct
+ * disabled/selectable filtering. Pairs with useXDSTableSelection.
+ *
+ * Modeled after the internal useXDSTableRowSelectionState which handles
+ * select-all correctly by preserving disabled-but-selected items and
+ * only toggling actionable (selectable + enabled) items.
+ *
+ * SYNC: When modified, update these files to stay in sync:
+ * - /packages/core/src/Table/plugins/selection/index.ts (exports)
+ * - /packages/core/src/Table/Table.doc.mjs (selection documentation)
+ */
+
+import {useCallback, useMemo, useRef} from 'react';
+import type {UseXDSTableSelectionConfig} from './useXDSTableSelection';
+
+// =============================================================================
+// Config Type
+// =============================================================================
+
+export interface UseXDSTableSelectionStateConfig<
+ T extends Record<string, unknown>,
+> {
+ /** The full data array rendered in the table. */
+ data: T[];
+ /**
+ * Key extractor — returns a unique string ID for each item.
+ * Can be a property name or a function.
+ */
+ idKey: (keyof T & string) | ((item: T) => string);
+ /**
+ * Should this row show a checkbox? Non-selectable rows are excluded
+ * from select-all and don\u2019t render a checkbox.
+ * @default () => true
+ */
+ getIsItemSelectable?: (item: T) => boolean;
+ /**
+ * Is this row\u2019s checkbox interactive? Disabled rows are frozen \u2014
+ * select-all won\u2019t add or remove them from the selection.
+ * A disabled row that was selected before becoming disabled stays selected.
+ * @default () => true
+ */
+ getIsItemEnabled?: (item: T) => boolean;
+ /**
+ * Controlled selected keys. The hook manages the selection set and
+ * calls this setter when it changes.
+ */
+ selectedKeys: Set<string>;
+ /**
+ * Setter for the controlled selected keys.
+ */
+ setSelectedKeys: React.Dispatch<React.SetStateAction<Set<string>>>;
+}
+
+export interface UseXDSTableSelectionStateResult<
+ T extends Record<string, unknown>,
+> {
+ /** Ready-to-use config for useXDSTableSelection. */
+ selectionConfig: UseXDSTableSelectionConfig<T>;
+}
+
+// =============================================================================
+// Hook
+// =============================================================================
+
+const stableTrue = () => true;
+
+export function useXDSTableSelectionState<T extends Record<string, unknown>>(
+ config: UseXDSTableSelectionStateConfig<T>,
+): UseXDSTableSelectionStateResult<T> {
+ const {
+ data,
+ idKey,
+ getIsItemSelectable = stableTrue,
+ getIsItemEnabled = stableTrue,
+ selectedKeys,
+ setSelectedKeys,
+ } = config;
+
+ const getId = useCallback(
+ (item: T): string =>
+ typeof idKey === 'function' ? idKey(item) : String(item[idKey]),
+ [idKey],
+ );
+
+ // Items that are both selectable and enabled — the "actionable" set
+ const getIsItemSelectableAndEnabled = useCallback(
+ (item: T) => getIsItemSelectable(item) && getIsItemEnabled(item),
+ [getIsItemSelectable, getIsItemEnabled],
+ );
+
+ // IDs of all actionable items
+ const selectableIDs = useMemo(
+ () => new Set(data.filter(getIsItemSelectableAndEnabled).map(getId)),
+ [data, getIsItemSelectableAndEnabled, getId],
+ );
+
+ // Selected IDs that are NOT actionable (disabled-but-selected).
+ // These are preserved across select-all / deselect-all.
+ const frozenSelectedIDs = useMemo(() => {
+ const frozen = new Set<string>();
+ for (const id of selectedKeys) {
+ if (!selectableIDs.has(id)) frozen.add(id);
+ }
+ return frozen;
+ }, [selectedKeys, selectableIDs]);
+
+ // All IDs that *would* be selected if select-all is checked
+ // (all actionable items + any frozen selected items)
+ const allSelectableIDs = useMemo(
+ () => new Set([...selectedKeys, ...selectableIDs]),
+ [selectedKeys, selectableIDs],
+ );
+
+ const getAllSelected = useCallback(
+ () =>
+ allSelectableIDs.size === selectedKeys.size &&
+ allSelectableIDs.size !== 0,
+ [allSelectableIDs, selectedKeys],
+ );
+
+ // Use refs to keep onSelectAll stable
+ const frozenSelectedIDsRef = useRef(frozenSelectedIDs);
+ frozenSelectedIDsRef.current = frozenSelectedIDs;
+
+ const allSelectableIDsRef = useRef(allSelectableIDs);
+ allSelectableIDsRef.current = allSelectableIDs;
+
+ const onSelectAll = useCallback(
+ ({isAllSelected}: {isAllSelected: boolean}) => {
+ setSelectedKeys(
+ isAllSelected
+ ? // Select all actionable + preserve frozen
+ allSelectableIDsRef.current
+ : // Deselect all actionable, keep frozen
+ frozenSelectedIDsRef.current,
+ );
+ },
+ [setSelectedKeys],
+ );
+
+ const onSelectItem = useCallback(
+ ({item, isSelected}: {item: T; isSelected: boolean}) => {
+ setSelectedKeys(prev => {
+ const next = new Set(prev);
+ const id = getId(item);
+ if (isSelected) {
+ next.add(id);
+ } else {
+ next.delete(id);
+ }
+ return next;
+ });
+ },
+ [getId, setSelectedKeys],
+ );
+
+ const getIsIndeterminate = useCallback(() => {
+ const selectedActionableCount = data.filter(
+ item =>
+ getIsItemSelectableAndEnabled(item) && selectedKeys.has(getId(item)),
+ ).length;
+ return (
+ selectedActionableCount > 0 &&
+ selectedActionableCount < selectableIDs.size
+ );
+ }, [data, getIsItemSelectableAndEnabled, selectedKeys, getId, selectableIDs]);
+
+ const selectionConfig = useMemo(
+ (): UseXDSTableSelectionConfig<T> => ({
+ getIsItemSelected: item => selectedKeys.has(getId(item)),
+ onSelectItem,
+ onSelectAll,
+ getIsAllSelected: getAllSelected,
+ getIsIndeterminate,
+ getIsItemSelectable,
+ getIsItemEnabled,
+ }),
+ [
+ selectedKeys,
+ getId,
+ onSelectItem,
+ onSelectAll,
+ getAllSelected,
+ getIsIndeterminate,
+ getIsItemSelectable,
+ getIsItemEnabled,
+ ],
+ );
+
+ return {selectionConfig};
+}