# Pagination

用按钮、链接或你的路由器在页面之间导航。

```svelte title="basic.svelte"
<script lang="ts">
  import {
    ChevronLeftIcon,
    ChevronRightIcon,
    EllipsisIcon,
  } from "@lucide/svelte"
  import {
    Pagination,
    PaginationEllipsis,
    PaginationItem,
    PaginationLink,
    PaginationList,
    PaginationNext,
    PaginationPrevious,
  } from "@ui-sdk/svelte/pagination"
  import { useLog } from "./log"

  const log = useLog()
</script>

<Pagination
  aria-label="Pagination"
  pageCount={10}
  onPageChange={(page, details) => log(`Page ${page} (${details.reason})`)}
>
  <PaginationList>
    {#snippet children(state)}
      <PaginationItem>
        <PaginationPrevious data-variant="ghost">
          <ChevronLeftIcon />
          <span data-slot="visually-hidden">Previous</span>
        </PaginationPrevious>
      </PaginationItem>
      {#each state.items as item (item)}
        <PaginationItem>
          {#if typeof item === "number"}
            <PaginationLink data-variant="ghost" page={item} />
          {:else}
            <PaginationEllipsis>
              <EllipsisIcon />
            </PaginationEllipsis>
          {/if}
        </PaginationItem>
      {/each}
      <PaginationItem>
        <PaginationNext data-variant="ghost">
          <span data-slot="visually-hidden">Next</span>
          <ChevronRightIcon />
        </PaginationNext>
      </PaginationItem>
    {/snippet}
  </PaginationList>
</Pagination>
```

选择某一页，或使用 Previous 和 Next。控制台会记录每一页及其原因，两端的步进仍作为按钮保持可聚焦。

## 安装
```bash
npm install @ui-sdk/svelte @ui-sdk/core
```

## 组合
用下面的组合构建 `Pagination`：

```text
Pagination
└── PaginationList
    ├── PaginationItem
    │   └── PaginationPrevious
    ├── PaginationItem
    │   └── PaginationLink
    ├── PaginationItem
    │   └── PaginationEllipsis
    ├── PaginationItem
    │   └── PaginationLink
    └── PaginationItem
        └── PaginationNext
```

用 `aria-label` 给这个导航命名，然后把页面链接和步进放进一个列表。

列表的 `children` 片段会收到它的状态，其中的 `items` 包含页码，以及字符串 `"ellipsis-start"` 和 `"ellipsis-end"`。为每个页码渲染一个链接，为每个空缺渲染一个省略号。用条目本身作为 key，这样范围移动时页面链接会保留它的元素。

`PaginationLink` 显示自己的页码，除非你提供 children。当前链接会得到 `aria-current="page"` 和 `data-current`。`PaginationEllipsis` 显示“…”并且对屏幕阅读器隐藏。

给 Previous、Next、First 和 Last 文本或一个 `aria-label`。位于端点时，步进会得到 `aria-disabled="true"` 和 `data-disabled`，不再更改当前页。作为按钮，它仍留在 Tab 顺序里。在根上设置 `disabled`，可以对每一页和每个步进做同样的事，比如在结果加载期间。控制器仍然可以更改当前页。

## 用法
导入这些部件并把它们组合起来：

```svelte
<script lang="ts">
  import {
    Pagination,
    PaginationEllipsis,
    PaginationItem,
    PaginationLink,
    PaginationList,
    PaginationNext,
    PaginationPrevious,
  } from "@ui-sdk/svelte/pagination"
</script>

<Pagination aria-label="Pagination" pageCount={10}>
  <PaginationList>
    {#snippet children({ items })}
      <PaginationItem>
        <PaginationPrevious>Previous</PaginationPrevious>
      </PaginationItem>
      {#each items as item (item)}
        <PaginationItem>
          {#if typeof item === "number"}
            <PaginationLink page={item} />
          {:else}
            <PaginationEllipsis />
          {/if}
        </PaginationItem>
      {/each}
      <PaginationItem>
        <PaginationNext>Next</PaginationNext>
      </PaginationItem>
    {/snippet}
  </PaginationList>
</Pagination>
```

## 总数与每页数量
除了 `pageCount`，也可以传入 `total`（一共有多少条）和 `pageSize`（每页能放多少条，默认是 10）。Pagination 会计算页数，最少为一页。这个示例在每页数量变化时会重置到第 1 页。

超出末尾的页码，比如在数量变小之后，会视为最后一页。

