# Pagination

## Introduction

The Pagination component enables users to navigate through large datasets or content collections that are divided into discrete pages. It provides controls for moving forward and backward, jumping to specific pages, and understanding the current position within the total set.

Pagination ships in two variants -- **standard** (clickable page numbers) and **compact** (dropdown selector) -- making it suitable for different screen sizes and layout constraints. It supports both controlled and uncontrolled usage patterns to integrate smoothly with any state management approach.

```tsx
<Stack spacing={4}>
    <Stack spacing={1}>
      <div>Standard</div>
      <Pagination {...args} variant="standard" />
    </Stack>
    <Stack spacing={1}>
      <div>Compact</div>
      <Pagination {...args} variant="compact" />
    </Stack>
  </Stack>
```

| Field                        | Description | Default |
| ---------------------------- | ----------- | ------- |
| Controls resolved at runtime | —           | —       |

## Usage

```tsx
import { Pagination } from '@ceed/cds';

function DataList() {
  const [page, setPage] = useState(1);
  const pageSize = 10;
  const totalItems = 250;

  return (
    <>
      <ItemList items={items} page={page} pageSize={pageSize} />
      <Pagination rowCount={totalItems} paginationModel={{ page, pageSize }} onPageChange={setPage} />
    </>
  );
}
```

## Features

### Sizes

Pagination is available in three sizes -- `sm`, `md`, and `lg` -- for both the standard and compact variants.

```tsx
<Stack spacing={4}>
    <Stack spacing={2}>
      <div>Standard</div>
      <Pagination {...args} variant="standard" size="sm" />
      <Pagination {...args} variant="standard" size="md" />
      <Pagination {...args} variant="standard" size="lg" />
    </Stack>
    <Stack spacing={2}>
      <div>Compact</div>
      <Pagination {...args} variant="compact" size="sm" />
      <Pagination {...args} variant="compact" size="md" />
      <Pagination {...args} variant="compact" size="lg" />
    </Stack>
  </Stack>
```

### Page Positions

The component correctly handles the visual presentation when the user is at the beginning, middle, or end of the page range, adjusting ellipsis buttons and disabled states accordingly.

```tsx
<Stack spacing={4}>
    <Stack spacing={2}>
      <div>Standard</div>
      <Pagination
        {...args}
        variant="standard"
        defaultPaginationModel={{
          page: 1,
          pageSize: 1
        }}
      />
      <Pagination
        {...args}
        variant="standard"
        defaultPaginationModel={{
          page: 10,
          pageSize: 1
        }}
      />
      <Pagination
        {...args}
        variant="standard"
        defaultPaginationModel={{
          page: 20,
          pageSize: 1
        }}
      />
    </Stack>
    <Stack spacing={2}>
      <div>Compact</div>
      <Pagination
        {...args}
        variant="compact"
        defaultPaginationModel={{
          page: 1,
          pageSize: 1
        }}
      />
      <Pagination
        {...args}
        variant="compact"
        defaultPaginationModel={{
          page: 10,
          pageSize: 1
        }}
      />
      <Pagination
        {...args}
        variant="compact"
        defaultPaginationModel={{
          page: 20,
          pageSize: 1
        }}
      />
    </Stack>
  </Stack>
```

### Uncontrolled Mode

In uncontrolled mode the component manages its own page state internally. Pass `defaultPaginationModel` to set the initial state and use `onPageChange` to react to changes.

```tsx
<Pagination {...args} />
```

### Controlled Mode

In controlled mode the parent component owns the page state via `paginationModel` and updates it through `onPageChange`. This gives full control over navigation behavior.

```tsx
<Pagination {...args} paginationModel={paginationModel} onPageChange={handlePageChange} />
```

### Dynamic Row Count

Pagination automatically adjusts when the total number of items changes. If the current page exceeds the new page count, the component clamps to the last available page.

```tsx
<Stack gap={2}>
    <Pagination {...args} rowCount={rowCount} />
    <Stack direction="row" gap={2}>
      <Button onClick={() => setRowCount(rowCount - 1)}>Decrease Row count</Button>
      <Button onClick={() => setRowCount(rowCount + 1)}>Increase Row count</Button>
    </Stack>
  </Stack>
```

## Common Use Cases

### Data Table Pagination

