# Pagination

Previous, every page and next as quiet buttons, with one glass marker that glides to the page you pick.

Tier: free. Type: component. Category: navigation. Tags: motion, table.

## Install

```bash
npx shadcn@latest add @pixilui/pagination
```

One-time setup: add the registry to `components.json`:

```json
{
  "registries": {
    "@pixilui": "https://pixilui.com/r/{name}.json"
  }
}
```

Files: `components/pixilui/pagination.tsx`.

## Preview

Live preview: https://pixilui.com/components/pagination

Signature: One glass marker glides between page numbers instead of each page lighting up on its own.

Styles: `quiet` (default), `lively`, set with `data-style` on <html>. The item reads the style through the foundation; it needs no prop. Standalone files: quiet https://pixilui.com/r/standalone/pagination.tsx, lively https://pixilui.com/r/standalone/pagination.lively.tsx.

## Code

`components/pixilui/pagination.tsx`

```tsx
"use client";

import { forwardRef, useCallback, useLayoutEffect, useRef, useState, type ComponentPropsWithoutRef, type ReactNode } from "react";
import { cn } from "./lib/utils";
import { Button } from "./button";

/*
  The locked pagination (exploration 04): Secondary 2 page buttons with one glass marker that glides
  to the current page. The marker's look and glide live in foundation.css section 7
  (pixilui-btn-pages); this file places it, at once on first paint and after the font loads.
*/

export type PaginationProps = Omit<ComponentPropsWithoutRef<"div">, "onChange" | "children"> & {
  /** How many pages there are. Every page shows, so keep it to about 7. */
  pageCount: number;
  /** The current page (from 1), controlled. Pair with onPageChange. */
  page?: number;
  /** The starting page when uncontrolled. */
  defaultPage?: number;
  /** Runs with the page a person picked. */
  onPageChange?: (page: number) => void | Promise<void>;
  /** The previous icon (Lucide ArrowLeft). */
  previousIcon: ReactNode;
  /** The next icon (Lucide ArrowRight). */
  nextIcon: ReactNode;
  /** Accessible name of the previous button. */
  previousLabel?: string;
  /** Accessible name of the next button. */
  nextLabel?: string;
  /** Names the navigation for screen readers. */
  "aria-label"?: string;
};

/** Previous, every page, next: one glass marker glides to the current page. */
export const Pagination = forwardRef<HTMLDivElement, PaginationProps>(function Pagination(
  { pageCount, page: pageProp, defaultPage = 1, onPageChange, previousIcon, nextIcon, previousLabel = "Previous page", nextLabel = "Next page", "aria-label": ariaLabel = "Pages", className, ...rest },
  ref,
) {
  const [inner, setInner] = useState(defaultPage);
  const page = pageProp ?? inner;
  const mark = useRef<HTMLSpanElement | null>(null);
  const nav = useRef<HTMLDivElement | null>(null);
  const placed = useRef(false);
  const setRef = useCallback(
    (node: HTMLDivElement | null) => {
      nav.current = node;
      if (typeof ref === "function") ref(node);
      else if (ref) ref.current = node;
    },
    [ref],
  );

  useLayoutEffect(() => {
    const place = () => {
      const current = nav.current?.querySelector<HTMLElement>('[aria-current="page"]');
      const el = mark.current;
      if (!current || !el) return;
      const instant = !placed.current;
      if (instant) el.style.transition = "none";
      el.style.setProperty("--btn-mx", `${current.offsetLeft}px`);
      el.style.setProperty("--btn-mw", `${current.offsetWidth}px`);
      if (instant) {
        void el.offsetWidth;
        el.style.transition = "";
      }
    };
    place();
    placed.current = true;
    document.fonts?.ready.then(() => {
      placed.current = false;
      place();
      placed.current = true;
    });
  }, [page]);

  const go = (next: number) => {
    if (next < 1 || next > pageCount || next === page) return;
    if (pageProp === undefined) setInner(next);
    void onPageChange?.(next);
  };

  return (
    <div ref={setRef} className={cn("pixilui-btn-pages font-body", className)} data-has-mark="" role="navigation" aria-label={ariaLabel} {...rest}>
      <span ref={mark} className="pixilui-btn-pages-mark" aria-hidden="true" />
      <Button variant="secondary-2" size="sm" aria-label={previousLabel} icon={previousIcon} disabled={page === 1} onClick={() => go(page - 1)} />
      {Array.from({ length: pageCount }, (_, i) => i + 1).map((n) => (
        <Button key={n} variant="secondary-2" size="sm" aria-current={n === page ? "page" : undefined} onClick={() => go(n)}>
          {String(n)}
        </Button>
      ))}
      <Button variant="secondary-2" size="sm" aria-label={nextLabel} icon={nextIcon} disabled={page === pageCount} onClick={() => go(page + 1)} />
    </div>
  );
});
```

