Skip to content

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

TypeScript

feat(Table): useXDSTablePagination plugin #978 (#1011)

Cindy Zhangf820f2db7df6
diff --git a/apps/storybook/stories/TablePagination.stories.tsx b/apps/storybook/stories/TablePagination.stories.tsx
new file mode 100644
index 0000000000..8fecf3f89a
--- /dev/null
+++ b/apps/storybook/stories/TablePagination.stories.tsx
@@ -0,0 +1,392 @@
+import {useState} from 'react';
+import type {Meta, StoryObj} from '@storybook/react';
+import {
+ XDSTable,
+ useXDSTablePagination,
+ useXDSTableSelection,
+ useXDSTableSelectionState,
+} from '@xds/core/Table';
+import type {XDSTableColumn} from '@xds/core/Table';
+
+// =============================================================================
+// Sample Data
+// =============================================================================
+
+interface User extends Record<string, unknown> {
+ id: string;
+ name: string;
+ email: string;
+ role: string;
+}
+
+const users: User[] = Array.from({length: 50}, (_, i) => ({
+ id: String(i + 1),
+ name: `User ${i + 1}`,
+ email: `user${i + 1}@example.com`,
+ role: ['Engineer', 'Designer', 'Manager', 'Admin', 'Analyst'][i % 5],
+}));
+
+const columns: XDSTableColumn<User>[] = [
+ {key: 'name', header: 'Name'},
+ {key: 'email', header: 'Email'},
+ {key: 'role', header: 'Role'},
+];
+
+// =============================================================================
+// Types
+// =============================================================================
+
+type Variant = 'pages' | 'count' | 'compact' | 'dots' | 'none';
+type Position = 'below' | 'above' | 'both' | 'none';
+type Align = 'start' | 'center' | 'end';
+
+// =============================================================================
+// Shared render helper
+// =============================================================================
+
+function PaginatedDemo({
+ variant = 'pages',
+ position = 'below',
+ align = 'start',
+}: {
+ variant?: Variant;
+ position?: Position;
+ align?: Align;
+}) {
+ const [page, setPage] = useState(1);
+
+ const pagination = useXDSTablePagination<User>({
+ page,
+ onPageChange: setPage,
+ totalItems: users.length,
+ pageSize: 10,
+ variant,
+ position,
+ align,
+ });
+
+ return (
+ <XDSTable
+ data={pagination.paginatedData(users)}
+ columns={columns}
+ idKey="id"
+ plugins={{pagination: pagination.plugin}}
+ />
+ );
+}
+
+// =============================================================================
+// Stories
+// =============================================================================
+
+const meta: Meta = {
+ title: 'Core/XDSTable/Pagination',
+ tags: ['autodocs'],
+};
+
+export default meta;
+type Story = StoryObj;
+
+export const Default: Story = {
+ render: () => {
+ const [page, setPage] = useState(1);
+
+ const pagination = useXDSTablePagination<User>({
+ page,
+ onPageChange: setPage,
+ totalItems: users.length,
+ pageSize: 10,
+ });
+
+ return (
+ <div style={{maxWidth: 600}}>
+ <XDSTable
+ data={pagination.paginatedData(users)}
+ columns={columns}
+ idKey="id"
+ plugins={{pagination: pagination.plugin}}
+ />
+ </div>
+ );
+ },
+};
+
+export const ServerSide: Story = {
+ render: () => {
+ const [page, setPage] = useState(1);
+ const pageSize = 10;
+
+ const serverData = users.slice((page - 1) * pageSize, page * pageSize);
+
+ const pagination = useXDSTablePagination<User>({
+ page,
+ onPageChange: setPage,
+ totalItems: users.length,
+ pageSize,
+ });
+
+ return (
+ <div style={{maxWidth: 600}}>
+ <p style={{marginBottom: 8, fontSize: 14, color: '#666'}}>
+ Server-side: data is pre-sliced, no paginatedData() needed.
+ </p>
+ <XDSTable
+ data={serverData}
+ columns={columns}
+ idKey="id"
+ plugins={{pagination: pagination.plugin}}
+ />
+ </div>
+ );
+ },
+};
+
+export const PageSizeSelector: Story = {
+ render: () => {
+ const [page, setPage] = useState(1);
+ const [pageSize, setPageSize] = useState(10);
+
+ const pagination = useXDSTablePagination<User>({
+ page,
+ onPageChange: setPage,
+ totalItems: users.length,
+ pageSize,
+ onPageSizeChange: setPageSize,
+ pageSizeOptions: [5, 10, 25, 50],
+ });
+
+ return (
+ <div style={{maxWidth: 600}}>
+ <XDSTable
+ data={pagination.paginatedData(users)}
+ columns={columns}
+ idKey="id"
+ plugins={{pagination: pagination.plugin}}
+ />
+ </div>
+ );
+ },
+};
+
+export const CursorBased: Story = {
+ render: () => {
+ const [page, setPage] = useState(1);
+ const pageSize = 10;
+
+ const hasMore = page * pageSize < users.length;
+
+ const pagination = useXDSTablePagination<User>({
+ page,
+ onPageChange: setPage,
+ hasMore,
+ pageSize,
+ });
+
+ return (
+ <div style={{maxWidth: 600}}>
+ <p style={{marginBottom: 8, fontSize: 14, color: '#666'}}>
+ Cursor-based: total unknown, only hasMore={String(hasMore)}.
+ </p>
+ <XDSTable
+ data={pagination.paginatedData(users)}
+ columns={columns}
+ idKey="id"
+ plugins={{pagination: pagination.plugin}}
+ />
+ </div>
+ );
+ },
+};
+
+export const PositionAbove: Story = {
+ render: () => {
+ const [page, setPage] = useState(1);
+
+ const pagination = useXDSTablePagination<User>({
+ page,
+ onPageChange: setPage,
+ totalItems: users.length,
+ pageSize: 10,
+ position: 'above',
+ });
+
+ return (
+ <div style={{maxWidth: 600}}>
+ <XDSTable
+ data={pagination.paginatedData(users)}
+ columns={columns}
+ idKey="id"
+ plugins={{pagination: pagination.plugin}}
+ />
+ </div>
+ );
+ },
+};
+
+export const PositionBoth: Story = {
+ render: () => {
+ const [page, setPage] = useState(1);
+
+ const pagination = useXDSTablePagination<User>({
+ page,
+ onPageChange: setPage,
+ totalItems: users.length,
+ pageSize: 10,
+ position: 'both',
+ });
+
+ return (
+ <div style={{maxWidth: 600}}>
+ <XDSTable
+ data={pagination.paginatedData(users)}
+ columns={columns}
+ idKey="id"
+ plugins={{pagination: pagination.plugin}}
+ />
+ </div>
+ );
+ },
+};
+
+export const WithSelection: Story = {
+ render: () => {
+ const [page, setPage] = useState(1);
+ const [selectedKeys, setSelectedKeys] = useState<Set<string>>(new Set());
+
+ const pagination = useXDSTablePagination<User>({
+ page,
+ onPageChange: setPage,
+ totalItems: users.length,
+ pageSize: 10,
+ });
+
+ const pageData = pagination.paginatedData(users);
+
+ const {selectionConfig} = useXDSTableSelectionState<User>({
+ data: pageData,
+ idKey: 'id',
+ selectedKeys,
+ setSelectedKeys,
+ });
+ const selectionPlugin = useXDSTableSelection<User>(selectionConfig);
+
+ return (
+ <div style={{maxWidth: 600}}>
+ <p style={{marginBottom: 8, fontSize: 14, color: '#666'}}>
+ Pagination + Selection composed. Selected: {selectedKeys.size}
+ </p>
+ <XDSTable
+ data={pageData}
+ columns={columns}
+ idKey="id"
+ plugins={{
+ selection: selectionPlugin,
+ pagination: pagination.plugin,
+ }}
+ />
+ </div>
+ );
+ },
+};
+
+/**
+ * Interactive playground — use the controls panel to explore every combination
+ * of variant, position, and align.
+ */
+export const Playground: Story = {
+ argTypes: {
+ variant: {
+ control: 'select',
+ options: ['pages', 'count', 'compact', 'dots', 'none'],
+ description: 'What appears between prev/next buttons',
+ },
+ position: {
+ control: 'select',
+ options: ['below', 'above', 'both', 'none'],
+ description: 'Where pagination renders relative to the table',
+ },
+ align: {
+ control: 'select',
+ options: ['start', 'center', 'end'],
+ description: 'Horizontal alignment of the pagination controls',
+ },
+ },
+ args: {
+ variant: 'pages',
+ position: 'below',
+ align: 'center',
+ },
+ render: (args: {variant: Variant; position: Position; align: Align}) => (
+ <div style={{maxWidth: 700}}>
+ <PaginatedDemo
+ variant={args.variant}
+ position={args.position}
+ align={args.align}
+ />
+ </div>
+ ),
+};
+
+// =============================================================================
+// Options Matrix
+// =============================================================================
+
+const VARIANTS: Variant[] = ['pages', 'count', 'compact', 'dots'];
+const POSITIONS: Position[] = ['below', 'above', 'both'];
+const ALIGNS: Align[] = ['start', 'center', 'end'];
+
+/**
+ * All variant × position × align combinations in one scrollable view.
+ * One row per combination, labelled clearly. The `none` values are omitted.
+ */
+export const OptionsMatrix: Story = {
+ render: () => (
+ <div style={{fontFamily: 'sans-serif', maxWidth: 700}}>
+ {VARIANTS.flatMap(variant =>
+ POSITIONS.flatMap(position =>
+ ALIGNS.map(align => (
+ <div
+ key={`${variant}-${position}-${align}`}
+ style={{
+ marginBottom: 48,
+ paddingBottom: 48,
+ borderBottom: '1px solid #e5e5e5',
+ }}>
+ <div
+ style={{
+ display: 'inline-flex',
+ gap: 8,
+ marginBottom: 12,
+ flexWrap: 'wrap',
+ }}>
+ {[
+ {label: 'variant', value: variant},
+ {label: 'position', value: position},
+ {label: 'align', value: align},
+ ].map(({label, value}) => (
+ <span
+ key={label}
+ style={{
+ fontSize: 11,
+ fontFamily: 'monospace',
+ background: '#f0f0f0',
+ borderRadius: 4,
+ padding: '2px 6px',
+ color: '#555',
+ }}>
+ {label}=&quot;{value}&quot;
+ </span>
+ ))}
+ </div>
+ <PaginatedDemo
+ variant={variant}
+ position={position}
+ align={align}
+ />
+ </div>
+ )),
+ ),
+ )}
+ </div>
+ ),
+};
diff --git a/packages/core/src/Table/index.ts b/packages/core/src/Table/index.ts
index 5bea5415ed..2eaa448437 100644
--- a/packages/core/src/Table/index.ts
+++ b/packages/core/src/Table/index.ts
@@ -18,6 +18,7 @@ export {XDSTableContext} from './XDSTableContext';
export {useXDSTableSelection} from './plugins/selection';
export {useXDSTableSelectionState} from './plugins/selection';
export {useXDSTableSortable} from './plugins/sortable';
+export {useXDSTablePagination} from './plugins/pagination';
export {useXDSBaseTablePlugins} from './useXDSBaseTablePlugins';
export {
proportional,
@@ -62,3 +63,7 @@ export type {
XDSTableSortState,
} from './plugins/sortable';
export type {XDSTableSortableColumnConfig} from './types';
+export type {
+ UseXDSTablePaginationConfig,
+ UseXDSTablePaginationReturn,
+} from './plugins/pagination';
diff --git a/packages/core/src/Table/plugins/pagination/index.ts b/packages/core/src/Table/plugins/pagination/index.ts
new file mode 100644
index 0000000000..501ac4d2f7
--- /dev/null
+++ b/packages/core/src/Table/plugins/pagination/index.ts
@@ -0,0 +1,5 @@
+export {useXDSTablePagination} from './useXDSTablePagination';
+export type {
+ UseXDSTablePaginationConfig,
+ UseXDSTablePaginationReturn,
+} 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
new file mode 100644
index 0000000000..6f5c871195
--- /dev/null
+++ b/packages/core/src/Table/plugins/pagination/useXDSTablePagination-perf.test.tsx
@@ -0,0 +1,254 @@
+/**
+ * @file useXDSTablePagination-perf.test.tsx
+ * @input useXDSTablePagination, XDSTable, React testing utilities
+ * @output Performance tests for pagination plugin render behavior
+ * @position Test file; validates plugin identity stability and render efficiency
+ *
+ * The pagination plugin should produce a referentially stable plugin object
+ * so that page/pageSize changes don't cause the entire table to re-render.
+ */
+
+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 type {XDSTableColumn} from '../../types';
+
+// =============================================================================
+// Test Data
+// =============================================================================
+
+interface TestRow extends Record<string, unknown> {
+ id: string;
+ name: string;
+}
+
+const createTestData = (count: number): TestRow[] =>
+ Array.from({length: count}, (_, i) => ({
+ id: `row-${i}`,
+ name: `Item ${i}`,
+ }));
+
+// =============================================================================
+// Helpers
+// =============================================================================
+
+/**
+ * Tracks how many times the plugin reference changes across renders.
+ */
+function PluginStabilityTracker({
+ data,
+ pluginChanges,
+}: {
+ data: TestRow[];
+ pluginChanges: {count: number};
+}) {
+ const [page, setPage] = useState(1);
+ const [pageSize, setPageSize] = useState(5);
+
+ const pagination = useXDSTablePagination<TestRow>({
+ page,
+ onPageChange: setPage,
+ totalItems: data.length,
+ pageSize,
+ onPageSizeChange: setPageSize,
+ pageSizeOptions: [5, 10, 20],
+ });
+
+ const prevPluginRef = useRef(pagination.plugin);
+ useEffect(() => {
+ if (prevPluginRef.current !== pagination.plugin) {
+ pluginChanges.count++;
+ prevPluginRef.current = pagination.plugin;
+ }
+ });
+
+ const columns = useMemo<XDSTableColumn<TestRow>[]>(
+ () => [{key: 'name', header: 'Name'}],
+ [],
+ );
+
+ return (
+ <div>
+ <button data-testid="next-page" onClick={() => setPage(p => p + 1)}>
+ Next
+ </button>
+ <button data-testid="prev-page" onClick={() => setPage(p => p - 1)}>
+ Prev
+ </button>
+ <button data-testid="change-size" onClick={() => setPageSize(10)}>
+ Size 10
+ </button>
+ <span data-testid="page">{page}</span>
+ <XDSTable
+ data={pagination.paginatedData(data)}
+ columns={columns}
+ idKey="id"
+ plugins={{pagination: pagination.plugin}}
+ />
+ </div>
+ );
+}
+
+/**
+ * Table with render counting per row to verify pagination changes
+ * don't cause all rows to re-render.
+ */
+function PaginationRenderCountTable({
+ data,
+ renderCounts,
+}: {
+ data: TestRow[];
+ renderCounts: Record<string, number>;
+}) {
+ const [page, setPage] = useState(1);
+ const pageSize = 5;
+
+ const pagination = useXDSTablePagination<TestRow>({
+ page,
+ onPageChange: setPage,
+ totalItems: data.length,
+ pageSize,
+ });
+
+ const columns = useMemo<XDSTableColumn<TestRow>[]>(
+ () => [
+ {
+ key: 'name',
+ header: 'Name',
+ renderCell: (item: TestRow) => {
+ renderCounts[item.id] = (renderCounts[item.id] ?? 0) + 1;
+ return item.name;
+ },
+ },
+ ],
+ [renderCounts],
+ );
+
+ return (
+ <div>
+ <button data-testid="next-page" onClick={() => setPage(p => p + 1)}>
+ Next
+ </button>
+ <XDSTable
+ data={pagination.paginatedData(data)}
+ columns={columns}
+ idKey="id"
+ plugins={{pagination: pagination.plugin}}
+ />
+ </div>
+ );
+}
+
+// =============================================================================
+// Tests
+// =============================================================================
+
+describe('Pagination plugin render performance', () => {
+ it('plugin identity should be stable across page changes', async () => {
+ const data = createTestData(20);
+ const pluginChanges = {count: 0};
+
+ render(<PluginStabilityTracker data={data} pluginChanges={pluginChanges} />);
+
+ // Go to page 2
+ await act(async () => {
+ screen.getByTestId('next-page').click();
+ });
+
+ // Go to page 3
+ await act(async () => {
+ screen.getByTestId('next-page').click();
+ });
+
+ expect(screen.getByTestId('page').textContent).toBe('3');
+ // Plugin reference should NOT have changed
+ expect(pluginChanges.count).toBe(0);
+ });
+
+ it('plugin identity should be stable across pageSize changes', async () => {
+ const data = createTestData(20);
+ const pluginChanges = {count: 0};
+
+ render(<PluginStabilityTracker data={data} pluginChanges={pluginChanges} />);
+
+ // Change page size
+ await act(async () => {
+ screen.getByTestId('change-size').click();
+ });
+
+ // Plugin reference should NOT have changed
+ expect(pluginChanges.count).toBe(0);
+ });
+
+ it('page change should not re-render rows that remain visible', async () => {
+ // 20 items, pageSize 5 — page 1 shows rows 0-4, page 2 shows rows 5-9
+ const data = createTestData(20);
+ const renderCounts: Record<string, number> = {};
+
+ render(
+ <PaginationRenderCountTable data={data} renderCounts={renderCounts} />,
+ );
+
+ // Initial render: rows 0-4 rendered once each
+ const initialCounts = {...renderCounts};
+ expect(Object.keys(initialCounts)).toHaveLength(5);
+
+ // Navigate to page 2
+ await act(async () => {
+ screen.getByTestId('next-page').click();
+ });
+
+ // Page 1 rows (0-4) should NOT have re-rendered — they're not in the DOM
+ for (let i = 0; i < 5; i++) {
+ expect(renderCounts[`row-${i}`]).toBe(initialCounts[`row-${i}`]);
+ }
+
+ // Page 2 rows (5-9) should each have rendered exactly once
+ for (let i = 5; i < 10; i++) {
+ 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
new file mode 100644
index 0000000000..33a1dd77de
--- /dev/null
+++ b/packages/core/src/Table/plugins/pagination/useXDSTablePagination.test.tsx
@@ -0,0 +1,801 @@
+/**
+ * @file useXDSTablePagination.test.tsx
+ * @input useXDSTablePagination, XDSTable, XDSPagination, React testing utilities
+ * @output Functional tests for the pagination plugin
+ * @position Test file; validates pagination hook behavior, data slicing, plugin rendering
+ */
+
+import {describe, it, expect, vi} from 'vitest';
+import {useState} from 'react';
+import {render, screen, within} from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+import {renderHook, act} from '@testing-library/react';
+import {XDSTable} from '../../XDSTable';
+import {useXDSTablePagination} from './useXDSTablePagination';
+import {useXDSTableSelection} from '../selection/useXDSTableSelection';
+import type {XDSTableColumn} from '../../types';
+
+// =============================================================================
+// Test Data
+// =============================================================================
+
+interface TestItem extends Record<string, unknown> {
+ id: string;
+ name: string;
+ value: number;
+}
+
+function generateItems(count: number): TestItem[] {
+ return Array.from({length: count}, (_, i) => ({
+ id: String(i + 1),
+ name: `Item ${i + 1}`,
+ value: (i + 1) * 10,
+ }));
+}
+
+const columns: XDSTableColumn<TestItem>[] = [
+ {key: 'name', header: 'Name'},
+ {key: 'value', header: 'Value'},
+];
+
+// =============================================================================
+// Helper Components
+// =============================================================================
+
+function PaginatedTable({
+ data,
+ pageSize = 10,
+ position,
+ align,
+ variant,
+ size,
+ label,
+ pageSizeOptions,
+ totalPagesProp,
+ hasMore,
+}: {
+ data: TestItem[];
+ pageSize?: number;
+ position?: 'below' | 'above' | 'both' | 'none';
+ align?: 'start' | 'center' | 'end';
+ variant?: 'pages' | 'count' | 'compact' | 'dots' | 'none';
+ size?: 'sm' | 'md';
+ label?: string;
+ pageSizeOptions?: number[];
+ totalPagesProp?: number;
+ hasMore?: boolean;
+}) {
+ const [page, setPage] = useState(1);
+ const [currentPageSize, setCurrentPageSize] = useState(pageSize);
+
+ const pagination = useXDSTablePagination<TestItem>({
+ page,
+ onPageChange: setPage,
+ // Allow overriding with totalPages/hasMore for specific test scenarios
+ totalItems:
+ totalPagesProp == null && hasMore == null ? data.length : undefined,
+ totalPages: totalPagesProp,
+ hasMore,
+ pageSize: currentPageSize,
+ position,
+ align,
+ variant,
+ size,
+ label,
+ pageSizeOptions,
+ onPageSizeChange: pageSizeOptions ? setCurrentPageSize : undefined,
+ });
+
+ return (
+ <XDSTable
+ data={pagination.paginatedData(data)}
+ columns={columns}
+ idKey="id"
+ plugins={{pagination: pagination.plugin}}
+ />
+ );
+}
+
+// =============================================================================
+// Hook Return Value 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();
+ });
+ });
+
+ // ===========================================================================
+ // 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('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('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');
+
+ page = 2;
+ rerender();
+ expect(result.current.paginatedData(data)[0].id).toBe('11');
+ });
+
+ 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);
+
+ pageSize = 5;
+ rerender();
+ expect(result.current.paginatedData(data)).toHaveLength(5);
+ });
+
+ it('handles data shorter than pageSize', () => {
+ const {result} = renderHook(() =>
+ useXDSTablePagination({
+ page: 1,
+ onPageChange: vi.fn(),
+ totalItems: 3,
+ pageSize: 10,
+ }),
+ );
+ const data = generateItems(3);
+ const sliced = result.current.paginatedData(data);
+ expect(sliced).toHaveLength(3);
+ });
+
+ it('memoizes paginatedData callback', () => {
+ const {result, rerender} = renderHook(() =>
+ useXDSTablePagination({
+ page: 1,
+ onPageChange: vi.fn(),
+ totalItems: 30,
+ pageSize: 10,
+ }),
+ );
+ const first = result.current.paginatedData;
+ rerender();
+ expect(result.current.paginatedData).toBe(first);
+ });
+ });
+
+ // ===========================================================================
+ // Plugin Behavior
+ // ===========================================================================
+
+ describe('plugin behavior', () => {
+ it('transformTableContext renders XDSPagination below table by default', () => {
+ render(<PaginatedTable data={generateItems(30)} pageSize={10} />);
+ const table = screen.getByRole('table');
+ const nav = screen.getByRole('navigation', {name: 'Table pagination'});
+ expect(table).toBeInTheDocument();
+ expect(nav).toBeInTheDocument();
+ // Nav should come after the table in DOM order
+ expect(
+ table.compareDocumentPosition(nav) & Node.DOCUMENT_POSITION_FOLLOWING,
+ ).toBeTruthy();
+ });
+
+ it('transformTableContext renders XDSPagination above table', () => {
+ render(
+ <PaginatedTable
+ data={generateItems(30)}
+ pageSize={10}
+ position="above"
+ />,
+ );
+ const table = screen.getByRole('table');
+ const nav = screen.getByRole('navigation', {name: 'Table pagination'});
+ // Nav should come before the table in DOM order
+ expect(
+ table.compareDocumentPosition(nav) & Node.DOCUMENT_POSITION_PRECEDING,
+ ).toBeTruthy();
+ });
+
+ it('transformTableContext renders XDSPagination above and below', () => {
+ render(
+ <PaginatedTable
+ data={generateItems(30)}
+ pageSize={10}
+ position="both"
+ />,
+ );
+ const navs = screen.getAllByRole('navigation', {
+ name: 'Table pagination',
+ });
+ expect(navs).toHaveLength(2);
+ });
+
+ it('transformTableContext does not render XDSPagination when position is none', () => {
+ render(
+ <PaginatedTable
+ data={generateItems(30)}
+ pageSize={10}
+ position="none"
+ />,
+ );
+ expect(
+ screen.queryByRole('navigation', {name: 'Table pagination'}),
+ ).not.toBeInTheDocument();
+ });
+
+ it('does not render pagination when there is only one page', () => {
+ // 5 items with pageSize 10 → 1 page total
+ render(<PaginatedTable data={generateItems(5)} pageSize={10} />);
+ expect(
+ screen.queryByRole('navigation', {name: 'Table pagination'}),
+ ).not.toBeInTheDocument();
+ });
+
+ it('does not render pagination when totalPages is explicitly 1', () => {
+ render(
+ <PaginatedTable
+ data={generateItems(5)}
+ pageSize={10}
+ totalPagesProp={1}
+ />,
+ );
+ expect(
+ screen.queryByRole('navigation', {name: 'Table pagination'}),
+ ).not.toBeInTheDocument();
+ });
+
+ it('renders pagination when hasMore is true even with one page of data', () => {
+ render(
+ <PaginatedTable data={generateItems(5)} pageSize={10} hasMore={true} />,
+ );
+ expect(
+ screen.getByRole('navigation', {name: 'Table pagination'}),
+ ).toBeInTheDocument();
+ });
+
+ it('renders pagination wrapper with center alignment', () => {
+ render(
+ <PaginatedTable
+ data={generateItems(30)}
+ pageSize={10}
+ align="center"
+ />,
+ );
+ const nav = screen.getByRole('navigation', {name: 'Table pagination'});
+ expect(nav.parentElement).toBeInTheDocument();
+ });
+
+ it('renders pagination wrapper with end alignment', () => {
+ render(
+ <PaginatedTable data={generateItems(30)} pageSize={10} align="end" />,
+ );
+ const nav = screen.getByRole('navigation', {name: 'Table pagination'});
+ expect(nav.parentElement).toBeInTheDocument();
+ });
+
+ it('paginationProps include pageSizeOptions when provided', () => {
+ render(
+ <PaginatedTable
+ data={generateItems(50)}
+ pageSize={10}
+ pageSizeOptions={[10, 25, 50]}
+ />,
+ );
+ expect(screen.getByLabelText('Items per page')).toBeInTheDocument();
+ });
+
+ it('paginationProps exclude pageSizeOptions when not provided', () => {
+ render(<PaginatedTable data={generateItems(50)} pageSize={10} />);
+ expect(screen.queryByLabelText('Items per page')).not.toBeInTheDocument();
+ });
+ });
+
+ // ===========================================================================
+ // Integration with XDSTable
+ // ===========================================================================
+
+ describe('integration with XDSTable', () => {
+ it('renders table with paginated data', () => {
+ render(<PaginatedTable data={generateItems(25)} pageSize={10} />);
+ const rows = screen.getAllByRole('row');
+ // 1 header row + 10 data rows
+ expect(rows).toHaveLength(11);
+ });
+
+ it('page change re-renders table with new data', async () => {
+ const user = userEvent.setup();
+ render(<PaginatedTable data={generateItems(25)} pageSize={10} />);
+
+ // Initially on page 1 — should show Item 1..10
+ expect(screen.getByText('Item 1')).toBeInTheDocument();
+ expect(screen.getByText('Item 10')).toBeInTheDocument();
+
+ // Click page 2
+ const page2Button = screen.getByRole('button', {
+ name: 'Go to page 2',
+ });
+ await user.click(page2Button);
+
+ // Now should show Item 11..20
+ expect(screen.getByText('Item 11')).toBeInTheDocument();
+ expect(screen.getByText('Item 20')).toBeInTheDocument();
+ expect(screen.queryByText('Item 1')).not.toBeInTheDocument();
+ });
+
+ it('empty data renders pagination as null', () => {
+ render(<PaginatedTable data={[]} pageSize={10} />);
+ expect(
+ screen.queryByRole('navigation', {name: 'Table pagination'}),
+ ).not.toBeInTheDocument();
+ });
+
+ it('works alongside selection plugin', () => {
+ function DualPluginTable() {
+ const [page, setPage] = useState(1);
+ const data = generateItems(20);
+ const [selectedIds, setSelectedIds] = useState<Set<string>>(new Set());
+
+ const pagination = useXDSTablePagination<TestItem>({
+ page,
+ onPageChange: setPage,
+ totalItems: data.length,
+ pageSize: 10,
+ });
+
+ const selection = useXDSTableSelection<TestItem>({
+ getIsItemSelected: item => selectedIds.has(item.id),
+ onSelectItem: ({item, isSelected}) => {
+ const next = new Set(selectedIds);
+ if (isSelected) next.add(item.id);
+ else next.delete(item.id);
+ setSelectedIds(next);
+ },
+ onSelectAll: ({isAllSelected}) => {
+ const pageData = pagination.paginatedData(data);
+ setSelectedIds(
+ isAllSelected ? new Set(pageData.map(d => d.id)) : new Set(),
+ );
+ },
+ getIsAllSelected: () => {
+ const pageData = pagination.paginatedData(data);
+ return (
+ pageData.length > 0 && pageData.every(d => selectedIds.has(d.id))
+ );
+ },
+ });
+
+ return (
+ <XDSTable
+ data={pagination.paginatedData(data)}
+ columns={columns}
+ idKey="id"
+ plugins={{selection, pagination: pagination.plugin}}
+ />
+ );
+ }
+
+ render(<DualPluginTable />);
+ expect(screen.getByRole('table')).toBeInTheDocument();
+ expect(
+ screen.getByRole('navigation', {name: 'Table pagination'}),
+ ).toBeInTheDocument();
+ expect(screen.getByLabelText('Select all rows')).toBeInTheDocument();
+ });
+
+ it('plugin order does not break rendering', () => {
+ function ReversedPluginTable() {
+ const [page, setPage] = useState(1);
+ const data = generateItems(20);
+
+ const pagination = useXDSTablePagination<TestItem>({
+ page,
+ onPageChange: setPage,
+ totalItems: data.length,
+ pageSize: 10,
+ });
+
+ const selection = useXDSTableSelection<TestItem>({
+ getIsItemSelected: () => false,
+ onSelectItem: vi.fn(),
+ onSelectAll: vi.fn(),
+ getIsAllSelected: () => false,
+ });
+
+ return (
+ <XDSTable
+ data={pagination.paginatedData(data)}
+ columns={columns}
+ idKey="id"
+ plugins={{pagination: pagination.plugin, selection}}
+ />
+ );
+ }
+
+ render(<ReversedPluginTable />);
+ expect(screen.getByRole('table')).toBeInTheDocument();
+ expect(
+ 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);
+ });
+ });
+
+ // ===========================================================================
+ // Props Passthrough to XDSPagination
+ // ===========================================================================
+
+ describe('props passthrough', () => {
+ it('passes variant prop', () => {
+ render(
+ <PaginatedTable
+ data={generateItems(30)}
+ pageSize={10}
+ variant="compact"
+ />,
+ );
+ expect(screen.getByText('Page 1 of 3')).toBeInTheDocument();
+ });
+
+ it('passes size prop', () => {
+ render(
+ <PaginatedTable data={generateItems(30)} pageSize={10} size="sm" />,
+ );
+ const nav = screen.getByRole('navigation', {name: 'Table pagination'});
+ expect(nav).toBeInTheDocument();
+ });
+
+ it('passes label prop', () => {
+ render(
+ <PaginatedTable
+ data={generateItems(30)}
+ pageSize={10}
+ label="Custom navigation"
+ />,
+ );
+ expect(
+ screen.getByRole('navigation', {name: 'Custom navigation'}),
+ ).toBeInTheDocument();
+ });
+
+ it('passes hasMore for cursor-based pagination', () => {
+ function CursorTable() {
+ const [page, setPage] = useState(1);
+ const pagination = useXDSTablePagination<TestItem>({
+ page,
+ onPageChange: setPage,
+ hasMore: true,
+ pageSize: 10,
+ });
+ return (
+ <XDSTable
+ data={generateItems(10)}
+ columns={columns}
+ idKey="id"
+ plugins={{pagination: pagination.plugin}}
+ />
+ );
+ }
+ render(<CursorTable />);
+ const nextButton = screen.getByRole('button', {
+ name: 'Go to next page',
+ });
+ expect(nextButton).not.toBeDisabled();
+ });
+
+ it('passes onPageSizeChange and pageSizeOptions', () => {
+ render(
+ <PaginatedTable
+ data={generateItems(50)}
+ pageSize={10}
+ pageSizeOptions={[10, 25, 50]}
+ />,
+ );
+
+ // Verify the page size selector is rendered with current value
+ const selector = screen.getByRole('combobox', {name: 'Items per page'});
+ expect(selector).toBeInTheDocument();
+ expect(selector).toHaveTextContent('10');
+ });
+ });
+
+ // ===========================================================================
+ // Edge Cases
+ // ===========================================================================
+
+ 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 totalPages=1 — pagination is hidden', () => {
+ // When there is only one page, the plugin should not render pagination at all.
+ render(<PaginatedTable data={generateItems(5)} pageSize={10} />);
+ expect(
+ screen.queryByRole('navigation', {name: 'Table pagination'}),
+ ).not.toBeInTheDocument();
+ });
+
+ it('handles page=1 with no totalItems or totalPages (cursor mode)', () => {
+ function CursorTable() {
+ const pagination = useXDSTablePagination<TestItem>({
+ page: 1,
+ onPageChange: vi.fn(),
+ hasMore: false,
+ });
+ return (
+ <XDSTable
+ data={generateItems(5)}
+ columns={columns}
+ idKey="id"
+ plugins={{pagination: pagination.plugin}}
+ />
+ );
+ }
+ render(<CursorTable />);
+ const prevButton = screen.getByRole('button', {
+ name: 'Go to previous page',
+ });
+ const nextButton = screen.getByRole('button', {
+ name: 'Go to next page',
+ });
+ expect(prevButton).toBeDisabled();
+ expect(nextButton).toBeDisabled();
+ });
+
+ it('handles rapid page changes', async () => {
+ const user = userEvent.setup();
+ render(<PaginatedTable data={generateItems(50)} pageSize={10} />);
+
+ const page2 = screen.getByRole('button', {name: 'Go to page 2'});
+ await user.click(page2);
+
+ const page3 = screen.getByRole('button', {name: 'Go to page 3'});
+ await user.click(page3);
+
+ // Should be on page 3 showing Item 21..30
+ expect(screen.getByText('Item 21')).toBeInTheDocument();
+ expect(screen.getByText('Item 30')).toBeInTheDocument();
+ });
+ });
+
+ // ===========================================================================
+ // Accessibility
+ // ===========================================================================
+
+ describe('accessibility', () => {
+ it('pagination nav has correct aria-label', () => {
+ render(<PaginatedTable data={generateItems(30)} pageSize={10} />);
+ expect(
+ screen.getByRole('navigation', {name: 'Table pagination'}),
+ ).toBeInTheDocument();
+ });
+
+ it('page buttons have aria-label "Go to page N"', () => {
+ render(<PaginatedTable data={generateItems(30)} pageSize={10} />);
+ expect(
+ screen.getByRole('button', {name: 'Go to page 1'}),
+ ).toBeInTheDocument();
+ expect(
+ screen.getByRole('button', {name: 'Go to page 2'}),
+ ).toBeInTheDocument();
+ });
+
+ it('current page has aria-current="page"', () => {
+ render(<PaginatedTable data={generateItems(30)} pageSize={10} />);
+ const page1Button = screen.getByRole('button', {name: 'Go to page 1'});
+ expect(page1Button).toHaveAttribute('aria-current', 'page');
+ });
+
+ it('disabled prev/next buttons have aria-disabled', () => {
+ // Use multi-page data so pagination is rendered; on page 1, prev is disabled.
+ render(<PaginatedTable data={generateItems(30)} pageSize={10} />);
+ const prevButton = screen.getByRole('button', {
+ name: 'Go to previous page',
+ });
+ expect(prevButton).toBeDisabled();
+ });
+ });
+});
diff --git a/packages/core/src/Table/plugins/pagination/useXDSTablePagination.tsx b/packages/core/src/Table/plugins/pagination/useXDSTablePagination.tsx
new file mode 100644
index 0000000000..312b758a41
--- /dev/null
+++ b/packages/core/src/Table/plugins/pagination/useXDSTablePagination.tsx
@@ -0,0 +1,377 @@
+'use client';
+
+/**
+ * @file useXDSTablePagination.tsx
+ * @input React, XDSPagination, Table plugin types
+ * @output Exports useXDSTablePagination hook and config/return types
+ * @position Pagination plugin; consumed by XDSTable via plugins prop
+ *
+ * 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 * as stylex from '@stylexjs/stylex';
+import {spacingVars} from '../../../theme/tokens.stylex';
+import {XDSPagination} from '../../../Pagination';
+import type {XDSPaginationProps} from '../../../Pagination';
+import type {TablePlugin} from '../../types';
+
+// =============================================================================
+// Styles
+// =============================================================================
+
+const styles = stylex.create({
+ wrapper: {
+ display: 'flex',
+ },
+ marginTop: {
+ marginTop: spacingVars['--spacing-2'],
+ },
+ marginBottom: {
+ marginBottom: spacingVars['--spacing-2'],
+ },
+ alignStart: {
+ justifyContent: 'flex-start',
+ },
+ alignCenter: {
+ justifyContent: 'center',
+ },
+ alignEnd: {
+ justifyContent: 'flex-end',
+ },
+});
+
+// =============================================================================
+// Config Type
+// =============================================================================
+
+/**
+ * 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.
+ *
+ * @example
+ * ```
+ * const [page, setPage] = useState(1);
+ * const [pageSize, setPageSize] = useState(20);
+ *
+ * const pagination = useXDSTablePagination({
+ * page,
+ * onPageChange: setPage,
+ * totalItems: data.length,
+ * pageSize,
+ * });
+ *
+ * <XDSTable
+ * data={pagination.paginatedData(data)}
+ * columns={columns}
+ * plugins={{ pagination: pagination.plugin }}
+ * />
+ * ```
+ *
+ * @example
+ * ```
+ * const pagination = 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 }}
+ * />
+ * ```
+ *
+ * @example
+ * ```
+ * const pagination = useXDSTablePagination({
+ * page,
+ * onPageChange: setPage,
+ * totalItems: data.length,
+ * pageSize,
+ * onPageSizeChange: setPageSize,
+ * pageSizeOptions: [10, 25, 50, 100],
+ * });
+ * ```
+ *
+ * @example
+ * ```
+ * const pagination = useXDSTablePagination({
+ * page,
+ * onPageChange: setPage,
+ * hasMore: cursor != null,
+ * pageSize: 20,
+ * });
+ * ```
+ */
+export interface UseXDSTablePaginationConfig {
+ // --- Core (required) ---
+
+ /** Current page number (1-based). */
+ page: number;
+
+ /** Called when the page changes. Consumer updates their own state. */
+ onPageChange: (page: number) => void;
+
+ // --- Data shape (provide one) ---
+
+ /**
+ * Total number of items across all pages.
+ * Used to calculate total page count and "X–Y of Z" display.
+ * Takes precedence over `totalPages` if both are provided.
+ */
+ totalItems?: number;
+
+ /**
+ * Total number of pages. Use when you know the page count but not item count.
+ */
+ totalPages?: number;
+
+ /**
+ * Whether more pages exist after the current one.
+ * Use for cursor-based pagination where the total is unknown.
+ * Mutually exclusive with totalItems/totalPages.
+ */
+ hasMore?: boolean;
+
+ // --- Page size ---
+
+ /**
+ * Number of items per page.
+ * @default 10
+ */
+ pageSize?: number;
+
+ /**
+ * Called when the user changes the page size via the page size selector.
+ * When provided alongside `pageSizeOptions`, a page size dropdown is shown.
+ */
+ onPageSizeChange?: (pageSize: number) => void;
+
+ /**
+ * Available page size options. Shows a page size selector when provided.
+ * @example
+ * ```
+ * [10, 25, 50, 100]
+ * ```
+ */
+ pageSizeOptions?: number[];
+
+ // --- Display ---
+
+ /**
+ * Visual variant for the pagination controls.
+ * Passed through to XDSPagination.
+ * @default 'pages'
+ */
+ variant?: 'pages' | 'count' | 'compact' | 'dots' | 'none';
+
+ /**
+ * Size of the pagination controls.
+ * @default 'md'
+ */
+ size?: 'sm' | 'md';
+
+ /**
+ * 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
+ *
+ * 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
+ *
+ * @default 'center'
+ */
+ align?: 'start' | 'center' | 'end';
+
+ // --- Accessibility ---
+
+ /**
+ * Accessible label for the pagination nav landmark.
+ * @default 'Table pagination'
+ */
+ label?: string;
+}
+
+// =============================================================================
+// Return Type
+// =============================================================================
+
+/**
+ * Return value of useXDSTablePagination.
+ */
+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;
+}
+
+// =============================================================================
+// Hook
+// =============================================================================
+
+export function useXDSTablePagination<T extends Record<string, unknown>>(
+ config: UseXDSTablePaginationConfig,
+): UseXDSTablePaginationReturn<T> {
+ const {
+ page,
+ onPageChange,
+ totalItems,
+ totalPages: totalPagesProp,
+ hasMore,
+ pageSize = 10,
+ onPageSizeChange,
+ pageSizeOptions,
+ variant = 'pages',
+ size = 'md',
+ position = 'below',
+ align = 'center',
+ label = 'Table pagination',
+ } = config;
+
+ const computedTotalPages =
+ totalPagesProp ??
+ (totalItems != null ? Math.ceil(totalItems / pageSize) : undefined);
+
+ // Build XDSPagination props from config
+ const paginationProps: XDSPaginationProps = {
+ page,
+ onChange: onPageChange,
+ totalItems,
+ totalPages: computedTotalPages,
+ hasMore,
+ pageSize,
+ onPageSizeChange,
+ pageSizeOptions,
+ variant,
+ size,
+ 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(
+ (): TablePlugin<T> => ({
+ transformTableContext(children: ReactNode) {
+ const {
+ position: pos,
+ paginationProps: props,
+ align: a,
+ } = configRef.current;
+ 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
+ ? Math.ceil(props.totalItems / props.pageSize)
+ : undefined);
+ const isSinglePage = resolvedTotalPages === 1 && props.hasMore !== true;
+ if (isSinglePage) return children;
+
+ const makeWrapper = (side: 'above' | 'below') => (
+ <div
+ {...stylex.props(
+ styles.wrapper,
+ side === 'below' && styles.marginTop,
+ side === 'above' && styles.marginBottom,
+ a === 'center' && styles.alignCenter,
+ a === 'end' && styles.alignEnd,
+ a === 'start' && styles.alignStart,
+ )}>
+ <XDSPagination {...props} />
+ </div>
+ );
+
+ return (
+ <>
+ {(pos === 'above' || pos === 'both') && makeWrapper('above')}
+ {children}
+ {(pos === 'below' || pos === 'both') && makeWrapper('below')}
+ </>
+ );
+ },
+ }),
+ [],
+ );
+
+ return {
+ plugin,
+ paginationProps,
+ paginatedData,
+ page,
+ totalPages: computedTotalPages,
+ pageSize,
+ };
+}