```svelte title="total.svelte"
<script lang="ts">
  import {
    ChevronLeftIcon,
    ChevronRightIcon,
    EllipsisIcon,
  } from "@lucide/svelte"
  import {
    Pagination,
    PaginationEllipsis,
    PaginationItem,
    PaginationLink,
    PaginationList,
    PaginationNext,
    PaginationPrevious,
  } from "@ui-sdk/svelte/pagination"
  import { useLog } from "./log"

  const log = useLog()
  let page = $state(2)
  let pageSize = $state(20)
  const total = 95

  function onchange(event: Event & { currentTarget: HTMLSelectElement }) {
    pageSize = Number(event.currentTarget.value)
    page = 1
    log(`${event.currentTarget.value} rows per page`)
  }
</script>

<div data-slot="stack">
  <div data-slot="row">
    <p>
      Showing {(page - 1) * pageSize + 1}–{Math.min(page * pageSize, total)} of {total}
    </p>
    <label data-slot="label">
      Rows per page
      <select value={pageSize} {onchange}>
        <option value={10}>10</option>
        <option value={20}>20</option>
        <option value={50}>50</option>
      </select>
    </label>
  </div>
  <Pagination
    bind:page
    aria-label="Pagination"
    {total}
    {pageSize}
    onPageChange={(next) => log(`Page ${next}`)}
  >
    <PaginationList>
      {#snippet children(state)}
        <PaginationItem>
          <PaginationPrevious data-variant="ghost">
            <ChevronLeftIcon />
            <span data-slot="visually-hidden">Previous</span>
          </PaginationPrevious>
        </PaginationItem>
        {#each state.items as item (item)}
          <PaginationItem>
            {#if typeof item === "number"}
              <PaginationLink data-variant="ghost" page={item} />
            {:else}
              <PaginationEllipsis>
                <EllipsisIcon />
              </PaginationEllipsis>
            {/if}
          </PaginationItem>
        {/each}
        <PaginationItem>
          <PaginationNext data-variant="ghost">
            <span data-slot="visually-hidden">Next</span>
            <ChevronRightIcon />
          </PaginationNext>
        </PaginationItem>
      {/snippet}
    </PaginationList>
  </Pagination>
</div>
```

选择某一页，然后更改 Rows per page。控制台会记录每次变更，新的每页数量会重新从第 1 页开始。

## 简单
只有几页时，范围里没有空缺，所以可以直接把链接写出来，省掉步进。

```svelte
<Pagination aria-label="Pagination" pageCount={5}>
  <PaginationList>
    {#each [1, 2, 3, 4, 5] as page (page)}
      <PaginationItem>
        <PaginationLink {page} />
      </PaginationItem>
    {/each}
  </PaginationList>
</Pagination>
```

## 链接
传入 `getHref`，把每一页映射到一个 URL。页面链接和步进就会渲染成锚点。

```svelte
<Pagination
  aria-label="Pagination"
  pageCount={10}
  getHref={(page) => `/posts?page=${page}`}
>
  ...
</Pagination>
```

服务端渲染的锚点在 JavaScript 加载之前就能工作。普通点击会更改当前页并跟随 URL。带修饰键的点击和中键点击不会改动分页状态，这样浏览器可以在别处打开链接。

位于端点的步进会失去它的 `href` 并离开 Tab 顺序，但如果它已经拥有焦点，就会保留焦点。导航期间，它原来的 `href` 保持原位，这样 Next 不会意外跟随下一页的 URL。

## 路由器链接
在客户端渲染你的路由器链接来翻页。部件用 `getHref` 渲染 `<a>` 元素，所以像 SvelteKit 这样监听链接点击的路由器会照常翻页。路由器的链接组件放进 `render` 片段，带上 `{...props}`；它会收到部件的 props，包括 `href`。分页的点击处理函数先运行：当变更被取消或步进位于端点时，它会调用 `preventDefault()`，路由器就不再处理这个链接。