## Usage

When to use:

- Paging a short list: run history, an audit log, eval results, a few pages of invoices.
- Under a table whose row count is known up front.

When not to use:

- More than about 7 pages: this shows every page; use a windowed pagination or a page input.
- Feeds that grow as you read: load more on scroll or with a button.

```tsx
import { IconBack } from "@/components/pixilui/icons/back";
import { IconForward } from "@/components/pixilui/icons/forward";
import { Pagination } from "@/components/pixilui/pagination";

// One finished element, no rows.
export const knobs = {} as const;

export default function PaginationDemo() {
  return <Pagination pageCount={3} defaultPage={2} previousIcon={<IconBack />} nextIcon={<IconForward />} />;
}
```

## Examples

None.

## API

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `aria-label` | `string` |  | Names the navigation for screen readers. |
| `pageCount` (required) | `number` |  | How many pages there are. Every page shows, so keep it to about 7. |
| `page` | `number` |  | The current page (from 1), controlled. Pair with onPageChange. |
| `defaultPage` | `number` | `1` | The starting page when uncontrolled. |
| `onPageChange` | `(page: number) => void \| Promise<void>` |  | Runs with the page a person picked. |
| `previousIcon` (required) | `ReactNode` |  | The previous icon (Lucide ArrowLeft). |
| `nextIcon` (required) | `ReactNode` |  | The next icon (Lucide ArrowRight). |
| `previousLabel` | `string` | `"Previous page"` | Accessible name of the previous button. |
| `nextLabel` | `string` | `"Next page"` | Accessible name of the next button. |

Also accepts every native `<div>` attribute except `onChange`, and a ref to it.

## Keyboard

- `Tab`: Moves through previous, each page and next.
- `Enter`: Goes to the focused page.
- `Space`: The same as Enter, on release.

## Accessibility

- A navigation landmark named Pages (aria-label), holding native buttons.
- The current page has aria-current="page".
- Previous and next are named Previous page and Next page, and disable on the first and last page.
- The marker is aria-hidden decoration.

## Motion

- The glass marker glides to the new page on the snappy spring, its width following the number.
- On first paint and after the font loads the marker is placed at once, never sliding in from the start.
- Reduced motion: the marker moves at once.

## Responsive

- As wide as its pages. Three to seven pages fit at 375 wide.

## Performance

- The marker moves by two custom properties on one element.

## Notes for AI

- Pass pageCount, then page and onPageChange (controlled) or defaultPage. Pages count from 1.
- It shows every page and suits up to about 7; windowing with ellipses is a follow-up.
- Pass previousIcon and nextIcon (Lucide ArrowLeft and ArrowRight); never import an icon library inside the component.

## Related

- [Button](https://pixilui.com/components/button/markdown): The PixilUI button in four main styles and four more, five sizes from 24 to 44, with icons, loading, disabled, a count and a shortcut.
- [Segmented control](https://pixilui.com/components/segmented-control/markdown): Two to five mutually exclusive choices on one glass track, with a thumb that glides to the one you pick and jumps at once when you arrow through them.
- [Stepper](https://pixilui.com/components/stepper/markdown): Fewer and more around a small number, such as parallel runs or seats, where the number rolls up or down the way it moved and each end disables its button.
