Skip to content

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

TypeScript

feat(Table): useXDSTableColumnSettings plugin #978 (#1019)

Cindy Zhang40444ab7426a
diff --git a/apps/storybook/stories/TableColumnSettings.stories.tsx b/apps/storybook/stories/TableColumnSettings.stories.tsx
new file mode 100644
index 0000000000..6aaeb8a087
--- /dev/null
+++ b/apps/storybook/stories/TableColumnSettings.stories.tsx
@@ -0,0 +1,291 @@
+import {useState} from 'react';
+import type {Meta, StoryObj} from '@storybook/react';
+import {
+ XDSTable,
+ useXDSTableColumnSettings,
+ useXDSTableSelection,
+ useXDSTableSelectionState,
+} from '@xds/core/Table';
+import type {XDSTableColumn} from '@xds/core/Table';
+import {XDSMultiSelector} from '@xds/core/MultiSelector';
+import {XDSButton} from '@xds/core/Button';
+import {XDSToolbar} from '@xds/core/Toolbar';
+import {XDSText} from '@xds/core/Text';
+
+// =============================================================================
+// Sample Data
+// =============================================================================
+
+interface User extends Record<string, unknown> {
+ id: string;
+ name: string;
+ email: string;
+ role: string;
+ department: string;
+ status: string;
+}
+
+const users: User[] = [
+ {
+ id: '1',
+ name: 'Alice',
+ email: '[email protected]',
+ role: 'Engineer',
+ department: 'Platform',
+ status: 'Active',
+ },
+ {
+ id: '2',
+ name: 'Bob',
+ email: '[email protected]',
+ role: 'Designer',
+ department: 'Product',
+ status: 'Active',
+ },
+ {
+ id: '3',
+ name: 'Charlie',
+ email: '[email protected]',
+ role: 'Manager',
+ department: 'Platform',
+ status: 'Away',
+ },
+ {
+ id: '4',
+ name: 'Diana',
+ email: '[email protected]',
+ role: 'Engineer',
+ department: 'Infrastructure',
+ status: 'Active',
+ },
+ {
+ id: '5',
+ name: 'Eve',
+ email: '[email protected]',
+ role: 'Admin',
+ department: 'Operations',
+ status: 'Inactive',
+ },
+];
+
+const allColumns: XDSTableColumn<User>[] = [
+ {key: 'name', header: 'Name'},
+ {key: 'email', header: 'Email'},
+ {key: 'role', header: 'Role'},
+ {key: 'department', header: 'Department'},
+ {key: 'status', header: 'Status'},
+];
+
+type UserColumnKey = 'name' | 'email' | 'role' | 'department' | 'status';
+
+const columnOptions = [
+ {key: 'name' as UserColumnKey, label: 'Name', isAlwaysVisible: true},
+ {key: 'email' as UserColumnKey, label: 'Email'},
+ {key: 'role' as UserColumnKey, label: 'Role'},
+ {key: 'department' as UserColumnKey, label: 'Department'},
+ {key: 'status' as UserColumnKey, label: 'Status'},
+];
+
+const defaultActiveKeys: UserColumnKey[] = [
+ 'name',
+ 'email',
+ 'role',
+ 'department',
+ 'status',
+];
+
+// =============================================================================
+// Stories
+// =============================================================================
+
+const meta: Meta = {
+ title: 'Core/XDSTable/ColumnSettings',
+ tags: ['autodocs'],
+};
+
+export default meta;
+type Story = StoryObj;
+
+export const BasicColumnToggle: Story = {
+ render: () => {
+ const [activeKeys, setActiveKeys] =
+ useState<UserColumnKey[]>(defaultActiveKeys);
+
+ const columnSettings = useXDSTableColumnSettings<User, UserColumnKey>({
+ columns: columnOptions,
+ activeColumnKeys: activeKeys,
+ onChangeActiveColumnKeys: setActiveKeys,
+ });
+
+ return (
+ <div style={{maxWidth: 700}}>
+ <XDSToolbar
+ label="Table actions"
+ startContent={<XDSText type="label">Users</XDSText>}
+ endContent={
+ <XDSMultiSelector
+ label="Columns"
+ isLabelHidden
+ options={columnSettings.columnOptions}
+ value={[...columnSettings.activeColumnKeys]}
+ onChange={columnSettings.setActiveColumnKeys}
+ />
+ }
+ />
+ <XDSTable
+ data={users}
+ columns={columnSettings.activeColumns(allColumns)}
+ idKey="id"
+ plugins={{columnSettings: columnSettings.plugin}}
+ />
+ </div>
+ );
+ },
+};
+
+export const DisabledColumns: Story = {
+ render: () => {
+ const [activeKeys, setActiveKeys] = useState<UserColumnKey[]>([
+ 'name',
+ 'email',
+ 'role',
+ ]);
+
+ const columnSettings = useXDSTableColumnSettings<User, UserColumnKey>({
+ columns: columnOptions,
+ activeColumnKeys: activeKeys,
+ onChangeActiveColumnKeys: setActiveKeys,
+ });
+
+ return (
+ <div style={{maxWidth: 700}}>
+ <XDSText type="supporting">
+ &quot;Name&quot; is always visible and cannot be unchecked.
+ </XDSText>
+ <XDSToolbar
+ label="Table actions"
+ startContent={<XDSText type="label">Users</XDSText>}
+ endContent={
+ <XDSMultiSelector
+ label="Columns"
+ isLabelHidden
+ options={columnSettings.columnOptions}
+ value={[...columnSettings.activeColumnKeys]}
+ onChange={columnSettings.setActiveColumnKeys}
+ />
+ }
+ />
+ <XDSTable
+ data={users}
+ columns={columnSettings.activeColumns(allColumns)}
+ idKey="id"
+ plugins={{columnSettings: columnSettings.plugin}}
+ />
+ </div>
+ );
+ },
+};
+
+export const ResetToDefault: Story = {
+ render: () => {
+ const defaultKeys: UserColumnKey[] = ['name', 'email', 'role'];
+
+ const [activeKeys, setActiveKeys] =
+ useState<UserColumnKey[]>(defaultKeys);
+
+ const columnSettings = useXDSTableColumnSettings<User, UserColumnKey>({
+ columns: columnOptions,
+ activeColumnKeys: activeKeys,
+ onChangeActiveColumnKeys: setActiveKeys,
+ defaultColumnKeys: defaultKeys,
+ });
+
+ return (
+ <div style={{maxWidth: 700}}>
+ <XDSText type="supporting">
+ Toggle columns, then reset to restore the default set (Name, Email,
+ Role).
+ </XDSText>
+ <XDSToolbar
+ label="Table actions"
+ startContent={<XDSText type="label">Users</XDSText>}
+ endContent={
+ <>
+ <XDSButton
+ label="Reset to default"
+ variant="secondary"
+ onClick={columnSettings.resetToDefault}
+ />
+ <XDSMultiSelector
+ label="Columns"
+ isLabelHidden
+ options={columnSettings.columnOptions}
+ value={[...columnSettings.activeColumnKeys]}
+ onChange={columnSettings.setActiveColumnKeys}
+ />
+ </>
+ }
+ />
+ <XDSTable
+ data={users}
+ columns={columnSettings.activeColumns(allColumns)}
+ idKey="id"
+ plugins={{columnSettings: columnSettings.plugin}}
+ />
+ </div>
+ );
+ },
+};
+
+export const WithSelection: Story = {
+ render: () => {
+ const [activeKeys, setActiveKeys] =
+ useState<UserColumnKey[]>(defaultActiveKeys);
+ const [selectedKeys, setSelectedKeys] = useState<Set<string>>(new Set());
+
+ const columnSettings = useXDSTableColumnSettings<User, UserColumnKey>({
+ columns: columnOptions,
+ activeColumnKeys: activeKeys,
+ onChangeActiveColumnKeys: setActiveKeys,
+ });
+
+ const {selectionConfig} = useXDSTableSelectionState<User>({
+ data: users,
+ idKey: 'id',
+ selectedKeys,
+ setSelectedKeys,
+ });
+ const selectionPlugin = useXDSTableSelection<User>(selectionConfig);
+
+ return (
+ <div style={{maxWidth: 700}}>
+ <XDSToolbar
+ label="Table actions"
+ startContent={
+ <XDSText type="supporting">
+ {selectedKeys.size} of {users.length} selected
+ </XDSText>
+ }
+ endContent={
+ <XDSMultiSelector
+ label="Columns"
+ isLabelHidden
+ options={columnSettings.columnOptions}
+ value={[...columnSettings.activeColumnKeys]}
+ onChange={columnSettings.setActiveColumnKeys}
+ />
+ }
+ />
+ <XDSTable
+ data={users}
+ columns={columnSettings.activeColumns(allColumns)}
+ idKey="id"
+ plugins={{
+ columnSettings: columnSettings.plugin,
+ selection: selectionPlugin,
+ }}
+ />
+ </div>
+ );
+ },
+};
diff --git a/packages/core/src/Table/index.ts b/packages/core/src/Table/index.ts
index 2eaa448437..12e1833692 100644
--- a/packages/core/src/Table/index.ts
+++ b/packages/core/src/Table/index.ts
@@ -19,6 +19,7 @@ export {useXDSTableSelection} from './plugins/selection';
export {useXDSTableSelectionState} from './plugins/selection';
export {useXDSTableSortable} from './plugins/sortable';
export {useXDSTablePagination} from './plugins/pagination';
+export {useXDSTableColumnSettings} from './plugins/columnSettings';
export {useXDSBaseTablePlugins} from './useXDSBaseTablePlugins';
export {
proportional,
@@ -67,3 +68,8 @@ export type {
UseXDSTablePaginationConfig,
UseXDSTablePaginationReturn,
} from './plugins/pagination';
+export type {
+ UseXDSTableColumnSettingsConfig,
+ UseXDSTableColumnSettingsReturn,
+ XDSColumnSettingsOption,
+} from './plugins/columnSettings';
diff --git a/packages/core/src/Table/plugins/columnSettings/index.ts b/packages/core/src/Table/plugins/columnSettings/index.ts
new file mode 100644
index 0000000000..ef76fbfc54
--- /dev/null
+++ b/packages/core/src/Table/plugins/columnSettings/index.ts
@@ -0,0 +1,6 @@
+export {useXDSTableColumnSettings} from './useXDSTableColumnSettings';
+export type {
+ UseXDSTableColumnSettingsConfig,
+ UseXDSTableColumnSettingsReturn,
+ XDSColumnSettingsOption,
+} from './useXDSTableColumnSettings';
diff --git a/packages/core/src/Table/plugins/columnSettings/useXDSTableColumnSettings.test.tsx b/packages/core/src/Table/plugins/columnSettings/useXDSTableColumnSettings.test.tsx
new file mode 100644
index 0000000000..92c3f379b4
--- /dev/null
+++ b/packages/core/src/Table/plugins/columnSettings/useXDSTableColumnSettings.test.tsx
@@ -0,0 +1,537 @@
+/**
+ * @file useXDSTableColumnSettings.test.tsx
+ * @input useXDSTableColumnSettings, XDSTable, React testing utilities
+ * @output Functional tests for the column settings plugin
+ * @position Test file; validates column visibility, toggling, column options
+ */
+
+import {describe, it, expect, vi} from 'vitest';
+import {useState} from 'react';
+import {render, screen} from '@testing-library/react';
+import {renderHook, act} from '@testing-library/react';
+import {XDSTable} from '../../XDSTable';
+import {
+ useXDSTableColumnSettings,
+ type UseXDSTableColumnSettingsConfig,
+ type XDSColumnSettingsOption,
+} from './useXDSTableColumnSettings';
+import type {XDSTableColumn} from '../../types';
+
+// =============================================================================
+// Test Data
+// =============================================================================
+
+interface User extends Record<string, unknown> {
+ id: string;
+ name: string;
+ email: string;
+ role: string;
+ status: string;
+ lastLogin: string;
+}
+
+const testUsers: User[] = [
+ {
+ id: '1',
+ name: 'Alice',
+ email: '[email protected]',
+ role: 'admin',
+ status: 'active',
+ lastLogin: '2026-01-01',
+ },
+ {
+ id: '2',
+ name: 'Bob',
+ email: '[email protected]',
+ role: 'user',
+ status: 'inactive',
+ lastLogin: '2026-02-01',
+ },
+];
+
+const allTableColumns: XDSTableColumn<User>[] = [
+ {key: 'name', header: 'Name'},
+ {key: 'email', header: 'Email'},
+ {key: 'role', header: 'Role'},
+ {key: 'status', header: 'Status'},
+ {key: 'lastLogin', header: 'Last Login'},
+];
+
+const columnOptions: XDSColumnSettingsOption[] = [
+ {key: 'name', label: 'Name', isAlwaysVisible: true},
+ {key: 'email', label: 'Email'},
+ {key: 'role', label: 'Role'},
+ {key: 'status', label: 'Status'},
+ {key: 'lastLogin', label: 'Last Login'},
+];
+
+// =============================================================================
+// Helpers
+// =============================================================================
+
+function renderColumnSettingsHook(
+ overrides: Partial<UseXDSTableColumnSettingsConfig> = {},
+) {
+ const defaultConfig: UseXDSTableColumnSettingsConfig = {
+ columns: columnOptions,
+ activeColumnKeys: ['name', 'email', 'role'],
+ onChangeActiveColumnKeys: vi.fn(),
+ ...overrides,
+ };
+
+ return renderHook(() =>
+ useXDSTableColumnSettings<User>(defaultConfig),
+ );
+}
+
+// =============================================================================
+// Hook Return Value
+// =============================================================================
+
+describe('useXDSTableColumnSettings', () => {
+ describe('return value', () => {
+ it('returns plugin object with transformTableContext', () => {
+ const {result} = renderColumnSettingsHook();
+ expect(result.current.plugin).toBeDefined();
+ expect(result.current.plugin.transformTableContext).toBeInstanceOf(
+ Function,
+ );
+ });
+
+ it('returns activeColumns function', () => {
+ const {result} = renderColumnSettingsHook();
+ expect(result.current.activeColumns).toBeInstanceOf(Function);
+ });
+
+ it('returns toggleColumn function', () => {
+ const {result} = renderColumnSettingsHook();
+ expect(result.current.toggleColumn).toBeInstanceOf(Function);
+ });
+
+ it('returns isColumnActive function', () => {
+ const {result} = renderColumnSettingsHook();
+ expect(result.current.isColumnActive).toBeInstanceOf(Function);
+ });
+
+ it('returns isColumnToggleable function', () => {
+ const {result} = renderColumnSettingsHook();
+ expect(result.current.isColumnToggleable).toBeInstanceOf(Function);
+ });
+
+ it('returns activeColumnKeys passthrough', () => {
+ const {result} = renderColumnSettingsHook({
+ activeColumnKeys: ['name', 'email'],
+ });
+ expect(result.current.activeColumnKeys).toEqual(['name', 'email']);
+ });
+ });
+
+ // ===========================================================================
+ // activeColumns helper
+ // ===========================================================================
+
+ describe('activeColumns', () => {
+ it('filters columns to only active keys', () => {
+ const {result} = renderColumnSettingsHook({
+ activeColumnKeys: ['name', 'email', 'role'],
+ });
+ const filtered = result.current.activeColumns(allTableColumns);
+ expect(filtered).toHaveLength(3);
+ expect(filtered.map((c) => c.key)).toEqual(['name', 'email', 'role']);
+ });
+
+ it('preserves activeColumnKeys order', () => {
+ const {result} = renderColumnSettingsHook({
+ activeColumnKeys: ['role', 'name', 'email'],
+ });
+ const filtered = result.current.activeColumns(allTableColumns);
+ expect(filtered.map((c) => c.key)).toEqual(['role', 'name', 'email']);
+ });
+
+ it('handles unknown keys gracefully', () => {
+ const {result} = renderColumnSettingsHook({
+ activeColumnKeys: ['name', 'nonexistent', 'email'],
+ });
+ const filtered = result.current.activeColumns(allTableColumns);
+ expect(filtered).toHaveLength(2);
+ expect(filtered.map((c) => c.key)).toEqual(['name', 'email']);
+ });
+
+ it('returns empty array for empty activeColumnKeys', () => {
+ const {result} = renderColumnSettingsHook({
+ activeColumnKeys: [],
+ });
+ const filtered = result.current.activeColumns(allTableColumns);
+ expect(filtered).toHaveLength(0);
+ });
+
+ it('returns all columns when all keys active', () => {
+ const {result} = renderColumnSettingsHook({
+ activeColumnKeys: ['name', 'email', 'role', 'status', 'lastLogin'],
+ });
+ const filtered = result.current.activeColumns(allTableColumns);
+ expect(filtered).toHaveLength(5);
+ });
+
+ it('maintains XDSTableColumn shape', () => {
+ const columnsWithRenderCell: XDSTableColumn<User>[] = [
+ {key: 'name', header: 'Name', renderCell: (item) => item.name},
+ {key: 'email', header: 'Email'},
+ ];
+ const {result} = renderColumnSettingsHook({
+ activeColumnKeys: ['name', 'email'],
+ });
+ const filtered = result.current.activeColumns(columnsWithRenderCell);
+ expect(filtered[0].key).toBe('name');
+ expect(filtered[0].header).toBe('Name');
+ expect(filtered[0].renderCell).toBeInstanceOf(Function);
+ });
+ });
+
+ // ===========================================================================
+ // toggleColumn
+ // ===========================================================================
+
+ describe('toggleColumn', () => {
+ it('removes active column', () => {
+ const onChange = vi.fn();
+ const {result} = renderColumnSettingsHook({
+ activeColumnKeys: ['name', 'email', 'role'],
+ onChangeActiveColumnKeys: onChange,
+ });
+
+ act(() => result.current.toggleColumn('email'));
+ expect(onChange).toHaveBeenCalledWith(['name', 'role']);
+ });
+
+ it('adds inactive column at end', () => {
+ const onChange = vi.fn();
+ const {result} = renderColumnSettingsHook({
+ activeColumnKeys: ['name', 'email'],
+ onChangeActiveColumnKeys: onChange,
+ });
+
+ act(() => result.current.toggleColumn('status'));
+ expect(onChange).toHaveBeenCalledWith(['name', 'email', 'status']);
+ });
+
+ it('no-op for isAlwaysVisible columns', () => {
+ const onChange = vi.fn();
+ const {result} = renderColumnSettingsHook({
+ activeColumnKeys: ['name', 'email'],
+ onChangeActiveColumnKeys: onChange,
+ });
+
+ act(() => result.current.toggleColumn('name'));
+ expect(onChange).not.toHaveBeenCalled();
+ });
+
+ it('calls onChangeActiveColumnKeys with new array', () => {
+ const onChange = vi.fn();
+ const {result} = renderColumnSettingsHook({
+ activeColumnKeys: ['name', 'email'],
+ onChangeActiveColumnKeys: onChange,
+ });
+
+ act(() => result.current.toggleColumn('role'));
+ expect(onChange).toHaveBeenCalledTimes(1);
+ expect(onChange).toHaveBeenCalledWith(['name', 'email', 'role']);
+ });
+ });
+
+ // ===========================================================================
+ // isColumnActive
+ // ===========================================================================
+
+ describe('isColumnActive', () => {
+ it('returns true for active columns', () => {
+ const {result} = renderColumnSettingsHook({
+ activeColumnKeys: ['name', 'email'],
+ });
+ expect(result.current.isColumnActive('name')).toBe(true);
+ expect(result.current.isColumnActive('email')).toBe(true);
+ });
+
+ it('returns false for inactive columns', () => {
+ const {result} = renderColumnSettingsHook({
+ activeColumnKeys: ['name', 'email'],
+ });
+ expect(result.current.isColumnActive('role')).toBe(false);
+ expect(result.current.isColumnActive('status')).toBe(false);
+ });
+ });
+
+ // ===========================================================================
+ // isColumnToggleable
+ // ===========================================================================
+
+ describe('isColumnToggleable', () => {
+ it('returns true for normal columns', () => {
+ const {result} = renderColumnSettingsHook();
+ expect(result.current.isColumnToggleable('email')).toBe(true);
+ expect(result.current.isColumnToggleable('role')).toBe(true);
+ });
+
+ it('returns false for always-visible columns', () => {
+ const {result} = renderColumnSettingsHook();
+ expect(result.current.isColumnToggleable('name')).toBe(false);
+ });
+ });
+
+ // ===========================================================================
+ // showAllColumns
+ // ===========================================================================
+
+ describe('showAllColumns', () => {
+ it('sets all column keys as active in columns config order', () => {
+ const onChange = vi.fn();
+ const {result} = renderColumnSettingsHook({
+ activeColumnKeys: ['name'],
+ onChangeActiveColumnKeys: onChange,
+ });
+
+ act(() => result.current.showAllColumns());
+ expect(onChange).toHaveBeenCalledWith([
+ 'name',
+ 'email',
+ 'role',
+ 'status',
+ 'lastLogin',
+ ]);
+ });
+ });
+
+ // ===========================================================================
+ // resetToDefault
+ // ===========================================================================
+
+ describe('resetToDefault', () => {
+ it('resets to defaultColumnKeys when provided', () => {
+ const onChange = vi.fn();
+ const {result} = renderColumnSettingsHook({
+ activeColumnKeys: ['name', 'email', 'role', 'status', 'lastLogin'],
+ onChangeActiveColumnKeys: onChange,
+ defaultColumnKeys: ['name', 'email'],
+ });
+
+ act(() => result.current.resetToDefault());
+ expect(onChange).toHaveBeenCalledWith(['name', 'email']);
+ });
+
+ it('shows all columns when no defaultColumnKeys', () => {
+ const onChange = vi.fn();
+ const {result} = renderColumnSettingsHook({
+ activeColumnKeys: ['name'],
+ onChangeActiveColumnKeys: onChange,
+ });
+
+ act(() => result.current.resetToDefault());
+ expect(onChange).toHaveBeenCalledWith([
+ 'name',
+ 'email',
+ 'role',
+ 'status',
+ 'lastLogin',
+ ]);
+ });
+ });
+
+ // ===========================================================================
+ // columnOptions
+ // ===========================================================================
+
+ describe('columnOptions', () => {
+ it('generates one item per column for ungrouped columns', () => {
+ const {result} = renderColumnSettingsHook();
+ expect(result.current.columnOptions).toHaveLength(5);
+ });
+
+ it('marks always-visible columns as disabled', () => {
+ const {result} = renderColumnSettingsHook();
+ const items = result.current.columnOptions;
+ // First item is 'name' with isAlwaysVisible
+ const nameItem = items[0];
+ expect(nameItem).toHaveProperty('disabled', true);
+ // Second item is 'email' without isAlwaysVisible
+ const emailItem = items[1];
+ expect(emailItem).toHaveProperty('disabled', false);
+ });
+
+ it('generates items with value and label', () => {
+ const {result} = renderColumnSettingsHook();
+ const items = result.current.columnOptions;
+ const first = items[0] as {value: string; label: string};
+ expect(first.value).toBe('name');
+ expect(first.label).toBe('Name');
+ });
+
+ it('groups columns by group field into sections', () => {
+ const groupedColumns: XDSColumnSettingsOption[] = [
+ {key: 'name', label: 'Name', isAlwaysVisible: true, group: 'Basic'},
+ {key: 'email', label: 'Email', group: 'Basic'},
+ {key: 'role', label: 'Role', group: 'Details'},
+ {key: 'status', label: 'Status'},
+ ];
+
+ const {result} = renderColumnSettingsHook({columns: groupedColumns});
+ const items = result.current.columnOptions;
+
+ // Should have 2 sections + 1 ungrouped item
+ const sections = items.filter(
+ (i) => typeof i === 'object' && 'type' in i && i.type === 'section',
+ );
+ expect(sections).toHaveLength(2);
+
+ const basicSection = sections[0] as {
+ type: 'section';
+ title: string;
+ options: Array<{value: string}>;
+ };
+ expect(basicSection.title).toBe('Basic');
+ expect(basicSection.options).toHaveLength(2);
+
+ // Ungrouped item ('status') appears after sections
+ const lastItem = items[items.length - 1] as {value: string};
+ expect(lastItem.value).toBe('status');
+ });
+ });
+
+ // ===========================================================================
+ // setActiveColumnKeys
+ // ===========================================================================
+
+ describe('setActiveColumnKeys', () => {
+ it('passes selected values to onChangeActiveColumnKeys', () => {
+ const onChange = vi.fn();
+ const {result} = renderColumnSettingsHook({
+ onChangeActiveColumnKeys: onChange,
+ });
+
+ act(() =>
+ result.current.setActiveColumnKeys(['name', 'email', 'status']),
+ );
+ expect(onChange).toHaveBeenCalledWith(
+ expect.arrayContaining(['name', 'email', 'status']),
+ );
+ });
+
+ it('enforces isAlwaysVisible columns remain in set', () => {
+ const onChange = vi.fn();
+ const {result} = renderColumnSettingsHook({
+ onChangeActiveColumnKeys: onChange,
+ });
+
+ // Try to deselect 'name' (isAlwaysVisible) by not including it
+ act(() => result.current.setActiveColumnKeys(['email']));
+ const calledWith = onChange.mock.calls[0][0] as string[];
+ expect(calledWith).toContain('name');
+ expect(calledWith).toContain('email');
+ });
+ });
+
+ // ===========================================================================
+ // Integration with XDSTable
+ // ===========================================================================
+
+ describe('integration with XDSTable', () => {
+ function ColumnSettingsTable({
+ initialActiveKeys,
+ }: {
+ initialActiveKeys: string[];
+ }) {
+ const [activeKeys, setActiveKeys] = useState(initialActiveKeys);
+
+ const columnSettings = useXDSTableColumnSettings<User>({
+ columns: columnOptions,
+ activeColumnKeys: activeKeys,
+ onChangeActiveColumnKeys: setActiveKeys,
+ });
+
+ return (
+ <XDSTable
+ data={testUsers}
+ columns={columnSettings.activeColumns(allTableColumns)}
+ plugins={[columnSettings.plugin]}
+ idKey="id"
+ />
+ );
+ }
+
+ it('table renders only active columns', () => {
+ render(
+ <ColumnSettingsTable initialActiveKeys={['name', 'email', 'role']} />,
+ );
+
+ // Active columns should be visible
+ expect(screen.getByText('Name')).toBeInTheDocument();
+ expect(screen.getByText('Email')).toBeInTheDocument();
+ expect(screen.getByText('Role')).toBeInTheDocument();
+
+ // Inactive columns should not be visible
+ expect(screen.queryByText('Status')).not.toBeInTheDocument();
+ expect(screen.queryByText('Last Login')).not.toBeInTheDocument();
+ });
+
+ it('column order matches activeColumnKeys order', () => {
+ render(
+ <ColumnSettingsTable initialActiveKeys={['role', 'name', 'email']} />,
+ );
+
+ const headers = screen.getAllByRole('columnheader');
+ expect(headers[0]).toHaveTextContent('Role');
+ expect(headers[1]).toHaveTextContent('Name');
+ expect(headers[2]).toHaveTextContent('Email');
+ });
+ });
+
+ // ===========================================================================
+ // Edge Cases
+ // ===========================================================================
+
+ describe('edge cases', () => {
+ it('handles empty columns config', () => {
+ const {result} = renderColumnSettingsHook({
+ columns: [],
+ activeColumnKeys: [],
+ });
+
+ expect(result.current.columnOptions).toHaveLength(0);
+ expect(result.current.activeColumns(allTableColumns)).toHaveLength(0);
+ });
+
+ it('handles single column with isAlwaysVisible', () => {
+ const {result} = renderColumnSettingsHook({
+ columns: [{key: 'name', label: 'Name', isAlwaysVisible: true}],
+ activeColumnKeys: ['name'],
+ });
+
+ expect(result.current.isColumnToggleable('name')).toBe(false);
+ expect(result.current.isColumnActive('name')).toBe(true);
+ });
+
+ it('handles all columns isAlwaysVisible', () => {
+ const allVisible: XDSColumnSettingsOption[] = [
+ {key: 'name', label: 'Name', isAlwaysVisible: true},
+ {key: 'email', label: 'Email', isAlwaysVisible: true},
+ ];
+
+ const onChange = vi.fn();
+ const {result} = renderColumnSettingsHook({
+ columns: allVisible,
+ activeColumnKeys: ['name', 'email'],
+ onChangeActiveColumnKeys: onChange,
+ });
+
+ act(() => result.current.toggleColumn('name'));
+ act(() => result.current.toggleColumn('email'));
+ expect(onChange).not.toHaveBeenCalled();
+ });
+
+ it('plugin reference is stable across renders', () => {
+ const {result, rerender} = renderColumnSettingsHook();
+ const firstPlugin = result.current.plugin;
+ rerender();
+ expect(result.current.plugin).toBe(firstPlugin);
+ });
+ });
+});
diff --git a/packages/core/src/Table/plugins/columnSettings/useXDSTableColumnSettings.tsx b/packages/core/src/Table/plugins/columnSettings/useXDSTableColumnSettings.tsx
new file mode 100644
index 0000000000..40fdcdefc6
--- /dev/null
+++ b/packages/core/src/Table/plugins/columnSettings/useXDSTableColumnSettings.tsx
@@ -0,0 +1,415 @@
+'use client';
+
+/**
+ * @file useXDSTableColumnSettings.tsx
+ * @input React, Table types, MultiSelector types
+ * @output Exports useXDSTableColumnSettings hook and config/return types
+ * @position Column settings plugin; consumed by XDSTable via plugins prop
+ *
+ * Headless column visibility and ordering management for XDSTable.
+ * The consumer owns all state — the hook provides filtered columns,
+ * toggle helpers, and pre-built XDSMultiSelector options.
+ *
+ * SYNC: When modified, update these files to stay in sync:
+ * - /packages/core/src/Table/index.ts (exports)
+ */
+
+import {useCallback, useMemo, useRef, type ReactNode} from 'react';
+import type {TablePlugin, XDSTableColumn} from '../../types';
+import type {XDSMultiSelectorOptionType} from '../../../MultiSelector/types';
+
+// =============================================================================
+// Config Types
+// =============================================================================
+
+/**
+ * Definition of a column for the column settings UI.
+ * Separate from XDSTableColumn because the settings UI needs metadata
+ * (label, group, disableability) that the table column doesn't carry.
+ */
+export interface XDSColumnSettingsOption<
+ TColumnKey extends string = string,
+> {
+ /** Column key — must match XDSTableColumn.key */
+ key: TColumnKey;
+ /** Human-readable label for the column settings UI */
+ label: string;
+ /**
+ * Whether this column can be hidden.
+ * When true, the column is always visible and its checkbox is disabled.
+ * Use for essential columns like "Name" or "ID".
+ *
+ * @default false
+ */
+ isAlwaysVisible?: boolean;
+ /**
+ * Optional group name for organized column lists.
+ * Columns with the same group are rendered together under a heading.
+ */
+ group?: string;
+}
+
+/**
+ * Configuration for useXDSTableColumnSettings.
+ *
+ * Headless column visibility and ordering management for XDSTable.
+ * The consumer owns all state. The hook provides filtered columns
+ * and a plugin for table integration.
+ *
+ * @template TColumnKey - String literal union of column keys
+ *
+ * @example
+ * ```
+ * const allColumns = [
+ * { key: 'name', header: 'Name' },
+ * { key: 'email', header: 'Email' },
+ * { key: 'role', header: 'Role' },
+ * { key: 'status', header: 'Status' },
+ * ];
+ *
+ * const [activeKeys, setActiveKeys] = useState(['name', 'email', 'role']);
+ *
+ * const columnSettings = useXDSTableColumnSettings({
+ * columns: [
+ * { key: 'name', label: 'Name', isAlwaysVisible: true },
+ * { key: 'email', label: 'Email' },
+ * { key: 'role', label: 'Role' },
+ * { key: 'status', label: 'Status' },
+ * ],
+ * activeColumnKeys: activeKeys,
+ * onChangeActiveColumnKeys: setActiveKeys,
+ * });
+ *
+ * <XDSTable
+ * data={data}
+ * columns={columnSettings.activeColumns(allColumns)}
+ * plugins={[columnSettings.plugin]}
+ * />
+ * ```
+ *
+ * @example
+ * ```
+ * <XDSMultiSelector
+ * label="Columns"
+ * options={columnSettings.columnOptions}
+ * value={[...columnSettings.activeColumnKeys]}
+ * onChange={columnSettings.setActiveColumnKeys}
+ * hasSelectAll
+ * />
+ * ```
+ */
+export interface UseXDSTableColumnSettingsConfig<
+ TColumnKey extends string = string,
+> {
+ /**
+ * All available columns with metadata for the settings UI.
+ * This defines the universe of columns the user can toggle.
+ */
+ columns: ReadonlyArray<XDSColumnSettingsOption<TColumnKey>>;
+
+ /**
+ * Currently active column keys, in display order.
+ * Only columns with keys in this array are shown in the table.
+ * The array order determines column display order.
+ */
+ activeColumnKeys: ReadonlyArray<TColumnKey>;
+
+ /**
+ * Called when active columns change (toggle, reorder).
+ * Consumer updates their own state.
+ */
+ onChangeActiveColumnKeys: (keys: ReadonlyArray<TColumnKey>) => void;
+
+ /**
+ * The default column set for "Reset to default" functionality.
+ * When omitted, resetToDefault shows all columns.
+ */
+ defaultColumnKeys?: ReadonlyArray<TColumnKey>;
+}
+
+// =============================================================================
+// Return Type
+// =============================================================================
+
+/**
+ * Return value of useXDSTableColumnSettings.
+ */
+export interface UseXDSTableColumnSettingsReturn<
+ T extends Record<string, unknown>,
+ TColumnKey extends string = string,
+> {
+ /** The TablePlugin to pass to XDSTable's plugins prop. */
+ plugin: TablePlugin<T>;
+
+ /**
+ * Filters and reorders the full columns array based on activeColumnKeys.
+ * Returns only active columns, in the order specified by activeColumnKeys.
+ *
+ * @example
+ * ```
+ * <XDSTable columns={columnSettings.activeColumns(allColumns)} />
+ * ```
+ */
+ activeColumns: (columns: XDSTableColumn<T>[]) => XDSTableColumn<T>[];
+
+ /**
+ * Toggle a column's visibility.
+ * If the column is active, removes it. If inactive, adds it to the end.
+ * No-op for columns with `isAlwaysVisible: true`.
+ */
+ toggleColumn: (key: TColumnKey) => void;
+
+ /**
+ * Whether a specific column is currently active (visible).
+ */
+ isColumnActive: (key: TColumnKey) => boolean;
+
+ /**
+ * Whether a specific column can be toggled.
+ * Returns false for columns with `isAlwaysVisible: true`.
+ */
+ isColumnToggleable: (key: TColumnKey) => boolean;
+
+ /**
+ * Show all columns.
+ */
+ showAllColumns: () => void;
+
+ /**
+ * Reset to the default column set.
+ * Uses `defaultColumnKeys` if provided, otherwise shows all columns.
+ */
+ resetToDefault: () => void;
+
+ /**
+ * Column options formatted for XDSMultiSelector.
+ * Each option represents a column; always-visible columns are disabled.
+ * Columns with a `group` are rendered as sections.
+ *
+ * @example
+ * ```
+ * <XDSMultiSelector
+ * label="Columns"
+ * options={columnSettings.columnOptions}
+ * value={[...columnSettings.activeColumnKeys]}
+ * onChange={columnSettings.setActiveColumnKeys}
+ * />
+ * ```
+ */
+ columnOptions: XDSMultiSelectorOptionType[];
+
+ /**
+ * Set active column keys from a list of key strings.
+ * Enforces that `isAlwaysVisible` columns remain in the active set.
+ * Pass directly as `onChange` to XDSMultiSelector.
+ */
+ setActiveColumnKeys: (keys: string[]) => void;
+
+ /** Currently active column keys (pass-through from config). */
+ activeColumnKeys: ReadonlyArray<TColumnKey>;
+}
+
+// =============================================================================
+// Hook
+// =============================================================================
+
+/**
+ * Headless column visibility and ordering management for XDSTable.
+ *
+ * Manages which columns are visible and in what order, provides a table plugin
+ * for integration, and generates pre-built items for XDSMultiSelector.
+ * The consumer owns all state — the hook provides helpers and a stable plugin.
+ *
+ * @example
+ * ```
+ * const columnSettings = useXDSTableColumnSettings({
+ * columns: [
+ * { key: 'name', label: 'Name', isAlwaysVisible: true },
+ * { key: 'email', label: 'Email' },
+ * ],
+ * activeColumnKeys: activeKeys,
+ * onChangeActiveColumnKeys: setActiveKeys,
+ * });
+ * ```
+ */
+export function useXDSTableColumnSettings<
+ T extends Record<string, unknown>,
+ TColumnKey extends string = string,
+>(
+ config: UseXDSTableColumnSettingsConfig<TColumnKey>,
+): UseXDSTableColumnSettingsReturn<T, TColumnKey> {
+ const {columns, activeColumnKeys} = config;
+
+ // Keep config in a ref so the plugin and callbacks always read
+ // the latest version without forcing new object identity.
+ const configRef = useRef(config);
+ configRef.current = config;
+
+ // Build lookup sets for fast checks
+ const activeSet = useMemo(
+ () => new Set(activeColumnKeys),
+ [activeColumnKeys],
+ );
+
+ const alwaysVisibleSet = useMemo(
+ () => new Set(columns.filter((c) => c.isAlwaysVisible).map((c) => c.key)),
+ [columns],
+ );
+
+ // --- Column operations ---
+
+ const toggleColumn = useCallback(
+ (key: TColumnKey) => {
+ const cfg = configRef.current;
+ const avSet = new Set(
+ cfg.columns.filter((c) => c.isAlwaysVisible).map((c) => c.key),
+ );
+ if (avSet.has(key)) return;
+
+ const currentKeys = cfg.activeColumnKeys;
+ const currentSet = new Set(currentKeys);
+ if (currentSet.has(key)) {
+ cfg.onChangeActiveColumnKeys(currentKeys.filter((k) => k !== key));
+ } else {
+ cfg.onChangeActiveColumnKeys([...currentKeys, key]);
+ }
+ },
+ // configRef is stable — no deps needed beyond the ref
+ [],
+ );
+
+ const isColumnActive = useCallback(
+ (key: TColumnKey) => activeSet.has(key),
+ [activeSet],
+ );
+
+ const isColumnToggleable = useCallback(
+ (key: TColumnKey) => !alwaysVisibleSet.has(key),
+ [alwaysVisibleSet],
+ );
+
+ const showAllColumns = useCallback(() => {
+ const cfg = configRef.current;
+ cfg.onChangeActiveColumnKeys(cfg.columns.map((c) => c.key));
+ }, []);
+
+ const resetToDefault = useCallback(() => {
+ const cfg = configRef.current;
+ if (cfg.defaultColumnKeys) {
+ cfg.onChangeActiveColumnKeys([...cfg.defaultColumnKeys]);
+ } else {
+ cfg.onChangeActiveColumnKeys(cfg.columns.map((c) => c.key));
+ }
+ }, []);
+
+ // --- Column filtering helper ---
+
+ const activeColumns = useCallback(
+ (allColumns: XDSTableColumn<T>[]): XDSTableColumn<T>[] => {
+ const columnMap = new Map(allColumns.map((c) => [c.key, c]));
+ return activeColumnKeys
+ .map((key) => columnMap.get(key))
+ .filter((c): c is XDSTableColumn<T> => c != null);
+ },
+ [activeColumnKeys],
+ );
+
+ // --- Column options for XDSMultiSelector ---
+
+ const columnOptions = useMemo((): XDSMultiSelectorOptionType[] => {
+ const hasGroups = columns.some((c) => c.group);
+
+ if (!hasGroups) {
+ return columns.map((col) => ({
+ value: col.key,
+ label: col.label,
+ disabled: col.isAlwaysVisible === true,
+ }));
+ }
+
+ // Build grouped sections
+ const groups = new Map<
+ string,
+ XDSColumnSettingsOption<TColumnKey>[]
+ >();
+ const ungrouped: XDSColumnSettingsOption<TColumnKey>[] = [];
+
+ for (const col of columns) {
+ if (col.group) {
+ const group = groups.get(col.group) ?? [];
+ group.push(col);
+ groups.set(col.group, group);
+ } else {
+ ungrouped.push(col);
+ }
+ }
+
+ const items: XDSMultiSelectorOptionType[] = [];
+
+ for (const [groupName, groupCols] of groups) {
+ items.push({
+ type: 'section' as const,
+ title: groupName,
+ options: groupCols.map((col) => ({
+ value: col.key,
+ label: col.label,
+ disabled: col.isAlwaysVisible === true,
+ })),
+ });
+ }
+
+ for (const col of ungrouped) {
+ items.push({
+ value: col.key,
+ label: col.label,
+ disabled: col.isAlwaysVisible === true,
+ });
+ }
+
+ return items;
+ }, [columns]);
+
+ // --- Set active column keys ---
+
+ const setActiveColumnKeys = useCallback(
+ (value: string[]) => {
+ const cfg = configRef.current;
+ const avSet = new Set(
+ cfg.columns.filter((c) => c.isAlwaysVisible).map((c) => c.key),
+ );
+ // Ensure always-visible columns remain in the set
+ const valueSet = new Set(value);
+ for (const key of avSet) {
+ valueSet.add(key);
+ }
+ cfg.onChangeActiveColumnKeys(
+ Array.from(valueSet) as unknown as TColumnKey[],
+ );
+ },
+ [],
+ );
+
+ // --- Plugin (stable ref via configRef) ---
+
+ const plugin = useMemo(
+ (): TablePlugin<T> => ({
+ transformTableContext(children: ReactNode) {
+ return children;
+ },
+ }),
+ [],
+ );
+
+ return {
+ plugin,
+ activeColumns,
+ toggleColumn,
+ isColumnActive,
+ isColumnToggleable,
+ showAllColumns,
+ resetToDefault,
+ columnOptions,
+ setActiveColumnKeys,
+ activeColumnKeys,
+ };
+}