从 URL 读取当前页，比如你路由器的搜索参数，让路由来[控制](https://ui-sdk.cn/docs/svelte/components/pagination#controlled)分页。

```svelte
<script lang="ts">
  import { page as route } from "$app/state"

  const page = $derived(Number(route.url.searchParams.get("page") ?? 1))
</script>

<Pagination
  aria-label="Pagination"
  pageCount={10}
  {page}
  getHref={(page) => `?page=${page}`}
>
  ...
</Pagination>
```

## 受控
用 `bind:page` 绑定 `page` 来控制分页，并用 `onPageChange` 获取原因。

```svelte
<script lang="ts">
  let page = $state(1)
</script>

<Pagination bind:page aria-label="Pagination" pageCount={10}>...</Pagination>
```

每次变更都带一个[原因](https://ui-sdk.cn/docs/svelte/components/pagination#reasons)：页面用 `item-press`，步进用 `previous-press`、`next-press`、`first-press` 或 `last-press`，[控制器](https://ui-sdk.cn/docs/svelte/components/pagination#controller)用 `imperative`。调用 `details.cancel()` 可以保留当前页，比如表单还有未保存的更改时。被取消的变更也会阻止链接导航。

## 默认页
`defaultPage` 是非受控时起始的页。默认是 1。

```svelte
<Pagination aria-label="Pagination" pageCount={10} defaultPage={5}>
  ...
</Pagination>
```

## 相邻页
`siblings` 是当前页两侧各显示多少页，默认是 1。靠近端点时，窗口会整体滑动而不是收缩，让范围的长度保持稳定。只隔一页的空缺会显示那一页，而不是省略号。

```svelte
<Pagination
  aria-label="Pagination"
  pageCount={20}
  defaultPage={10}
  siblings={2}
>
  ...
</Pagination>
```

## 边界
`boundaries` 是两端始终显示多少页，默认是 1。

```svelte
<Pagination
  aria-label="Pagination"
  pageCount={20}
  defaultPage={10}
  boundaries={2}
>
  ...
</Pagination>
```

## 从任意位置翻页
用 `createPaginationController()` 创建一个[控制器](https://ui-sdk.cn/docs/svelte/components/pagination#controller)，它就能从任何地方翻页，比如页面别处的按钮或键盘快捷键，而不必让分页受控。把它作为 `controller` 传入。

```svelte
<script lang="ts">
  const pagination = createPaginationController()
</script>

<button onclick={() => pagination.next()}>Next Page</button>
<Pagination aria-label="Pagination" pageCount={10} controller={pagination}>
  ...
</Pagination>
```

## 自己的标记
`paginationRange({ page, pageCount, siblings, boundaries })` 是各个部件使用的范围，以纯函数的形式提供。它可以在任何地方运行，比如在服务器上、在电子邮件里，或者用在不以页面列表呈现的界面上。从 `@ui-sdk/core/pagination` 导入它。这里它让一排幻灯片圆点无论有多少张幻灯片都保持同样的长度。

```svelte
<script lang="ts">
  import { paginationRange } from "@ui-sdk/core/pagination"

  const items = $derived(
    paginationRange({ page: slide, pageCount: 20, siblings: 2, boundaries: 1 })
  )
</script>

<div role="group" aria-label="Slides">
  {#each items as item (item)}
    {#if typeof item === "number"}
      <button
        aria-label={`Slide ${item}`}
        aria-current={item === slide ? "true" : undefined}
        onclick={() => (slide = item)}
      ></button>
    {:else}
      <span aria-hidden="true"></span>
    {/if}
  {/each}
</div>
```

## 自定义渲染
每个部件都接受一个 `render` 片段，它收到要展开的 props 和部件的状态：链接是否 `current`，对于步进，还有它要去的 `page` 以及它是否 `disabled`。`children` 片段也会收到状态。

```svelte title="render.svelte"
<script lang="ts">
  import { ArrowLeftIcon, ArrowRightIcon } from "@lucide/svelte"
  import {
    Pagination,
    PaginationEllipsis,
    PaginationItem,
    PaginationLink,
    PaginationList,
    PaginationNext,
    PaginationPrevious,
  } from "@ui-sdk/svelte/pagination"
</script>

<Pagination aria-label="Pagination" pageCount={10}>
  <PaginationList>
    {#snippet children(state)}
      <PaginationItem>
        <PaginationPrevious aria-label="Previous page">
          {#snippet render({ props, state: step })}
            <button
              {...props}
              title={step.disabled ? undefined : `Go to page ${step.page}`}
            >
              <ArrowLeftIcon aria-hidden="true" />
              {#if !step.disabled}
                <span aria-hidden="true">{step.page}</span>
              {/if}
            </button>
          {/snippet}
        </PaginationPrevious>
      </PaginationItem>
      {#each state.items as item (item)}
        <PaginationItem>
          {#if typeof item === "number"}
            <PaginationLink page={item}>
              {#snippet children(link)}
                {link.current ? `Page ${link.page}` : link.page}
              {/snippet}
            </PaginationLink>
          {:else}
            <PaginationEllipsis />
          {/if}
        </PaginationItem>
      {/each}
      <PaginationItem>
        <PaginationNext aria-label="Next page">
          {#snippet render({ props, state: step })}
            <button
              {...props}
              title={step.disabled ? undefined : `Go to page ${step.page}`}
            >
              {#if !step.disabled}
                <span aria-hidden="true">{step.page}</span>
              {/if}
              <ArrowRightIcon aria-hidden="true" />
            </button>
          {/snippet}
        </PaginationNext>
      </PaginationItem>
    {/snippet}
  </PaginationList>
</Pagination>
```

选择某一页。当前页会变宽，显示 Page 3，每个箭头会显示它将前往的那一页。

## 样式
部件没有样式。通过它们渲染的属性来设置样式，这些属性在每个框架里都相同：当前页链接上的 `aria-current="page"` 或 `data-current`，以及位于端点的步进上的 `aria-disabled` 或 `data-disabled`。

每个部件都有一个 `data-slot`，比如 `pagination-link`，它的状态属性列在[数据属性](https://ui-sdk.cn/docs/svelte/components/pagination#data-attributes)下。根、列表、条目和省略号都没有。

## 数据属性
### PaginationLink
`[data-slot="pagination-link"]`

- `data-current`: Present on the current page's link, beside `aria-current="page"`.

### PaginationPrevious
`[data-slot="pagination-previous"]`

- `data-disabled`: Present on a step at the end it goes to, beside `aria-disabled`. It stays focusable and does nothing.

### PaginationNext
`[data-slot="pagination-next"]`

- `data-disabled`: Present on a step at the end it goes to, beside `aria-disabled`. It stays focusable and does nothing.

### PaginationFirst
`[data-slot="pagination-first"]`

- `data-disabled`: Present on a step at the end it goes to, beside `aria-disabled`. It stays focusable and does nothing.

### PaginationLast
`[data-slot="pagination-last"]`

- `data-disabled`: Present on a step at the end it goes to, beside `aria-disabled`. It stays focusable and does nothing.

## API 参考
属性和回调与下面相同，都作为 Svelte props。`page` 可以用 `bind:page` 绑定。

### Pagination
- `page?` (`number`): The current page, from 1. Pass it to control the pagination.
- `defaultPage?` (`number`): The page it starts on, when uncontrolled.
- `onPageChange?` (`((page: number, details: ChangeDetails<PaginationPageChangeReason>) => void)`): Runs when the page wants to change: a page link (`"item-press"`), the Previous, Next, First or Last part, or a controller (`"imperative"`). `details.cancel()` keeps the page, and stops a link from navigating.
- `pageCount?` (`number`): How many pages there are. Or pass `total` and `pageSize`.
- `total?` (`number`): How many items there are, for `pageCount` from `pageSize`.
- `pageSize?` (`number`): How many items fit on a page, with `total`.
- `siblings?` (`number`): How many pages show on each side of the current one.
- `boundaries?` (`number`): How many pages always show at each end.
- `getHref?` (`((page: number) => string)`): The URL of a page. With it, parts are links: they navigate, open in a new tab with a modifier key, and work before JavaScript loads. Without it, they're buttons.
- `disabled?` (`boolean`): Whether every page and step does nothing, like a step at its end. A controller still pages it.
- `controller?` (`object`): Pages it from anywhere. Create one with `createPaginationController()`.
- `debug?` (`boolean`): Logs every state change with its reason to the console, in development builds.

### PaginationLink
- `page` (`number`): The page the link goes to, from 1.

`PaginationList`、`PaginationItem`、`PaginationPrevious`、`PaginationNext`、`PaginationFirst`、`PaginationLast` 和 `PaginationEllipsis` 没有自己的 props。

### 状态
`render` 和 `children` 片段按部件分别收到什么。

`Pagination` 和 `PaginationList`：

- `page` (`number`): The current page, from 1.
- `pageCount` (`number`): How many pages there are.
- `items` (`PaginationRangeItem[]`): The pages to show, with an ellipsis for each gap. Render a PaginationLink or a PaginationEllipsis for each.

`PaginationLink`：

- `page` (`number`): The page it goes to, from its `page` prop.
- `current` (`boolean`): Whether it's the current page.

`PaginationPrevious`、`PaginationNext`、`PaginationFirst` 和 `PaginationLast`：

- `page` (`number`): The page it goes to.
- `disabled` (`boolean`): Whether it's at the end it goes to, or the pagination is disabled, so it does nothing.

### 原因
`details.reason` 说明页码为什么变化。

- `item-press` (`MouseEvent | KeyboardEvent`): A member of a collection was chosen: a menu item, a tab, a radio or a checkbox item.
- `previous-press` (`MouseEvent | KeyboardEvent`): A pagination's or a carousel's Previous part was pressed.
- `next-press` (`MouseEvent | KeyboardEvent`): A pagination's or a carousel's Next part was pressed.
- `first-press` (`MouseEvent | KeyboardEvent`): A pagination's First part was pressed.
- `last-press` (`MouseEvent | KeyboardEvent`): A pagination's Last part was pressed.
- `imperative` (`none`): A controller or `api` call.

### 控制器
用 `createPaginationController()` 创建一个，并作为 `controller` 传入。

每个写入方法都接受可选的 `{ reason, event }`，传给 `onPageChange`，并在变更被取消或无处可去时返回 `false`。

- `getPage()` (`() => number`): The current page, from 1.
- `getPageCount()` (`() => number`): How many pages there are.
- `setPage(page, options?)` (`(page: number, options?: PaginationChangeOptions | undefined) => boolean`): Goes to a page, clamped to the range. Returns false when canceled or already there.
- `next(options?)` (`(options?: PaginationChangeOptions | undefined) => boolean`): Goes to the next page. Returns false on the last page.
- `previous(options?)` (`(options?: PaginationChangeOptions | undefined) => boolean`): Goes to the previous page. Returns false on the first page.
- `first(options?)` (`(options?: PaginationChangeOptions | undefined) => boolean`): Goes to the first page.
- `last(options?)` (`(options?: PaginationChangeOptions | undefined) => boolean`): Goes to the last page.

### 事件
回调先收到新的页码，再收到详情。绑定的 `page` 只在 `onPageChange` 未被取消时更新。

| Prop           | 所属部件     | 收到                                              |
| -------------- | ------------ | ------------------------------------------------- |
| `bind:page`    | `Pagination` | 当前页                                            |
| `onPageChange` | `Pagination` | `(page, details)`：新的页码，以及[原因](https://ui-sdk.cn/docs/svelte/components/pagination#reasons) |

## 无障碍
分页没有 WAI-ARIA 模式。它遵循常见的做法：一个用 `aria-label` 命名的 `navigation` 地标，一个由链接或按钮组成的列表，以及当前项上的 `aria-current="page"`。即使样式去掉了项目符号，列表也会保留 `list` 角色，否则 Safari 会丢掉它。

### 焦点
渲染成按钮的步进在两端仍然可以聚焦。被点击的页面链接在范围移动时保持焦点；如果渲染替换了它的元素，原语还会尝试把焦点恢复到那一页或那个步进。用值而不是索引来给范围条目设置 key。

### 经过测试的行为
下面每一行都是一个自动化测试。

- The pagination is a named navigation landmark with a list of pages.
- The first page is current to start with, or the default page.
- Pressing a page goes there.
- Enter on a focused page goes there.
- Space on a focused page goes there.
- Next and Previous step one page.
- First and Last go to the ends.
- First and Previous say they're disabled on the first page, and do nothing.
- Next and Last say they're disabled on the last page, and do nothing.
- A single page has nothing to step to.
- Siblings and boundaries widen the range.
- Ellipses are hidden from screen readers.
- With getHref, pages and steps are links to their pages.
- A link at an end has no href and says it's disabled.
- Pressing a link goes to its page and follows it.
- A change can be canceled.
- A canceled change stops a link from navigating.
- The controller pages it from outside.
- A controlled pagination follows its owner. React 和 Vue only.

Runs in React、Vue 和 web components.

在基线之外：

- Pressing Next onto the last page keeps focus on Next.
- Pressing Previous onto the first page keeps focus on Previous.
- Paging through every page with the keyboard never loses focus.
- Pressing a page keeps focus on it while the range moves around it.
- Focus comes back to the same part when the list renders again from scratch. React 和 Vue only.
- The list has the same number of entries on every page, so nothing shifts under the pointer.
- A gap of one page shows that page instead of an ellipsis.
- A link pressed with a modifier opens elsewhere and leaves the page as it is.
- The list keeps its list role when styled without bullets.
- Steps at the ends stay in the tab order and say they're disabled.
- A Next link goes to the next page, not past it, even after the page renders again.
- A Next link onto the last page still goes there, though it ends there.

Runs in React、Vue 和 web components.

在每个经过测试的框架里，屏幕阅读器听到的内容相同，由虚拟屏幕阅读器录制：

- Announcements while paging with a keyboard.

Runs in React、Vue 和 web components.