```tsx
function DataTable({ columns }) {
  const [page, setPage] = useState(1);
  const [pageSize] = useState(25);
  const { data, totalCount, isLoading } = useFetchData(page, pageSize);

  return (
    <Box>
      <Table columns={columns} data={data} loading={isLoading} />
      <Stack direction="row" justifyContent="space-between" alignItems="center" mt={2}>
        <Typography level="body-sm">
          Showing {(page - 1) * pageSize + 1}--{Math.min(page * pageSize, totalCount)} of {totalCount}
        </Typography>
        <Pagination rowCount={totalCount} paginationModel={{ page, pageSize }} onPageChange={setPage} />
      </Stack>
    </Box>
  );
}
```

### Search Results with Compact Variant

```tsx
function SearchResults({ query }) {
  const [page, setPage] = useState(1);
  const { results, totalCount } = useSearch(query, page);

  useEffect(() => {
    setPage(1);
  }, [query]);

  return (
    <Stack spacing={2}>
      <Typography level="body-sm">
        {totalCount} results for "{query}"
      </Typography>
      <ResultList results={results} />
      <Pagination
        rowCount={totalCount}
        paginationModel={{ page, pageSize: 10 }}
        onPageChange={setPage}
        variant="compact"
      />
    </Stack>
  );
}
```

### URL-Synchronized Pagination

```tsx
function URLPaginatedList() {
  const [searchParams, setSearchParams] = useSearchParams();
  const page = parseInt(searchParams.get('page') || '1', 10);

  const handlePageChange = (newPage: number) => {
    setSearchParams({ page: String(newPage) });
  };

  return <Pagination rowCount={totalCount} paginationModel={{ page, pageSize: 25 }} onPageChange={handlePageChange} />;
}
```

## Props and Customization

### Key Props

| Prop                     | Type                                 | Default                     | Description                |
| ------------------------ | ------------------------------------ | --------------------------- | -------------------------- |
| `paginationModel`        | `{ page: number; pageSize: number }` | (required)                  | Current page and page size |
| `defaultPaginationModel` | `{ page: number; pageSize: number }` | `{ page: 1, pageSize: 25 }` | Initial pagination state   |
| `rowCount`               | `number`                             | (required)                  | Total number of rows       |
| `onPageChange`           | `(newPage: number) => void`          | (required)                  | Callback when page changes |
| `size`                   | `'sm' \| 'md' \| 'lg'`               | `'md'`                      | Pagination control size    |
| `variant`                | `'standard' \| 'compact'`            | `'standard'`                | Pagination display mode    |

## Best Practices

- **Always show context.** Display the total item count and current range (for example "Showing 1--25 of 250") alongside the pagination controls so users understand the scope of the data.

```tsx
// Good
<Stack direction="row" justifyContent="space-between">
  <Typography>Showing 1--25 of 250 items</Typography>
  <Pagination rowCount={250} paginationModel={{ page: 1, pageSize: 25 }} onPageChange={setPage} />
</Stack>
```

- **Reset to page 1 when filters change.** When the user applies a new filter or search query, always reset the page to 1 to avoid showing an empty or out-of-range page.

```tsx
useEffect(() => {
  setPage(1);
}, [filters, searchQuery]);
```

- **Do not paginate very small datasets.** If the total number of items fits comfortably on a single screen, display all items directly instead of adding pagination overhead.

```tsx
// Bad -- pagination for 5 items
<Pagination rowCount={5} paginationModel={{ page: 1, pageSize: 10 }} onPageChange={setPage} />

// Good -- just render the list
<ItemList items={items} />
```

- **Handle loading states.** Disable pagination controls while data is being fetched to prevent race conditions from rapid page switches.

- **Use the compact variant on small screens.** The standard variant with page numbers can overflow on narrow viewports. Switch to `variant="compact"` or reduce the `size` prop for responsive layouts.

## Accessibility

- **ARIA attributes**: The current page button is marked with `aria-current="page"`. Previous and next buttons carry descriptive `aria-label` values such as "Previous page" and "Next page".
- **Keyboard navigation**: All pagination buttons are focusable with `Tab` and activated with `Enter` or `Space`. In the compact variant, arrow keys navigate the dropdown options.
- **Disabled states**: When the user is on the first or last page, the corresponding navigation button is properly disabled and announced as such to assistive technologies.
- **Live region consideration**: For dynamic content updates, consider wrapping a status message in an `aria-live="polite"` region to announce the current page to screen reader users.
