An open source design system that's fully customizable and agent ready
TypeScript
feat(core): add XDSPagination — standalone pagination controls (#440)
Cindy Zhang0c7f16fe23a4
diff --git a/apps/storybook/stories/Pagination.stories.tsx b/apps/storybook/stories/Pagination.stories.tsxnew file mode 100644index 0000000000..c8bb078b61--- /dev/null+++ b/apps/storybook/stories/Pagination.stories.tsx@@ -0,0 +1,168 @@+import type {Meta, StoryObj} from '@storybook/react';+import {useState} from 'react';+import {XDSPagination} from '@xds/core/Pagination';++const meta: Meta<typeof XDSPagination> = {+ title: 'Core/XDSPagination',+ component: XDSPagination,+ tags: ['autodocs'],+ argTypes: {+ page: {+ control: 'number',+ description: 'Current page (1-based)',+ },+ variant: {+ control: 'select',+ options: ['pages', 'count', 'compact', 'dots', 'none'],+ description: 'Visual variant',+ },+ size: {+ control: 'select',+ options: ['sm', 'md'],+ description: 'Size variant',+ },+ siblingCount: {+ control: 'number',+ description: 'Pages shown around current page',+ },+ isDisabled: {+ control: 'boolean',+ description: 'Disabled state',+ },+ },+};++export default meta;+type Story = StoryObj<typeof XDSPagination>;++// Interactive wrapper for controlled state+function PaginationDemo(props: React.ComponentProps<typeof XDSPagination>) {+ const [page, setPage] = useState(props.page ?? 1);+ const [pageSize, setPageSize] = useState(props.pageSize ?? 10);+ return (+ <XDSPagination+ {...props}+ page={page}+ onChange={setPage}+ pageSize={pageSize}+ onPageSizeChange={props.pageSizeOptions ? setPageSize : undefined}+ />+ );+}++export const Default: Story = {+ render: () => <PaginationDemo page={1} totalItems={100} pageSize={10} />,+};++export const PagesVariant: Story = {+ name: 'Variant: Pages',+ render: () => (+ <PaginationDemo page={1} totalItems={200} pageSize={10} variant="pages" />+ ),+};++export const CountVariant: Story = {+ name: 'Variant: Count',+ render: () => (+ <PaginationDemo page={1} totalItems={200} pageSize={20} variant="count" />+ ),+};++export const CompactVariant: Story = {+ name: 'Variant: Compact',+ render: () => <PaginationDemo page={1} totalPages={10} variant="compact" />,+};++export const DotsVariant: Story = {+ name: 'Variant: Dots',+ render: () => <PaginationDemo page={1} totalPages={8} variant="dots" />,+};++export const NoneVariant: Story = {+ name: 'Variant: None',+ render: () => <PaginationDemo page={1} totalPages={5} variant="none" />,+};++export const WithPageSizeSelector: Story = {+ name: 'With Page Size Selector',+ render: () => (+ <PaginationDemo+ page={1}+ totalItems={200}+ pageSize={10}+ pageSizeOptions={[10, 20, 50]}+ variant="count"+ />+ ),+};++export const CursorBased: Story = {+ name: 'Cursor-Based (hasMore)',+ render: () => <PaginationDemo page={1} hasMore={true} />,+};++export const SmallSize: Story = {+ name: 'Small Size',+ render: () => (+ <PaginationDemo page={1} totalItems={100} pageSize={10} size="sm" />+ ),+};++export const ManyPages: Story = {+ name: 'Many Pages (Ellipsis)',+ render: () => <PaginationDemo page={5} totalItems={500} pageSize={10} />,+};++export const ManyPagesLargeSiblings: Story = {+ name: 'Many Pages (siblingCount=2)',+ render: () => (+ <PaginationDemo page={10} totalItems={500} pageSize={10} siblingCount={2} />+ ),+};++export const SinglePage: Story = {+ name: 'Single Page',+ render: () => <PaginationDemo page={1} totalPages={1} />,+};++export const Disabled: Story = {+ render: () => <PaginationDemo page={3} totalPages={10} isDisabled />,+};++export const AllVariants: Story = {+ name: 'All Variants',+ render: () => (+ <div style={{display: 'flex', flexDirection: 'column', gap: 24}}>+ <div>+ <p style={{marginBottom: 8, fontWeight: 500}}>pages (default)</p>+ <PaginationDemo+ page={3}+ totalItems={100}+ pageSize={10}+ variant="pages"+ />+ </div>+ <div>+ <p style={{marginBottom: 8, fontWeight: 500}}>count</p>+ <PaginationDemo+ page={3}+ totalItems={100}+ pageSize={10}+ variant="count"+ />+ </div>+ <div>+ <p style={{marginBottom: 8, fontWeight: 500}}>compact</p>+ <PaginationDemo page={3} totalPages={10} variant="compact" />+ </div>+ <div>+ <p style={{marginBottom: 8, fontWeight: 500}}>dots</p>+ <PaginationDemo page={3} totalPages={8} variant="dots" />+ </div>+ <div>+ <p style={{marginBottom: 8, fontWeight: 500}}>none</p>+ <PaginationDemo page={3} totalPages={10} variant="none" />+ </div>+ </div>+ ),+};diff --git a/packages/core/src/Pagination/README.md b/packages/core/src/Pagination/README.mdnew file mode 100644index 0000000000..2bb3d93890--- /dev/null+++ b/packages/core/src/Pagination/README.md@@ -0,0 +1,110 @@+# Pagination++Standalone pagination controls for navigating through pages of content.++## Files++| File | Purpose |+| ------------------------ | ----------------------------- |+| `XDSPagination.tsx` | Main component implementation |+| `XDSPagination.test.tsx` | Unit tests |+| `index.ts` | Public exports |+| `README.md` | This file |++## Exports++- `XDSPagination` — Main pagination component+- `generatePageRange` — Utility to compute visible page numbers with ellipsis+- `XDSPaginationProps` — Props type+- `XDSPaginationVariant` — Variant type (`'pages' | 'count' | 'compact' | 'dots' | 'none'`)+- `XDSPaginationSize` — Size type (`'sm' | 'md'`)++## Usage++```tsx+import {XDSPagination} from '@xds/core/Pagination';++// Page number buttons (default)+<XDSPagination+ page={page}+ onChange={setPage}+ totalItems={200}+ pageSize={20}+/>++// Count display with page size selector+<XDSPagination+ page={page}+ onChange={setPage}+ totalItems={200}+ variant="count"+ pageSizeOptions={[10, 20, 50]}+ onPageSizeChange={setPageSize}+/>++// Cursor-based (no total known)+<XDSPagination+ page={page}+ onChange={setPage}+ hasMore={data.hasNextPage}+/>++// Carousel dots+<XDSPagination+ page={slideIndex}+ onChange={setSlideIndex}+ totalPages={slides.length}+ variant="dots"+/>+```++## Props++| Prop | Type | Default | Description |+| ------------------ | ----------------------------------------- | -------------- | -------------------------------------------- |+| `page` | `number` | — | Current page number (1-based, required) |+| `onChange` | `(page: number) => void` | — | Called when page changes (required) |+| `onChangeAction` | `(page: number) => void \| Promise<void>` | — | Async action on page change |+| `totalItems` | `number` | — | Total item count (calculates pages) |+| `totalPages` | `number` | — | Total page count (alternative to totalItems) |+| `hasMore` | `boolean` | — | Whether more pages exist (cursor-based) |+| `pageSize` | `number` | `10` | Items per page |+| `pageSizeOptions` | `number[]` | — | Shows page size selector when provided |+| `onPageSizeChange` | `(pageSize: number) => void` | — | Called when page size changes |+| `variant` | `XDSPaginationVariant` | `'pages'` | Visual variant |+| `siblingCount` | `number` | `1` | Pages shown around current (pages variant) |+| `size` | `XDSPaginationSize` | `'md'` | Size of controls |+| `isDisabled` | `boolean` | `false` | Whether the component is disabled |+| `label` | `string` | `'Pagination'` | Accessible label for nav landmark |+| `data-testid` | `string` | — | Test ID |+| `xstyle` | `StyleXStyles` | — | StyleX overrides |++## Variants++- **pages** — Clickable page number buttons with ellipsis truncation+- **count** — "1–20 of 200" text display+- **compact** — "Page 1 of 10" text display+- **dots** — Dot indicators (best for ≤10 pages)+- **none** — Just prev/next buttons++## Accessibility++- Root is `<nav>` with `aria-label`+- Current page has `aria-current="page"`+- Prev/next buttons have descriptive `aria-label`+- Ellipsis elements are `aria-hidden`+- All interactive elements are keyboard accessible++## Theme Integration++```typescript+// Override via ComponentStyles+theme.components.pagination = {+ root: {+ /* root nav styles */+ },+ button: {+ /* page button styles */+ },+};+```diff --git a/packages/core/src/Pagination/XDSPagination.test.tsx b/packages/core/src/Pagination/XDSPagination.test.tsxnew file mode 100644index 0000000000..a3b7ad672b--- /dev/null+++ b/packages/core/src/Pagination/XDSPagination.test.tsx@@ -0,0 +1,525 @@+/**+ * @file XDSPagination.test.tsx+ * @input Uses vitest, @testing-library/react, XDSPagination component+ * @output Unit tests for XDSPagination component behavior+ * @position Testing; validates XDSPagination.tsx implementation+ *+ * SYNC: When XDSPagination.tsx changes, update tests to match new behavior+ */++import {describe, it, expect, vi} from 'vitest';+import {render, screen, within} from '@testing-library/react';+import userEvent from '@testing-library/user-event';+import {XDSPagination, generatePageRange} from './XDSPagination';++// =============================================================================+// generatePageRange helper+// =============================================================================++describe('generatePageRange', () => {+ it('returns all pages when total fits within slots', () => {+ expect(generatePageRange(1, 5, 1)).toEqual([1, 2, 3, 4, 5]);+ });++ it('returns all pages when total equals slot count', () => {+ // With siblingCount=1, totalSlots = 5 + 2*1 = 7+ expect(generatePageRange(4, 7, 1)).toEqual([1, 2, 3, 4, 5, 6, 7]);+ });++ it('shows right ellipsis when near start', () => {+ const result = generatePageRange(1, 10, 1);+ expect(result).toEqual([1, 2, 3, 4, 5, '...', 10]);+ });++ it('shows left ellipsis when near end', () => {+ const result = generatePageRange(10, 10, 1);+ expect(result).toEqual([1, '...', 6, 7, 8, 9, 10]);+ });++ it('shows both ellipses when in middle', () => {+ const result = generatePageRange(5, 10, 1);+ expect(result).toEqual([1, '...', 4, 5, 6, '...', 10]);+ });++ it('handles siblingCount=2', () => {+ const result = generatePageRange(6, 12, 2);+ expect(result).toEqual([1, '...', 4, 5, 6, 7, 8, '...', 12]);+ });++ it('handles siblingCount=0', () => {+ const result = generatePageRange(5, 10, 0);+ expect(result).toEqual([1, '...', 5, '...', 10]);+ });++ it('handles single page', () => {+ expect(generatePageRange(1, 1, 1)).toEqual([1]);+ });++ it('handles two pages', () => {+ expect(generatePageRange(1, 2, 1)).toEqual([1, 2]);+ });+});++// =============================================================================+// XDSPagination component+// =============================================================================++describe('XDSPagination', () => {+ // ---------------------------------------------------------------------------+ // Basic rendering+ // ---------------------------------------------------------------------------++ describe('basic rendering', () => {+ it('renders nav landmark with default label', () => {+ render(<XDSPagination page={1} onChange={() => {}} totalPages={5} />);+ expect(+ screen.getByRole('navigation', {name: 'Pagination'}),+ ).toBeInTheDocument();+ });++ it('renders nav landmark with custom label', () => {+ render(+ <XDSPagination+ page={1}+ onChange={() => {}}+ totalPages={5}+ label="Results navigation"+ />,+ );+ expect(+ screen.getByRole('navigation', {name: 'Results navigation'}),+ ).toBeInTheDocument();+ });++ it('renders prev and next buttons', () => {+ render(<XDSPagination page={3} onChange={() => {}} totalPages={5} />);+ expect(+ screen.getByRole('button', {name: 'Go to previous page'}),+ ).toBeInTheDocument();+ expect(+ screen.getByRole('button', {name: 'Go to next page'}),+ ).toBeInTheDocument();+ });++ it('renders with data-testid', () => {+ render(+ <XDSPagination+ page={1}+ onChange={() => {}}+ totalPages={5}+ data-testid="my-pagination"+ />,+ );+ expect(screen.getByTestId('my-pagination')).toBeInTheDocument();+ });++ it('returns null when totalItems is 0', () => {+ const {container} = render(+ <XDSPagination page={1} onChange={() => {}} totalItems={0} />,+ );+ expect(container.firstChild).toBeNull();+ });++ it('returns null when totalPages is 0', () => {+ const {container} = render(+ <XDSPagination page={1} onChange={() => {}} totalPages={0} />,+ );+ expect(container.firstChild).toBeNull();+ });+ });++ // ---------------------------------------------------------------------------+ // Variant: pages (default)+ // ---------------------------------------------------------------------------++ describe('variant: pages', () => {+ it('renders page number buttons', () => {+ render(<XDSPagination page={1} onChange={() => {}} totalPages={5} />);+ for (let i = 1; i <= 5; i++) {+ expect(+ screen.getByRole('button', {name: `Go to page ${i}`}),+ ).toBeInTheDocument();+ }+ });++ it('marks current page with aria-current', () => {+ render(<XDSPagination page={3} onChange={() => {}} totalPages={5} />);+ const activeButton = screen.getByRole('button', {name: 'Go to page 3'});+ expect(activeButton).toHaveAttribute('aria-current', 'page');++ const otherButton = screen.getByRole('button', {name: 'Go to page 1'});+ expect(otherButton).not.toHaveAttribute('aria-current');+ });++ it('shows ellipsis for many pages', () => {+ render(<XDSPagination page={5} onChange={() => {}} totalPages={10} />);+ // Should show: 1 ... 4 5 6 ... 10+ expect(+ screen.getByRole('button', {name: 'Go to page 1'}),+ ).toBeInTheDocument();+ expect(+ screen.getByRole('button', {name: 'Go to page 4'}),+ ).toBeInTheDocument();+ expect(+ screen.getByRole('button', {name: 'Go to page 5'}),+ ).toBeInTheDocument();+ expect(+ screen.getByRole('button', {name: 'Go to page 6'}),+ ).toBeInTheDocument();+ expect(+ screen.getByRole('button', {name: 'Go to page 10'}),+ ).toBeInTheDocument();+ // Pages 2, 3, 7, 8, 9 should not be shown+ expect(+ screen.queryByRole('button', {name: 'Go to page 2'}),+ ).not.toBeInTheDocument();+ expect(+ screen.queryByRole('button', {name: 'Go to page 9'}),+ ).not.toBeInTheDocument();+ });++ it('does not render pages when totalPages is unknown', () => {+ render(<XDSPagination page={1} onChange={() => {}} hasMore />);+ // Should not show any page number buttons+ expect(+ screen.queryByRole('button', {name: /Go to page/}),+ ).not.toBeInTheDocument();+ });+ });++ // ---------------------------------------------------------------------------+ // Variant: count+ // ---------------------------------------------------------------------------++ describe('variant: count', () => {+ it('renders count text', () => {+ render(+ <XDSPagination+ page={1}+ onChange={() => {}}+ totalItems={100}+ pageSize={10}+ variant="count"+ />,+ );+ expect(screen.getByText(/1–10 of 100/)).toBeInTheDocument();+ });++ it('clamps range end to totalItems on last page', () => {+ render(+ <XDSPagination+ page={5}+ onChange={() => {}}+ totalItems={45}+ pageSize={10}+ variant="count"+ />,+ );+ expect(screen.getByText(/41–45 of 45/)).toBeInTheDocument();+ });+ });++ // ---------------------------------------------------------------------------+ // Variant: compact+ // ---------------------------------------------------------------------------++ describe('variant: compact', () => {+ it('renders compact text', () => {+ render(+ <XDSPagination+ page={3}+ onChange={() => {}}+ totalPages={10}+ variant="compact"+ />,+ );+ expect(screen.getByText('Page 3 of 10')).toBeInTheDocument();+ });+ });++ // ---------------------------------------------------------------------------+ // Variant: dots+ // ---------------------------------------------------------------------------++ describe('variant: dots', () => {+ it('renders dot indicators', () => {+ render(+ <XDSPagination+ page={2}+ onChange={() => {}}+ totalPages={5}+ variant="dots"+ />,+ );+ const group = screen.getByRole('group', {name: 'Page indicators'});+ const dots = within(group).getAllByRole('button');+ expect(dots).toHaveLength(5);+ });++ it('marks active dot with aria-current', () => {+ render(+ <XDSPagination+ page={3}+ onChange={() => {}}+ totalPages={5}+ variant="dots"+ />,+ );+ const activeDot = screen.getByRole('button', {name: 'Go to page 3'});+ expect(activeDot).toHaveAttribute('aria-current', 'page');+ });+ });++ // ---------------------------------------------------------------------------+ // Variant: none+ // ---------------------------------------------------------------------------++ describe('variant: none', () => {+ it('renders only prev/next buttons', () => {+ render(+ <XDSPagination+ page={2}+ onChange={() => {}}+ totalPages={5}+ variant="none"+ />,+ );+ expect(+ screen.getByRole('button', {name: 'Go to previous page'}),+ ).toBeInTheDocument();+ expect(+ screen.getByRole('button', {name: 'Go to next page'}),+ ).toBeInTheDocument();+ // No page buttons or text indicators+ expect(+ screen.queryByRole('button', {name: /Go to page/}),+ ).not.toBeInTheDocument();+ });+ });++ // ---------------------------------------------------------------------------+ // Page change callbacks+ // ---------------------------------------------------------------------------++ describe('page change callbacks', () => {+ it('calls onChange when clicking a page button', async () => {+ const user = userEvent.setup();+ const onChange = vi.fn();+ render(<XDSPagination page={1} onChange={onChange} totalPages={5} />);+ await user.click(screen.getByRole('button', {name: 'Go to page 3'}));+ expect(onChange).toHaveBeenCalledWith(3);+ });++ it('calls onChange when clicking next', async () => {+ const user = userEvent.setup();+ const onChange = vi.fn();+ render(<XDSPagination page={2} onChange={onChange} totalPages={5} />);+ await user.click(screen.getByRole('button', {name: 'Go to next page'}));+ expect(onChange).toHaveBeenCalledWith(3);+ });++ it('calls onChange when clicking previous', async () => {+ const user = userEvent.setup();+ const onChange = vi.fn();+ render(<XDSPagination page={3} onChange={onChange} totalPages={5} />);+ await user.click(+ screen.getByRole('button', {name: 'Go to previous page'}),+ );+ expect(onChange).toHaveBeenCalledWith(2);+ });++ it('calls onChange when clicking a dot', async () => {+ const user = userEvent.setup();+ const onChange = vi.fn();+ render(+ <XDSPagination+ page={1}+ onChange={onChange}+ totalPages={5}+ variant="dots"+ />,+ );+ await user.click(screen.getByRole('button', {name: 'Go to page 4'}));+ expect(onChange).toHaveBeenCalledWith(4);+ });+ });++ // ---------------------------------------------------------------------------+ // Boundary states+ // ---------------------------------------------------------------------------++ describe('boundary states', () => {+ it('disables previous button on first page', () => {+ render(<XDSPagination page={1} onChange={() => {}} totalPages={5} />);+ expect(+ screen.getByRole('button', {name: 'Go to previous page'}),+ ).toBeDisabled();+ });++ it('disables next button on last page', () => {+ render(<XDSPagination page={5} onChange={() => {}} totalPages={5} />);+ expect(+ screen.getByRole('button', {name: 'Go to next page'}),+ ).toBeDisabled();+ });++ it('enables both buttons on middle page', () => {+ render(<XDSPagination page={3} onChange={() => {}} totalPages={5} />);+ expect(+ screen.getByRole('button', {name: 'Go to previous page'}),+ ).not.toBeDisabled();+ expect(+ screen.getByRole('button', {name: 'Go to next page'}),+ ).not.toBeDisabled();+ });++ it('disables both buttons when only one page', () => {+ render(<XDSPagination page={1} onChange={() => {}} totalPages={1} />);+ expect(+ screen.getByRole('button', {name: 'Go to previous page'}),+ ).toBeDisabled();+ expect(+ screen.getByRole('button', {name: 'Go to next page'}),+ ).toBeDisabled();+ });+ });++ // ---------------------------------------------------------------------------+ // Cursor-based mode (hasMore)+ // ---------------------------------------------------------------------------++ describe('cursor-based mode', () => {+ it('enables next when hasMore is true', () => {+ render(<XDSPagination page={1} onChange={() => {}} hasMore />);+ expect(+ screen.getByRole('button', {name: 'Go to next page'}),+ ).not.toBeDisabled();+ });++ it('disables next when hasMore is false', () => {+ render(<XDSPagination page={3} onChange={() => {}} hasMore={false} />);+ expect(+ screen.getByRole('button', {name: 'Go to next page'}),+ ).toBeDisabled();+ });++ it('disables previous on first page with hasMore', () => {+ render(<XDSPagination page={1} onChange={() => {}} hasMore />);+ expect(+ screen.getByRole('button', {name: 'Go to previous page'}),+ ).toBeDisabled();+ });++ it('enables previous on page > 1 with hasMore', () => {+ render(<XDSPagination page={2} onChange={() => {}} hasMore />);+ expect(+ screen.getByRole('button', {name: 'Go to previous page'}),+ ).not.toBeDisabled();+ });+ });++ // ---------------------------------------------------------------------------+ // Page size selector+ // ---------------------------------------------------------------------------++ describe('page size selector', () => {+ it('renders page size selector when pageSizeOptions provided', () => {+ render(+ <XDSPagination+ page={1}+ onChange={() => {}}+ totalItems={100}+ pageSize={10}+ pageSizeOptions={[10, 20, 50]}+ onPageSizeChange={() => {}}+ />,+ );+ // The selector should be present (hidden label "Items per page")+ const nav = screen.getByRole('navigation');+ expect(nav).toBeInTheDocument();+ });++ it('does not render page size selector when pageSizeOptions not provided', () => {+ render(<XDSPagination page={1} onChange={() => {}} totalPages={5} />);+ // No selector trigger should be present+ const nav = screen.getByRole('navigation');+ // Only prev/next + page buttons should exist+ const buttons = within(nav).getAllByRole('button');+ // 2 nav buttons + page buttons+ expect(buttons.length).toBeGreaterThanOrEqual(2);+ });+ });++ // ---------------------------------------------------------------------------+ // Disabled state+ // ---------------------------------------------------------------------------++ describe('disabled state', () => {+ it('disables all page buttons when isDisabled', () => {+ render(+ <XDSPagination+ page={3}+ onChange={() => {}}+ totalPages={5}+ isDisabled+ />,+ );+ expect(+ screen.getByRole('button', {name: 'Go to previous page'}),+ ).toBeDisabled();+ expect(+ screen.getByRole('button', {name: 'Go to next page'}),+ ).toBeDisabled();+ // Page buttons should also be disabled+ expect(screen.getByRole('button', {name: 'Go to page 1'})).toBeDisabled();+ });++ it('does not call onChange when disabled', async () => {+ const user = userEvent.setup();+ const onChange = vi.fn();+ render(+ <XDSPagination+ page={3}+ onChange={onChange}+ totalPages={5}+ isDisabled+ />,+ );+ // Disabled buttons can't be clicked+ await user.click(screen.getByRole('button', {name: 'Go to page 1'}));+ expect(onChange).not.toHaveBeenCalled();+ });+ });++ // ---------------------------------------------------------------------------+ // totalItems calculation+ // ---------------------------------------------------------------------------++ describe('totalItems calculation', () => {+ it('calculates totalPages from totalItems and pageSize', () => {+ render(+ <XDSPagination+ page={1}+ onChange={() => {}}+ totalItems={95}+ pageSize={10}+ />,+ );+ // 95 / 10 = 10 pages, should show page 10+ expect(+ screen.getByRole('button', {name: 'Go to page 10'}),+ ).toBeInTheDocument();+ });++ it('uses default pageSize of 10', () => {+ render(<XDSPagination page={1} onChange={() => {}} totalItems={45} />);+ // 45 / 10 = 5 pages+ expect(+ screen.getByRole('button', {name: 'Go to page 5'}),+ ).toBeInTheDocument();+ expect(+ screen.queryByRole('button', {name: 'Go to page 6'}),+ ).not.toBeInTheDocument();+ });+ });+});diff --git a/packages/core/src/Pagination/XDSPagination.tsx b/packages/core/src/Pagination/XDSPagination.tsxnew file mode 100644index 0000000000..3a9e108834--- /dev/null+++ b/packages/core/src/Pagination/XDSPagination.tsx@@ -0,0 +1,642 @@+/**+ * @file XDSPagination.tsx+ * @input Uses React, StyleX, XDSButton, XDSIcon, XDSSelector, XDSText+ * @output Exports XDSPagination component, XDSPaginationProps, XDSPaginationVariant, XDSPaginationSize types+ * @position Core implementation; consumed by index.ts, tested by XDSPagination.test.tsx+ *+ * SYNC: When modified, update these files to stay in sync:+ * - /packages/core/src/Pagination/README.md (props table, features, implementation notes)+ * - /packages/core/src/Pagination/XDSPagination.test.tsx (tests for new/changed behavior)+ * - /packages/core/src/Pagination/index.ts (exports if types change)+ * - /apps/storybook/stories/Pagination.stories.tsx (storybook stories)+ *+ * Last synced props: page, onChange, onChangeAction, totalItems, totalPages, hasMore,+ * pageSize, pageSizeOptions, onPageSizeChange, variant, siblingCount, size, isDisabled,+ * label, data-testid, xstyle+ */++'use client';++import {forwardRef, useContext, useTransition} from 'react';+import * as stylex from '@stylexjs/stylex';+import type {StyleXStyles} from '@stylexjs/stylex';+import {+ colorVars,+ sizeVars,+ spacingVars,+ radiusVars,+ transitionVars,+ textSizeVars,+ fontWeightVars,+ lineHeightVars,+} from '../theme/tokens.stylex';+import {ThemeContext} from '../theme/ThemeContext';+import type {StyleXStyles as ThemeStyleXStyles} from '../theme/types';+import {XDSButton} from '../Button';+import {XDSIcon} from '../Icon';+import {XDSSelector} from '../Selector';+import {XDSText} from '../Text';++// =============================================================================+// Module Augmentation - Register component styles with ComponentStyles+// =============================================================================++declare module '../theme/types' {+ interface ComponentStyles {+ pagination?: {+ /** Root nav container styles */+ root?: ThemeStyleXStyles;+ /** Page number button styles */+ button?: ThemeStyleXStyles;+ };+ }+}++// =============================================================================+// Types+// =============================================================================++/** Visual variant controlling what appears between prev/next buttons. */+export type XDSPaginationVariant =+ | 'pages'+ | 'count'+ | 'compact'+ | 'dots'+ | 'none';++/** Size of the pagination controls. */+export type XDSPaginationSize = 'sm' | 'md';++export interface XDSPaginationProps {+ // --- Core (required) ---+ /** Current page number (1-based). Page 1 is the first page. */+ page: number;+ /** Called when the page changes. */+ onChange: (page: number) => void;+ /**+ * Async action on page change. Fires after onChange.+ * Uses React transitions for built-in loading state.+ */+ onChangeAction?: (page: number) => void | Promise<void>;++ // --- Data shape (provide one) ---+ /**+ * Total number of items. Used to calculate page count.+ * Takes precedence over totalPages if both provided.+ */+ totalItems?: number;+ /**+ * Total number of pages. Use when you know page count but not item count.+ */+ totalPages?: number;+ /**+ * Whether more pages exist after the current one.+ * Use for cursor-based pagination where total is unknown.+ */+ hasMore?: boolean;++ // --- Page size ---+ /** Number of items per page. @default 10 */+ pageSize?: number;+ /** Available page size options. Shows a page size selector when provided. */+ pageSizeOptions?: number[];+ /** Called when the page size changes. */+ onPageSizeChange?: (pageSize: number) => void;++ // --- Display ---+ /**+ * Visual variant controlling what appears between prev/next buttons.+ * - pages: Page number buttons with ellipsis (default)+ * - count: "X–Y of Z" text+ * - compact: "Page X of Y" text+ * - dots: Dot indicators+ * - none: Just prev/next buttons+ * @default 'pages'+ */+ variant?: XDSPaginationVariant;+ /**+ * Number of page buttons to show on each side of the current page.+ * Only applies when variant='pages'. @default 1+ */+ siblingCount?: number;+ /**+ * Size of the pagination controls.+ * @default 'md'+ */+ size?: XDSPaginationSize;++ // --- Behavior ---+ /** Whether the component is disabled. @default false */+ isDisabled?: boolean;++ // --- Accessibility ---+ /**+ * Accessible label for the navigation landmark.+ * @default 'Pagination'+ */+ label?: string;++ // --- Standard XDS ---+ /** Test ID for automated testing. */+ 'data-testid'?: string;+ /** StyleX overrides for the root element. */+ xstyle?: StyleXStyles;+}++// =============================================================================+// Styles+// =============================================================================++const styles = stylex.create({+ root: {+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'space-between',+ gap: spacingVars['--spacing-4'],+ },+ controls: {+ display: 'flex',+ alignItems: 'center',+ gap: spacingVars['--spacing-1'],+ },+ pageButton: {+ display: 'inline-flex',+ alignItems: 'center',+ justifyContent: 'center',+ minWidth: sizeVars['--size-md'],+ height: sizeVars['--size-md'],+ paddingInline: spacingVars['--spacing-2'],+ borderWidth: 0,+ borderStyle: 'none',+ borderRadius: radiusVars['--radius-element'],+ backgroundColor: 'transparent',+ color: colorVars['--color-text-primary'],+ fontFamily: 'inherit',+ fontSize: textSizeVars['--text-base'],+ lineHeight: lineHeightVars['--leading-base'],+ fontWeight: fontWeightVars['--font-weight-medium'],+ cursor: 'pointer',+ transitionProperty: 'background-color, color',+ transitionDuration: transitionVars['--transition-fast'],+ backgroundImage: {+ default: null,+ ':hover': {+ '@media (hover: hover)': `linear-gradient(${colorVars['--color-hover-overlay']}, ${colorVars['--color-hover-overlay']})`,+ },+ ':active': `linear-gradient(${colorVars['--color-pressed-overlay']}, ${colorVars['--color-pressed-overlay']})`,+ },+ outline: {+ default: 'none',+ ':focus-visible': `2px solid ${colorVars['--color-focus-outline']}`,+ },+ outlineOffset: {+ default: '0',+ ':focus-visible': '3px',+ },+ },+ pageButtonSm: {+ minWidth: sizeVars['--size-sm'],+ height: sizeVars['--size-sm'],+ fontSize: textSizeVars['--text-sm'],+ },+ pageButtonActive: {+ backgroundColor: colorVars['--color-accent'],+ color: colorVars['--color-text-on-media'],+ backgroundImage: {+ default: null,+ ':hover': {+ '@media (hover: hover)': `linear-gradient(${colorVars['--color-hover-overlay']}, ${colorVars['--color-hover-overlay']})`,+ },+ ':active': `linear-gradient(${colorVars['--color-pressed-overlay']}, ${colorVars['--color-pressed-overlay']})`,+ },+ },+ pageButtonDisabled: {+ cursor: 'not-allowed',+ opacity: 0.5,+ },+ ellipsis: {+ display: 'inline-flex',+ alignItems: 'center',+ justifyContent: 'center',+ minWidth: sizeVars['--size-md'],+ height: sizeVars['--size-md'],+ color: colorVars['--color-text-secondary'],+ fontSize: textSizeVars['--text-base'],+ userSelect: 'none',+ },+ ellipsisSm: {+ minWidth: sizeVars['--size-sm'],+ height: sizeVars['--size-sm'],+ fontSize: textSizeVars['--text-sm'],+ },+ infoText: {+ display: 'flex',+ alignItems: 'center',+ whiteSpace: 'nowrap',+ },+ dotsContainer: {+ display: 'flex',+ alignItems: 'center',+ gap: spacingVars['--spacing-1'],+ },+ dot: {+ width: 8,+ height: 8,+ borderWidth: 0,+ borderStyle: 'none',+ padding: 0,+ borderRadius: '50%',+ backgroundColor: colorVars['--color-deemphasized'],+ cursor: 'pointer',+ transitionProperty: 'background-color',+ transitionDuration: transitionVars['--transition-fast'],+ outline: {+ default: 'none',+ ':focus-visible': `2px solid ${colorVars['--color-focus-outline']}`,+ },+ outlineOffset: {+ default: '0',+ ':focus-visible': '2px',+ },+ },+ dotSm: {+ width: 6,+ height: 6,+ },+ dotActive: {+ backgroundColor: colorVars['--color-accent'],+ },+ dotDisabled: {+ cursor: 'not-allowed',+ opacity: 0.5,+ },+ pageSizeSelector: {+ display: 'flex',+ alignItems: 'center',+ gap: spacingVars['--spacing-2'],+ },+ pageSizeSelectorControl: {+ width: 80,+ },+ disabled: {+ opacity: 0.5,+ pointerEvents: 'none' as const,+ },+});++// =============================================================================+// Helpers+// =============================================================================++/**+ * Generates the range of page numbers to display, including ellipsis markers.+ * Returns an array of page numbers and '...' strings.+ *+ * @example+ * generatePageRange(5, 10, 1) → [1, '...', 4, 5, 6, '...', 10]+ * generatePageRange(1, 10, 1) → [1, 2, 3, '...', 10]+ * generatePageRange(1, 5, 1) → [1, 2, 3, 4, 5]+ */+export function generatePageRange(+ currentPage: number,+ totalPages: number,+ siblingCount: number,+): Array<number | '...'> {+ // Total page number slots (excluding ellipses):+ // first + last + current + 2*siblings = 3 + 2*siblings+ // With 2 potential ellipsis slots: 5 + 2*siblings+ const totalSlots = 5 + 2 * siblingCount;++ // If total pages fit within slots, show all pages+ if (totalPages <= totalSlots) {+ return Array.from({length: totalPages}, (_, i) => i + 1);+ }++ const leftSiblingIndex = Math.max(currentPage - siblingCount, 1);+ const rightSiblingIndex = Math.min(currentPage + siblingCount, totalPages);++ const showLeftEllipsis = leftSiblingIndex > 2;+ const showRightEllipsis = rightSiblingIndex < totalPages - 1;++ if (!showLeftEllipsis && showRightEllipsis) {+ // Near the start: show more pages on the left+ const leftRange = 3 + 2 * siblingCount;+ const pages: Array<number | '...'> = Array.from(+ {length: leftRange},+ (_, i) => i + 1,+ );+ pages.push('...', totalPages);+ return pages;+ }++ if (showLeftEllipsis && !showRightEllipsis) {+ // Near the end: show more pages on the right+ const rightRange = 3 + 2 * siblingCount;+ const pages: Array<number | '...'> = [1, '...'];+ for (let i = totalPages - rightRange + 1; i <= totalPages; i++) {+ pages.push(i);+ }+ return pages;+ }++ // In the middle: show ellipsis on both sides+ const pages: Array<number | '...'> = [1, '...'];+ for (let i = leftSiblingIndex; i <= rightSiblingIndex; i++) {+ pages.push(i);+ }+ pages.push('...', totalPages);+ return pages;+}++// =============================================================================+// Component+// =============================================================================++/**+ * Standalone pagination controls for navigating through pages of content.+ *+ * Supports multiple display variants: page numbers, count text, compact text,+ * dot indicators, or minimal prev/next navigation. Works with known totals+ * or cursor-based pagination.+ *+ * @example+ * ```tsx+ * // Page number buttons (default)+ * <XDSPagination+ * page={page}+ * onChange={setPage}+ * totalItems={200}+ * pageSize={20}+ * />+ *+ * // Count display below a table+ * <XDSPagination+ * page={page}+ * onChange={setPage}+ * totalItems={200}+ * pageSize={20}+ * variant="count"+ * pageSizeOptions={[10, 20, 50]}+ * onPageSizeChange={setPageSize}+ * size="sm"+ * />+ *+ * // Cursor-based (no total known)+ * <XDSPagination+ * page={page}+ * onChange={setPage}+ * hasMore={data.hasNextPage}+ * />+ *+ * // Carousel dots+ * <XDSPagination+ * page={slideIndex}+ * onChange={setSlideIndex}+ * totalPages={slides.length}+ * variant="dots"+ * />+ * ```+ */+export const XDSPagination = forwardRef<HTMLElement, XDSPaginationProps>(+ function XDSPagination(+ {+ page,+ onChange,+ onChangeAction,+ totalItems,+ totalPages: totalPagesProp,+ hasMore,+ pageSize = 10,+ pageSizeOptions,+ onPageSizeChange,+ variant = 'pages',+ siblingCount = 1,+ size = 'md',+ isDisabled = false,+ label = 'Pagination',+ 'data-testid': testId,+ xstyle,+ },+ ref,+ ) {+ const [isPending, startTransition] = useTransition();+ const themeContext = useContext(ThemeContext);+ const rootOverride = themeContext?.theme.components?.pagination?.root;+ const buttonOverride = themeContext?.theme.components?.pagination?.button;++ // Compute pagination state+ const computedTotalPages =+ totalPagesProp ??+ (totalItems != null ? Math.ceil(totalItems / pageSize) : undefined);++ const hasPrevious = page > 1;+ const hasNext =+ computedTotalPages != null+ ? page < computedTotalPages+ : (hasMore ?? false);++ // Return null for empty state+ if (totalItems != null && totalItems <= 0) {+ return null;+ }+ if (computedTotalPages != null && computedTotalPages <= 0) {+ return null;+ }++ const handlePageChange = (newPage: number) => {+ if (isDisabled || isPending) return;+ onChange(newPage);+ if (onChangeAction) {+ startTransition(async () => {+ await onChangeAction(newPage);+ });+ }+ };++ const handlePrevious = () => {+ if (hasPrevious) {+ handlePageChange(page - 1);+ }+ };++ const handleNext = () => {+ if (hasNext) {+ handlePageChange(page + 1);+ }+ };++ const handlePageSizeChange = (value: string) => {+ const newSize = Number(value);+ onPageSizeChange?.(newSize);+ // Reset to page 1 when page size changes+ onChange(1);+ if (onChangeAction) {+ startTransition(async () => {+ await onChangeAction(1);+ });+ }+ };++ // Item range for count display+ const rangeStart = (page - 1) * pageSize + 1;+ const rangeEnd =+ totalItems != null+ ? Math.min(page * pageSize, totalItems)+ : page * pageSize;++ const buttonSize = size === 'sm' ? 'sm' : 'md';+ const isSm = size === 'sm';++ const renderIndicator = () => {+ switch (variant) {+ case 'pages': {+ if (computedTotalPages == null) return null;+ const pageRange = generatePageRange(+ page,+ computedTotalPages,+ siblingCount,+ );+ return (+ <>+ {pageRange.map((item, index) => {+ if (item === '...') {+ return (+ <span+ key={`ellipsis-${index}`}+ aria-hidden="true"+ {...stylex.props(+ styles.ellipsis,+ isSm && styles.ellipsisSm,+ )}>+ …+ </span>+ );+ }+ const isActive = item === page;+ return (+ <button+ key={item}+ type="button"+ aria-label={`Go to page ${item}`}+ aria-current={isActive ? 'page' : undefined}+ onClick={() => handlePageChange(item)}+ disabled={isDisabled}+ {...stylex.props(+ styles.pageButton,+ isSm && styles.pageButtonSm,+ isActive && styles.pageButtonActive,+ isDisabled && styles.pageButtonDisabled,+ buttonOverride,+ )}>+ {item}+ </button>+ );+ })}+ </>+ );+ }++ case 'count': {+ if (totalItems == null) return null;+ return (+ <span {...stylex.props(styles.infoText)}>+ <XDSText type="body" size="sm" color="secondary">+ {`${rangeStart}\u2013${rangeEnd} of ${totalItems}`}+ </XDSText>+ </span>+ );+ }++ case 'compact': {+ if (computedTotalPages == null) return null;+ return (+ <span {...stylex.props(styles.infoText)}>+ <XDSText type="body" size="sm" color="secondary">+ {`Page ${page} of ${computedTotalPages}`}+ </XDSText>+ </span>+ );+ }++ case 'dots': {+ if (computedTotalPages == null) return null;+ return (+ <div+ {...stylex.props(styles.dotsContainer)}+ role="group"+ aria-label="Page indicators">+ {Array.from({length: computedTotalPages}, (_, i) => (+ <button+ key={i + 1}+ type="button"+ aria-label={`Go to page ${i + 1}`}+ aria-current={i + 1 === page ? 'page' : undefined}+ onClick={() => handlePageChange(i + 1)}+ disabled={isDisabled}+ {...stylex.props(+ styles.dot,+ isSm && styles.dotSm,+ i + 1 === page && styles.dotActive,+ isDisabled && styles.dotDisabled,+ )}+ />+ ))}+ </div>+ );+ }++ case 'none':+ default:+ return null;+ }+ };++ return (+ <nav+ ref={ref}+ aria-label={label}+ data-testid={testId}+ {...stylex.props(styles.root, rootOverride, xstyle)}>+ {pageSizeOptions != null && pageSizeOptions.length > 0 && (+ <div {...stylex.props(styles.pageSizeSelector)}>+ <div {...stylex.props(styles.pageSizeSelectorControl)}>+ <XDSSelector+ label="Items per page"+ isLabelHidden+ items={pageSizeOptions.map(opt => String(opt))}+ value={String(pageSize)}+ onChange={handlePageSizeChange}+ size={buttonSize}+ isDisabled={isDisabled}+ />+ </div>+ </div>+ )}++ <div {...stylex.props(styles.controls)}>+ <XDSButton+ label="Go to previous page"+ variant="ghost"+ size={buttonSize}+ icon={<XDSIcon icon="chevronLeft" size={isSm ? 'sm' : 'md'} />}+ onClick={handlePrevious}+ isDisabled={isDisabled || !hasPrevious}+ />++ {renderIndicator()}++ <XDSButton+ label="Go to next page"+ variant="ghost"+ size={buttonSize}+ icon={<XDSIcon icon="chevronRight" size={isSm ? 'sm' : 'md'} />}+ onClick={handleNext}+ isDisabled={isDisabled || !hasNext}+ />+ </div>+ </nav>+ );+ },+);++XDSPagination.displayName = 'XDSPagination';diff --git a/packages/core/src/Pagination/index.ts b/packages/core/src/Pagination/index.tsnew file mode 100644index 0000000000..19b3e7b25d--- /dev/null+++ b/packages/core/src/Pagination/index.ts@@ -0,0 +1,13 @@+/**+ * @file index.ts+ * @input XDSPagination component and types+ * @output Public API for Pagination module+ * @position Barrel export; consumed by packages/core/src/index.ts+ */++export {XDSPagination, generatePageRange} from './XDSPagination';+export type {+ XDSPaginationProps,+ XDSPaginationVariant,+ XDSPaginationSize,+} from './XDSPagination';diff --git a/packages/core/src/index.ts b/packages/core/src/index.tsindex c3b5592fa1..e52d5de187 100644--- a/packages/core/src/index.ts+++ b/packages/core/src/index.ts@@ -51,6 +51,7 @@ export * from './MoreMenu';export * from './TopNav';export * from './SideNav';export * from './MobileNav';+export * from './Pagination';export * from './ProgressBar';// Layout utilities and components (includes XDSHStack, XDSVStack)