Skip to content

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

TypeScript

refactor(Table): useXDSTablePagination returns TablePlugin directly (#1165)

Cindy Zhang80c366451ac9
diff --git a/apps/storybook/stories/TablePagination.stories.tsx b/apps/storybook/stories/TablePagination.stories.tsx
index 8fecf3f89a..3f672a2352 100644
--- a/apps/storybook/stories/TablePagination.stories.tsx
+++ b/apps/storybook/stories/TablePagination.stories.tsx
@@ -3,6 +3,7 @@ import type {Meta, StoryObj} from '@storybook/react';
import {
XDSTable,
useXDSTablePagination,
+ paginateData,
useXDSTableSelection,
useXDSTableSelectionState,
} from '@xds/core/Table';
@@ -54,12 +55,13 @@ function PaginatedDemo({
align?: Align;
}) {
const [page, setPage] = useState(1);
+ const pageSize = 10;
- const pagination = useXDSTablePagination<User>({
+ const plugin = useXDSTablePagination<User>({
page,
onPageChange: setPage,
totalItems: users.length,
- pageSize: 10,
+ pageSize,
variant,
position,
align,
@@ -67,10 +69,10 @@ function PaginatedDemo({
return (
<XDSTable
- data={pagination.paginatedData(users)}
+ data={paginateData(users, page, pageSize)}
columns={columns}
idKey="id"
- plugins={{pagination: pagination.plugin}}
+ plugins={{pagination: plugin}}
/>
);
}
@@ -90,21 +92,22 @@ type Story = StoryObj;
export const Default: Story = {
render: () => {
const [page, setPage] = useState(1);
+ const pageSize = 10;
- const pagination = useXDSTablePagination<User>({
+ const plugin = useXDSTablePagination<User>({
page,
onPageChange: setPage,
totalItems: users.length,
- pageSize: 10,
+ pageSize,
});
return (
<div style={{maxWidth: 600}}>
<XDSTable
- data={pagination.paginatedData(users)}
+ data={paginateData(users, page, pageSize)}
columns={columns}
idKey="id"
- plugins={{pagination: pagination.plugin}}
+ plugins={{pagination: plugin}}
/>
</div>
);
@@ -118,7 +121,7 @@ export const ServerSide: Story = {
const serverData = users.slice((page - 1) * pageSize, page * pageSize);
- const pagination = useXDSTablePagination<User>({
+ const plugin = useXDSTablePagination<User>({
page,
onPageChange: setPage,
totalItems: users.length,
@@ -134,7 +137,7 @@ export const ServerSide: Story = {
data={serverData}
columns={columns}
idKey="id"
- plugins={{pagination: pagination.plugin}}
+ plugins={{pagination: plugin}}
/>
</div>
);
@@ -146,7 +149,7 @@ export const PageSizeSelector: Story = {
const [page, setPage] = useState(1);
const [pageSize, setPageSize] = useState(10);
- const pagination = useXDSTablePagination<User>({
+ const plugin = useXDSTablePagination<User>({
page,
onPageChange: setPage,
totalItems: users.length,
@@ -158,10 +161,10 @@ export const PageSizeSelector: Story = {
return (
<div style={{maxWidth: 600}}>
<XDSTable
- data={pagination.paginatedData(users)}
+ data={paginateData(users, page, pageSize)}
columns={columns}
idKey="id"
- plugins={{pagination: pagination.plugin}}
+ plugins={{pagination: plugin}}
/>
</div>
);
@@ -175,7 +178,7 @@ export const CursorBased: Story = {
const hasMore = page * pageSize < users.length;
- const pagination = useXDSTablePagination<User>({
+ const plugin = useXDSTablePagination<User>({
page,
onPageChange: setPage,
hasMore,
@@ -188,10 +191,10 @@ export const CursorBased: Story = {
Cursor-based: total unknown, only hasMore={String(hasMore)}.
</p>
<XDSTable
- data={pagination.paginatedData(users)}
+ data={paginateData(users, page, pageSize)}
columns={columns}
idKey="id"
- plugins={{pagination: pagination.plugin}}
+ plugins={{pagination: plugin}}
/>
</div>
);
@@ -201,22 +204,23 @@ export const CursorBased: Story = {
export const PositionAbove: Story = {
render: () => {
const [page, setPage] = useState(1);
+ const pageSize = 10;
- const pagination = useXDSTablePagination<User>({
+ const plugin = useXDSTablePagination<User>({
page,
onPageChange: setPage,
totalItems: users.length,
- pageSize: 10,
+ pageSize,
position: 'above',
});
return (
<div style={{maxWidth: 600}}>
<XDSTable
- data={pagination.paginatedData(users)}
+ data={paginateData(users, page, pageSize)}
columns={columns}
idKey="id"
- plugins={{pagination: pagination.plugin}}
+ plugins={{pagination: plugin}}
/>
</div>
);
@@ -226,22 +230,23 @@ export const PositionAbove: Story = {
export const PositionBoth: Story = {
render: () => {
const [page, setPage] = useState(1);
+ const pageSize = 10;
- const pagination = useXDSTablePagination<User>({
+ const plugin = useXDSTablePagination<User>({
page,
onPageChange: setPage,
totalItems: users.length,
- pageSize: 10,
+ pageSize,
position: 'both',
});
return (
<div style={{maxWidth: 600}}>
<XDSTable
- data={pagination.paginatedData(users)}
+ data={paginateData(users, page, pageSize)}
columns={columns}
idKey="id"
- plugins={{pagination: pagination.plugin}}
+ plugins={{pagination: plugin}}
/>
</div>
);
@@ -253,14 +258,14 @@ export const WithSelection: Story = {
const [page, setPage] = useState(1);
const [selectedKeys, setSelectedKeys] = useState<Set<string>>(new Set());
- const pagination = useXDSTablePagination<User>({
+ const plugin = useXDSTablePagination<User>({
page,
onPageChange: setPage,
totalItems: users.length,
- pageSize: 10,
+ pageSize,
});
- const pageData = pagination.paginatedData(users);
+ const pageData = paginateData(users, page, pageSize);
const {selectionConfig} = useXDSTableSelectionState<User>({
data: pageData,
@@ -281,7 +286,7 @@ export const WithSelection: Story = {
idKey="id"
plugins={{
selection: selectionPlugin,
- pagination: pagination.plugin,
+ pagination: plugin,
}}
/>
</div>
diff --git a/packages/core/src/Table/index.ts b/packages/core/src/Table/index.ts
index 6eec638dfc..31889fd1be 100644
--- a/packages/core/src/Table/index.ts
+++ b/packages/core/src/Table/index.ts
@@ -19,7 +19,7 @@ export {useXDSTableSelection} from './plugins/selection';
export {useXDSTableSelectionState} from './plugins/selection';
export {useXDSTableSortable} from './plugins/sortable';
export {useXDSTableSortableState} from './plugins/sortable';
-export {useXDSTablePagination} from './plugins/pagination';
+export {useXDSTablePagination, paginateData} from './plugins/pagination';
export {useXDSTableColumnSettings} from './plugins/columnSettings';
export {useXDSTableColumnSettingsState} from './plugins/columnSettings';
export {useXDSTableColumnResize} from './plugins/columnResize';
@@ -76,10 +76,7 @@ export type {
XDSTableSortState,
} from './plugins/sortable';
export type {XDSTableSortableColumnConfig} from './types';
-export type {
- UseXDSTablePaginationConfig,
- UseXDSTablePaginationReturn,
-} from './plugins/pagination';
+export type {UseXDSTablePaginationConfig} from './plugins/pagination';
export type {
UseXDSTableColumnSettingsConfig,
XDSColumnSettingsOption,
diff --git a/packages/core/src/Table/plugins/pagination/index.ts b/packages/core/src/Table/plugins/pagination/index.ts
index 501ac4d2f7..dd4f155ba3 100644
--- a/packages/core/src/Table/plugins/pagination/index.ts
+++ b/packages/core/src/Table/plugins/pagination/index.ts
@@ -1,5 +1,2 @@
-export {useXDSTablePagination} from './useXDSTablePagination';
-export type {
- UseXDSTablePaginationConfig,
- UseXDSTablePaginationReturn,
-} from './useXDSTablePagination';
+export {useXDSTablePagination, paginateData} from './useXDSTablePagination';
+export type {UseXDSTablePaginationConfig} from './useXDSTablePagination';
diff --git a/packages/core/src/Table/plugins/pagination/useXDSTablePagination-perf.test.tsx b/packages/core/src/Table/plugins/pagination/useXDSTablePagination-perf.test.tsx
index 6f5c871195..5ece8763e2 100644
--- a/packages/core/src/Table/plugins/pagination/useXDSTablePagination-perf.test.tsx
+++ b/packages/core/src/Table/plugins/pagination/useXDSTablePagination-perf.test.tsx
@@ -12,7 +12,7 @@ import {describe, it, expect} from 'vitest';
import {render, screen, act} from '@testing-library/react';
import {useState, useMemo, useRef, useEffect} from 'react';
import {XDSTable} from '../../XDSTable';
-import {useXDSTablePagination} from './useXDSTablePagination';
+import {useXDSTablePagination, paginateData} from './useXDSTablePagination';
import type {XDSTableColumn} from '../../types';
// =============================================================================
@@ -47,7 +47,7 @@ function PluginStabilityTracker({
const [page, setPage] = useState(1);
const [pageSize, setPageSize] = useState(5);
- const pagination = useXDSTablePagination<TestRow>({
+ const plugin = useXDSTablePagination<TestRow>({
page,
onPageChange: setPage,
totalItems: data.length,
@@ -56,11 +56,11 @@ function PluginStabilityTracker({
pageSizeOptions: [5, 10, 20],
});
- const prevPluginRef = useRef(pagination.plugin);
+ const prevPluginRef = useRef(plugin);
useEffect(() => {
- if (prevPluginRef.current !== pagination.plugin) {
+ if (prevPluginRef.current !== plugin) {
pluginChanges.count++;
- prevPluginRef.current = pagination.plugin;
+ prevPluginRef.current = plugin;
}
});
@@ -82,10 +82,10 @@ function PluginStabilityTracker({
</button>
<span data-testid="page">{page}</span>
<XDSTable
- data={pagination.paginatedData(data)}
+ data={paginateData(data, page, pageSize)}
columns={columns}
idKey="id"
- plugins={{pagination: pagination.plugin}}
+ plugins={{pagination: plugin}}
/>
</div>
);
@@ -105,7 +105,7 @@ function PaginationRenderCountTable({
const [page, setPage] = useState(1);
const pageSize = 5;
- const pagination = useXDSTablePagination<TestRow>({
+ const plugin = useXDSTablePagination<TestRow>({
page,
onPageChange: setPage,
totalItems: data.length,
@@ -132,10 +132,10 @@ function PaginationRenderCountTable({
Next
</button>
<XDSTable
- data={pagination.paginatedData(data)}
+ data={paginateData(data, page, pageSize)}
columns={columns}
idKey="id"
- plugins={{pagination: pagination.plugin}}
+ plugins={{pagination: plugin}}
/>
</div>
);
@@ -150,7 +150,9 @@ describe('Pagination plugin render performance', () => {
const data = createTestData(20);
const pluginChanges = {count: 0};
- render(<PluginStabilityTracker data={data} pluginChanges={pluginChanges} />);
+ render(
+ <PluginStabilityTracker data={data} pluginChanges={pluginChanges} />,
+ );
// Go to page 2
await act(async () => {
@@ -171,7 +173,9 @@ describe('Pagination plugin render performance', () => {
const data = createTestData(20);
const pluginChanges = {count: 0};
- render(<PluginStabilityTracker data={data} pluginChanges={pluginChanges} />);
+ render(
+ <PluginStabilityTracker data={data} pluginChanges={pluginChanges} />,
+ );
// Change page size
await act(async () => {
@@ -210,45 +214,4 @@ describe('Pagination plugin render performance', () => {
expect(renderCounts[`row-${i}`]).toBe(1);
}
});
-
- it('paginatedData should return stable reference when page/pageSize unchanged', () => {
- const data = createTestData(20);
- let capturedPaginatedData: ((d: TestRow[]) => TestRow[]) | null = null;
- let renderCount = 0;
-
- function TestComponent() {
- const [, setForceUpdate] = useState(0);
- renderCount++;
-
- const pagination = useXDSTablePagination<TestRow>({
- page: 1,
- onPageChange: () => {},
- totalItems: data.length,
- pageSize: 5,
- });
-
- capturedPaginatedData = pagination.paginatedData;
-
- return (
- <button
- data-testid="force-update"
- onClick={() => setForceUpdate(n => n + 1)}>
- Force
- </button>
- );
- }
-
- render(<TestComponent />);
- const firstRef = capturedPaginatedData;
- expect(renderCount).toBe(1);
-
- // Force re-render without changing page or pageSize
- act(() => {
- screen.getByTestId('force-update').click();
- });
-
- expect(renderCount).toBe(2);
- // paginatedData should be the same reference
- expect(capturedPaginatedData).toBe(firstRef);
- });
});
diff --git a/packages/core/src/Table/plugins/pagination/useXDSTablePagination.test.tsx b/packages/core/src/Table/plugins/pagination/useXDSTablePagination.test.tsx
index 33a1dd77de..4a049d5078 100644
--- a/packages/core/src/Table/plugins/pagination/useXDSTablePagination.test.tsx
+++ b/packages/core/src/Table/plugins/pagination/useXDSTablePagination.test.tsx
@@ -7,11 +7,11 @@
import {describe, it, expect, vi} from 'vitest';
import {useState} from 'react';
-import {render, screen, within} from '@testing-library/react';
+import {render, screen} from '@testing-library/react';
import userEvent from '@testing-library/user-event';
-import {renderHook, act} from '@testing-library/react';
+import {renderHook} from '@testing-library/react';
import {XDSTable} from '../../XDSTable';
-import {useXDSTablePagination} from './useXDSTablePagination';
+import {useXDSTablePagination, paginateData} from './useXDSTablePagination';
import {useXDSTableSelection} from '../selection/useXDSTableSelection';
import type {XDSTableColumn} from '../../types';
@@ -68,7 +68,7 @@ function PaginatedTable({
const [page, setPage] = useState(1);
const [currentPageSize, setCurrentPageSize] = useState(pageSize);
- const pagination = useXDSTablePagination<TestItem>({
+ const plugin = useXDSTablePagination<TestItem>({
page,
onPageChange: setPage,
// Allow overriding with totalPages/hasMore for specific test scenarios
@@ -88,256 +88,79 @@ function PaginatedTable({
return (
<XDSTable
- data={pagination.paginatedData(data)}
+ data={paginateData(data, page, currentPageSize)}
columns={columns}
idKey="id"
- plugins={{pagination: pagination.plugin}}
+ plugins={{pagination: plugin}}
/>
);
}
// =============================================================================
-// Hook Return Value Tests
+// paginateData Utility Tests
// =============================================================================
-describe('useXDSTablePagination', () => {
- describe('hook return value', () => {
- it('returns plugin object with transformTableContext', () => {
- const {result} = renderHook(() =>
- useXDSTablePagination({page: 1, onPageChange: vi.fn(), totalItems: 50}),
- );
- expect(result.current.plugin).toBeDefined();
- expect(result.current.plugin.transformTableContext).toBeTypeOf(
- 'function',
- );
- });
-
- it('returns paginationProps matching config', () => {
- const onChange = vi.fn();
- const {result} = renderHook(() =>
- useXDSTablePagination({
- page: 2,
- onPageChange: onChange,
- totalItems: 100,
- pageSize: 25,
- variant: 'count',
- size: 'sm',
- label: 'Custom label',
- }),
- );
- const props = result.current.paginationProps;
- expect(props.page).toBe(2);
- expect(props.onChange).toBe(onChange);
- expect(props.totalItems).toBe(100);
- expect(props.pageSize).toBe(25);
- expect(props.variant).toBe('count');
- expect(props.size).toBe('sm');
- expect(props.label).toBe('Custom label');
- });
-
- it('returns paginatedData function', () => {
- const {result} = renderHook(() =>
- useXDSTablePagination({page: 1, onPageChange: vi.fn(), totalItems: 50}),
- );
- expect(result.current.paginatedData).toBeTypeOf('function');
- });
-
- it('returns computed totalPages from totalItems and pageSize', () => {
- const {result} = renderHook(() =>
- useXDSTablePagination({
- page: 1,
- onPageChange: vi.fn(),
- totalItems: 100,
- pageSize: 25,
- }),
- );
- expect(result.current.totalPages).toBe(4);
- });
-
- it('returns totalPages directly when totalPagesProp is provided', () => {
- const {result} = renderHook(() =>
- useXDSTablePagination({
- page: 1,
- onPageChange: vi.fn(),
- totalPages: 7,
- }),
- );
- expect(result.current.totalPages).toBe(7);
- });
-
- it('returns undefined totalPages when using hasMore', () => {
- const {result} = renderHook(() =>
- useXDSTablePagination({
- page: 1,
- onPageChange: vi.fn(),
- hasMore: true,
- }),
- );
- expect(result.current.totalPages).toBeUndefined();
- });
-
- it('defaults pageSize to 10', () => {
- const {result} = renderHook(() =>
- useXDSTablePagination({page: 1, onPageChange: vi.fn(), totalItems: 50}),
- );
- expect(result.current.pageSize).toBe(10);
- });
-
- it('defaults variant to pages', () => {
- const {result} = renderHook(() =>
- useXDSTablePagination({page: 1, onPageChange: vi.fn(), totalItems: 50}),
- );
- expect(result.current.paginationProps.variant).toBe('pages');
- });
-
- it('defaults position to below', () => {
- // Verify default by checking that pagination renders after the table
- render(<PaginatedTable data={generateItems(20)} />);
- const nav = screen.getByRole('navigation', {name: 'Table pagination'});
- expect(nav).toBeInTheDocument();
- });
+describe('paginateData', () => {
+ it('slices data for page 1', () => {
+ const data = generateItems(30);
+ const sliced = paginateData(data, 1, 10);
+ expect(sliced).toHaveLength(10);
+ expect(sliced[0].id).toBe('1');
+ expect(sliced[9].id).toBe('10');
});
- // ===========================================================================
- // paginatedData Helper
- // ===========================================================================
-
- describe('paginatedData helper', () => {
- it('slices data for page 1', () => {
- const {result} = renderHook(() =>
- useXDSTablePagination({
- page: 1,
- onPageChange: vi.fn(),
- totalItems: 30,
- pageSize: 10,
- }),
- );
- const data = generateItems(30);
- const sliced = result.current.paginatedData(data);
- expect(sliced).toHaveLength(10);
- expect(sliced[0].id).toBe('1');
- expect(sliced[9].id).toBe('10');
- });
-
- it('slices data for page 2', () => {
- const {result} = renderHook(() =>
- useXDSTablePagination({
- page: 2,
- onPageChange: vi.fn(),
- totalItems: 30,
- pageSize: 10,
- }),
- );
- const data = generateItems(30);
- const sliced = result.current.paginatedData(data);
- expect(sliced).toHaveLength(10);
- expect(sliced[0].id).toBe('11');
- expect(sliced[9].id).toBe('20');
- });
-
- it('slices data for last page with partial data', () => {
- const {result} = renderHook(() =>
- useXDSTablePagination({
- page: 3,
- onPageChange: vi.fn(),
- totalItems: 23,
- pageSize: 10,
- }),
- );
- const data = generateItems(23);
- const sliced = result.current.paginatedData(data);
- expect(sliced).toHaveLength(3);
- expect(sliced[0].id).toBe('21');
- expect(sliced[2].id).toBe('23');
- });
-
- it('returns empty array for empty data', () => {
- const {result} = renderHook(() =>
- useXDSTablePagination({
- page: 1,
- onPageChange: vi.fn(),
- totalItems: 0,
- pageSize: 10,
- }),
- );
- expect(result.current.paginatedData([])).toEqual([]);
- });
+ it('slices data for page 2', () => {
+ const data = generateItems(30);
+ const sliced = paginateData(data, 2, 10);
+ expect(sliced).toHaveLength(10);
+ expect(sliced[0].id).toBe('11');
+ expect(sliced[9].id).toBe('20');
+ });
- it('returns empty array when page exceeds data', () => {
- const {result} = renderHook(() =>
- useXDSTablePagination({
- page: 5,
- onPageChange: vi.fn(),
- totalItems: 10,
- pageSize: 10,
- }),
- );
- const data = generateItems(10);
- expect(result.current.paginatedData(data)).toEqual([]);
- });
+ it('slices data for last page with partial data', () => {
+ const data = generateItems(23);
+ const sliced = paginateData(data, 3, 10);
+ expect(sliced).toHaveLength(3);
+ expect(sliced[0].id).toBe('21');
+ expect(sliced[2].id).toBe('23');
+ });
- it('updates slice when page changes', () => {
- let page = 1;
- const {result, rerender} = renderHook(() =>
- useXDSTablePagination({
- page,
- onPageChange: vi.fn(),
- totalItems: 30,
- pageSize: 10,
- }),
- );
- const data = generateItems(30);
- expect(result.current.paginatedData(data)[0].id).toBe('1');
+ it('returns empty array for empty data', () => {
+ expect(paginateData([], 1, 10)).toEqual([]);
+ });
- page = 2;
- rerender();
- expect(result.current.paginatedData(data)[0].id).toBe('11');
- });
+ it('returns empty array when page exceeds data', () => {
+ const data = generateItems(10);
+ expect(paginateData(data, 5, 10)).toEqual([]);
+ });
- it('updates slice when pageSize changes', () => {
- let pageSize = 10;
- const {result, rerender} = renderHook(() =>
- useXDSTablePagination({
- page: 1,
- onPageChange: vi.fn(),
- totalItems: 30,
- pageSize,
- }),
- );
- const data = generateItems(30);
- expect(result.current.paginatedData(data)).toHaveLength(10);
+ it('handles data shorter than pageSize', () => {
+ const data = generateItems(3);
+ expect(paginateData(data, 1, 10)).toHaveLength(3);
+ });
+});
- pageSize = 5;
- rerender();
- expect(result.current.paginatedData(data)).toHaveLength(5);
- });
+// =============================================================================
+// Plugin Hook Tests
+// =============================================================================
- it('handles data shorter than pageSize', () => {
+describe('useXDSTablePagination', () => {
+ describe('plugin hook', () => {
+ it('returns a TablePlugin with transformTableContext', () => {
const {result} = renderHook(() =>
- useXDSTablePagination({
- page: 1,
- onPageChange: vi.fn(),
- totalItems: 3,
- pageSize: 10,
- }),
+ useXDSTablePagination({page: 1, onPageChange: vi.fn(), totalItems: 50}),
);
- const data = generateItems(3);
- const sliced = result.current.paginatedData(data);
- expect(sliced).toHaveLength(3);
+ expect(result.current).toBeDefined();
+ expect(result.current.transformTableContext).toBeTypeOf('function');
});
- it('memoizes paginatedData callback', () => {
+ it('plugin reference is stable across renders', () => {
const {result, rerender} = renderHook(() =>
- useXDSTablePagination({
- page: 1,
- onPageChange: vi.fn(),
- totalItems: 30,
- pageSize: 10,
- }),
+ useXDSTablePagination({page: 1, onPageChange: vi.fn(), totalItems: 50}),
);
- const first = result.current.paginatedData;
+ const first = result.current;
rerender();
- expect(result.current.paginatedData).toBe(first);
+ expect(result.current).toBe(first);
});
});
@@ -513,7 +336,7 @@ describe('useXDSTablePagination', () => {
const data = generateItems(20);
const [selectedIds, setSelectedIds] = useState<Set<string>>(new Set());
- const pagination = useXDSTablePagination<TestItem>({
+ const plugin = useXDSTablePagination<TestItem>({
page,
onPageChange: setPage,
totalItems: data.length,
@@ -529,13 +352,13 @@ describe('useXDSTablePagination', () => {
setSelectedIds(next);
},
onSelectAll: ({isAllSelected}) => {
- const pageData = pagination.paginatedData(data);
+ const pageData = paginateData(data, page, 10);
setSelectedIds(
isAllSelected ? new Set(pageData.map(d => d.id)) : new Set(),
);
},
getIsAllSelected: () => {
- const pageData = pagination.paginatedData(data);
+ const pageData = paginateData(data, page, 10);
return (
pageData.length > 0 && pageData.every(d => selectedIds.has(d.id))
);
@@ -544,10 +367,10 @@ describe('useXDSTablePagination', () => {
return (
<XDSTable
- data={pagination.paginatedData(data)}
+ data={paginateData(data, page, 10)}
columns={columns}
idKey="id"
- plugins={{selection, pagination: pagination.plugin}}
+ plugins={{selection, pagination: plugin}}
/>
);
}
@@ -565,7 +388,7 @@ describe('useXDSTablePagination', () => {
const [page, setPage] = useState(1);
const data = generateItems(20);
- const pagination = useXDSTablePagination<TestItem>({
+ const plugin = useXDSTablePagination<TestItem>({
page,
onPageChange: setPage,
totalItems: data.length,
@@ -581,10 +404,10 @@ describe('useXDSTablePagination', () => {
return (
<XDSTable
- data={pagination.paginatedData(data)}
+ data={paginateData(data, page, 10)}
columns={columns}
idKey="id"
- plugins={{pagination: pagination.plugin, selection}}
+ plugins={{pagination: plugin, selection}}
/>
);
}
@@ -595,24 +418,6 @@ describe('useXDSTablePagination', () => {
screen.getByRole('navigation', {name: 'Table pagination'}),
).toBeInTheDocument();
});
-
- it('page size change updates totalPages', () => {
- const {result, rerender} = renderHook(
- ({pageSize}: {pageSize: number}) =>
- useXDSTablePagination({
- page: 1,
- onPageChange: vi.fn(),
- totalItems: 50,
- pageSize,
- }),
- {initialProps: {pageSize: 10}},
- );
-
- expect(result.current.totalPages).toBe(5);
-
- rerender({pageSize: 25});
- expect(result.current.totalPages).toBe(2);
- });
});
// ===========================================================================
@@ -655,7 +460,7 @@ describe('useXDSTablePagination', () => {
it('passes hasMore for cursor-based pagination', () => {
function CursorTable() {
const [page, setPage] = useState(1);
- const pagination = useXDSTablePagination<TestItem>({
+ const plugin = useXDSTablePagination<TestItem>({
page,
onPageChange: setPage,
hasMore: true,
@@ -666,7 +471,7 @@ describe('useXDSTablePagination', () => {
data={generateItems(10)}
columns={columns}
idKey="id"
- plugins={{pagination: pagination.plugin}}
+ plugins={{pagination: plugin}}
/>
);
}
@@ -698,16 +503,11 @@ describe('useXDSTablePagination', () => {
// ===========================================================================
describe('edge cases', () => {
- it('handles totalItems=0 gracefully', () => {
- const {result} = renderHook(() =>
- useXDSTablePagination({
- page: 1,
- onPageChange: vi.fn(),
- totalItems: 0,
- pageSize: 10,
- }),
- );
- expect(result.current.totalPages).toBe(0);
+ it('handles totalItems=0 \u2014 pagination is hidden', () => {
+ render(<PaginatedTable data={[]} pageSize={10} />);
+ expect(
+ screen.queryByRole('navigation', {name: 'Table pagination'}),
+ ).not.toBeInTheDocument();
});
it('handles totalPages=1 — pagination is hidden', () => {
@@ -720,7 +520,7 @@ describe('useXDSTablePagination', () => {
it('handles page=1 with no totalItems or totalPages (cursor mode)', () => {
function CursorTable() {
- const pagination = useXDSTablePagination<TestItem>({
+ const plugin = useXDSTablePagination<TestItem>({
page: 1,
onPageChange: vi.fn(),
hasMore: false,
@@ -730,7 +530,7 @@ describe('useXDSTablePagination', () => {
data={generateItems(5)}
columns={columns}
idKey="id"
- plugins={{pagination: pagination.plugin}}
+ plugins={{pagination: plugin}}
/>
);
}
diff --git a/packages/core/src/Table/plugins/pagination/useXDSTablePagination.tsx b/packages/core/src/Table/plugins/pagination/useXDSTablePagination.tsx
index 312b758a41..c5238301c4 100644
--- a/packages/core/src/Table/plugins/pagination/useXDSTablePagination.tsx
+++ b/packages/core/src/Table/plugins/pagination/useXDSTablePagination.tsx
@@ -3,15 +3,20 @@
/**
* @file useXDSTablePagination.tsx
* @input React, XDSPagination, Table plugin types
- * @output Exports useXDSTablePagination hook and config/return types
+ * @output Exports useXDSTablePagination hook, config type, and paginateData utility
* @position Pagination plugin; consumed by XDSTable via plugins prop
*
+ * Returns a `TablePlugin` directly (same pattern as useXDSTableSortable,
+ * useXDSTableSelection, useXDSTableColumnSettings).
+ *
+ * For client-side data slicing, use the `paginateData` utility.
+ *
* SYNC: When modified, update these files to stay in sync:
* - /packages/core/src/Table/plugins/pagination/index.ts (exports)
* - /packages/core/src/Table/index.ts (exports)
*/
-import {useCallback, useMemo, useRef, type ReactNode} from 'react';
+import {useMemo, useRef, type ReactNode} from 'react';
import * as stylex from '@stylexjs/stylex';
import {spacingVars} from '../../../theme/tokens.stylex';
import {XDSPagination} from '../../../Pagination';
@@ -50,16 +55,16 @@ const styles = stylex.create({
/**
* Configuration for useXDSTablePagination.
*
- * Headless pagination state management for XDSTable. The consumer owns all
- * state — this hook provides data helpers and a plugin that integrates with
- * the table's plugin pipeline.
+ * The consumer owns all state. This hook renders pagination controls
+ * around the table via `transformTableContext`.
*
* @example
* ```
+ * // Client-side pagination
* const [page, setPage] = useState(1);
- * const [pageSize, setPageSize] = useState(20);
+ * const pageSize = 10;
*
- * const pagination = useXDSTablePagination({
+ * const plugin = useXDSTablePagination({
* page,
* onPageChange: setPage,
* totalItems: data.length,
@@ -67,44 +72,33 @@ const styles = stylex.create({
* });
*
* <XDSTable
- * data={pagination.paginatedData(data)}
+ * data={paginateData(data, page, pageSize)}
* columns={columns}
- * plugins={{ pagination: pagination.plugin }}
+ * plugins={{ pagination: plugin }}
* />
* ```
*
* @example
* ```
- * const pagination = useXDSTablePagination({
+ * // Server-side pagination \u2014 data already sliced
+ * const plugin = useXDSTablePagination({
* page,
* onPageChange: (p) => fetchPage(p),
* totalItems: serverTotal,
* pageSize: 25,
* });
*
- * // Data is already sliced by the server — don't use paginatedData()
* <XDSTable
* data={serverData}
* columns={columns}
- * plugins={{ pagination: pagination.plugin }}
+ * plugins={{ pagination: plugin }}
* />
* ```
*
* @example
* ```
- * const pagination = useXDSTablePagination({
- * page,
- * onPageChange: setPage,
- * totalItems: data.length,
- * pageSize,
- * onPageSizeChange: setPageSize,
- * pageSizeOptions: [10, 25, 50, 100],
- * });
- * ```
- *
- * @example
- * ```
- * const pagination = useXDSTablePagination({
+ * // Cursor-based pagination \u2014 total unknown
+ * const plugin = useXDSTablePagination({
* page,
* onPageChange: setPage,
* hasMore: cursor != null,
@@ -125,7 +119,7 @@ export interface UseXDSTablePaginationConfig {
/**
* Total number of items across all pages.
- * Used to calculate total page count and "X–Y of Z" display.
+ * Used to calculate total page count and "X\u2013Y of Z" display.
* Takes precedence over `totalPages` if both are provided.
*/
totalItems?: number;
@@ -182,21 +176,20 @@ export interface UseXDSTablePaginationConfig {
/**
* Where to render the pagination controls relative to the table.
- * - 'below' — renders pagination after the table (default)
- * - 'above' — renders pagination before the table
- * - 'both' — renders pagination above and below the table
- * - 'none' — does not auto-render; use `paginationProps` manually
+ * - 'below' \u2014 renders pagination after the table (default)
+ * - 'above' \u2014 renders pagination before the table
+ * - 'both' \u2014 renders pagination above and below the table
+ * - 'none' \u2014 does not auto-render; use XDSPagination manually
*
- * Only applies when using the plugin's `transformTableContext`.
* @default 'below'
*/
position?: 'below' | 'above' | 'both' | 'none';
/**
* Horizontal alignment of the pagination controls within their container.
- * - 'start' — left-aligned
- * - 'center' — centered (default)
- * - 'end' — right-aligned
+ * - 'start' \u2014 left-aligned
+ * - 'center' \u2014 centered (default)
+ * - 'end' \u2014 right-aligned
*
* @default 'center'
*/
@@ -212,61 +205,68 @@ export interface UseXDSTablePaginationConfig {
}
// =============================================================================
-// Return Type
+// Utility
// =============================================================================
/**
- * Return value of useXDSTablePagination.
+ * Slice a data array for the current page.
+ *
+ * Pure utility for client-side pagination. For server-side pagination
+ * where data is already sliced, pass it directly to XDSTable.
+ *
+ * @param data - Full data array
+ * @param page - Current page number (1-based)
+ * @param pageSize - Number of items per page
+ * @returns Slice of data for the current page
+ *
+ * @example
+ * ```
+ * const [page, setPage] = useState(1);
+ * const pageSize = 10;
+ *
+ * <XDSTable data={paginateData(data, page, pageSize)} ... />
+ * ```
*/
-export interface UseXDSTablePaginationReturn<
- T extends Record<string, unknown>,
-> {
- /** The TablePlugin to pass to XDSTable's plugins prop. */
- plugin: TablePlugin<T>;
-
- /**
- * Props to spread onto an XDSPagination component.
- * Use this when `position` is 'none' and you want to render
- * pagination controls in a custom location.
- *
- * @example
- * ```
- * <div className="toolbar">
- * <XDSPagination {...pagination.paginationProps} />
- * </div>
- * ```
- */
- paginationProps: XDSPaginationProps;
-
- /**
- * Slices the full data array for the current page.
- * Use for client-side pagination where you have all the data.
- * For server-side pagination (data already sliced), pass data directly.
- *
- * @example
- * ```
- * <XDSTable data={pagination.paginatedData(allData)} ... />
- * ```
- */
- paginatedData: (data: T[]) => T[];
-
- /** Current page number (1-based). */
- page: number;
-
- /** Computed total number of pages (undefined for cursor-based). */
- totalPages: number | undefined;
-
- /** Current page size. */
- pageSize: number;
+export function paginateData<T>(
+ data: T[],
+ page: number,
+ pageSize: number,
+): T[] {
+ const start = (page - 1) * pageSize;
+ return data.slice(start, start + pageSize);
}
// =============================================================================
// Hook
// =============================================================================
+/**
+ * Pagination table plugin \u2014 renders XDSPagination controls around the table.
+ *
+ * Returns a `TablePlugin` directly (same pattern as `useXDSTableSortable`,
+ * `useXDSTableSelection`, `useXDSTableColumnSettings`).
+ *
+ * @example
+ * ```
+ * const [page, setPage] = useState(1);
+ * const pageSize = 10;
+ *
+ * const plugin = useXDSTablePagination({
+ * page,
+ * onPageChange: setPage,
+ * totalItems: data.length,
+ * pageSize,
+ * });
+ *
+ * <XDSTable
+ * data={paginateData(data, page, pageSize)}
+ * plugins={{ pagination: plugin }}
+ * />
+ * ```
+ */
export function useXDSTablePagination<T extends Record<string, unknown>>(
config: UseXDSTablePaginationConfig,
-): UseXDSTablePaginationReturn<T> {
+): TablePlugin<T> {
const {
page,
onPageChange,
@@ -287,7 +287,7 @@ export function useXDSTablePagination<T extends Record<string, unknown>>(
totalPagesProp ??
(totalItems != null ? Math.ceil(totalItems / pageSize) : undefined);
- // Build XDSPagination props from config
+ // Build XDSPagination props
const paginationProps: XDSPaginationProps = {
page,
onChange: onPageChange,
@@ -302,25 +302,13 @@ export function useXDSTablePagination<T extends Record<string, unknown>>(
label,
};
- // Client-side data slicing helper
- const paginatedData = useCallback(
- (data: T[]): T[] => {
- const start = (page - 1) * pageSize;
- return data.slice(start, start + pageSize);
- },
- [page, pageSize],
- );
-
// Keep current config in a ref so the plugin can read the latest values
// without needing to recreate the plugin object on every change.
const configRef = useRef({paginationProps, position, align});
configRef.current = {paginationProps, position, align};
- // Stable plugin object — created once, reads config via ref.
- // The transformTableContext renders XDSPagination which reads current
- // props from the ref, so the pagination UI always reflects the latest state
- // without changing the plugin identity.
- const plugin = useMemo(
+ // Stable plugin object \u2014 created once, reads config via ref.
+ return useMemo(
(): TablePlugin<T> => ({
transformTableContext(children: ReactNode) {
const {
@@ -331,7 +319,6 @@ export function useXDSTablePagination<T extends Record<string, unknown>>(
if (pos === 'none') return children;
// Don't render pagination when there's only one page and no more data.
- // This can happen when filters reduce the result set to a single page.
const resolvedTotalPages =
props.totalPages ??
(props.totalItems != null && props.pageSize != null
@@ -365,13 +352,4 @@ export function useXDSTablePagination<T extends Record<string, unknown>>(
}),
[],
);
-
- return {
- plugin,
- paginationProps,
- paginatedData,
- page,
- totalPages: computedTotalPages,
- pageSize,
- };
}