# Pagination

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

```ts title="basic.ts"
import "@ui-sdk/web/pagination"
import { ChevronLeft, ChevronRight, createElement, Ellipsis } from "lucide"
import { log } from "./log"

function mount(root: HTMLElement) {
  root.innerHTML = `
    <ui-pagination aria-label="Pagination" page-count="10">
      <ui-pagination-list>
        <ui-pagination-item>
          <ui-pagination-previous>
            <button data-variant="ghost">
              ${createElement(ChevronLeft, { "aria-hidden": "true" }).outerHTML}
              <span data-slot="visually-hidden">Previous</span>
            </button>
          </ui-pagination-previous>
        </ui-pagination-item>
        <template>
          <ui-pagination-item>
            <ui-pagination-link>
              <button data-variant="ghost"></button>
            </ui-pagination-link>
          </ui-pagination-item>
        </template>
        <template data-ellipsis>
          <ui-pagination-item>
            <ui-pagination-ellipsis>${createElement(Ellipsis, { "aria-hidden": "true" }).outerHTML}</ui-pagination-ellipsis>
          </ui-pagination-item>
        </template>
        <ui-pagination-item>
          <ui-pagination-next>
            <button data-variant="ghost">
              <span data-slot="visually-hidden">Next</span>
              ${createElement(ChevronRight, { "aria-hidden": "true" }).outerHTML}
            </button>
          </ui-pagination-next>
        </ui-pagination-item>
      </ui-pagination-list>
    </ui-pagination>
  `
  root
    .querySelector("ui-pagination")!
    .addEventListener("pagechange", (event) => {
      const { value, reason } = event.detail
      log(root, `Page ${value} (${reason})`)
    })
}

export { mount }
```

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

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

导入组件会定义它的元素。在服务器上，导入不做任何事。

```ts
import "@ui-sdk/web/pagination"
```

## 组合
用下面的组合构建 `ui-pagination`：

```text
ui-pagination
└── ui-pagination-list
    ├── ui-pagination-item
    │   └── ui-pagination-previous
    │       └── button
    ├── template
    │   └── ui-pagination-item
    │       └── ui-pagination-link
    │           └── button
    ├── template
    │   └── ui-pagination-item
    │       └── ui-pagination-ellipsis
    └── ui-pagination-item
        └── ui-pagination-next
            └── button
```

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

带 `<template>` 的列表会用它渲染范围：每一页复制一份模板，页码放进一个空按钮，每个空缺用 `<template data-ellipsis>`。没有省略号模板时，空缺会得到一个普通的 `<ui-pagination-ellipsis>`。链接和步进会包住你自己的 `<button>`，或者配合 [`getHref`](https://ui-sdk.cn/docs/web-components/components/pagination#links) 包住 `<a>`，所以要为这些元素设置样式。你自己写的链接，比如服务器写的，会带一个 `page` 属性。

模板会在范围移动时保留页面条目的 key。当前页包住的按钮会得到 `aria-current="page"` 和 `data-current`；省略号显示“…”并对屏幕阅读器隐藏。

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

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

```html
<script type="module">
  import "@ui-sdk/web/pagination"
</script>

<ui-pagination aria-label="Pagination" page-count="10">
  <ui-pagination-list>
    <ui-pagination-item>
      <ui-pagination-previous><button>Previous</button></ui-pagination-previous>
    </ui-pagination-item>
    <template>
      <ui-pagination-item>
        <ui-pagination-link><button></button></ui-pagination-link>
      </ui-pagination-item>
    </template>
    <ui-pagination-item>
      <ui-pagination-next><button>Next</button></ui-pagination-next>
    </ui-pagination-item>
  </ui-pagination-list>
</ui-pagination>
```

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

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

```ts title="total.ts"
import "@ui-sdk/web/pagination"
import { ChevronLeft, ChevronRight, createElement, Ellipsis } from "lucide"
import { log } from "./log"

function mount(root: HTMLElement) {
  root.innerHTML = `
    <div data-slot="stack">
      <div data-slot="row">
        <p>Showing 21–40 of 95</p>
        <label data-slot="label">
          Rows per page
          <select>
            <option value="10">10</option>
            <option value="20" selected>20</option>
            <option value="50">50</option>
          </select>
        </label>
      </div>
      <ui-pagination aria-label="Pagination" total="95" page-size="20" default-page="2">
        <ui-pagination-list>
          <ui-pagination-item>
            <ui-pagination-previous>
              <button data-variant="ghost">
                ${createElement(ChevronLeft, { "aria-hidden": "true" }).outerHTML}
                <span data-slot="visually-hidden">Previous</span>
              </button>
            </ui-pagination-previous>
          </ui-pagination-item>
          <template>
            <ui-pagination-item>
              <ui-pagination-link>
                <button data-variant="ghost"></button>
              </ui-pagination-link>
            </ui-pagination-item>
          </template>
          <template data-ellipsis>
            <ui-pagination-item>
              <ui-pagination-ellipsis>${createElement(Ellipsis, { "aria-hidden": "true" }).outerHTML}</ui-pagination-ellipsis>
            </ui-pagination-item>
          </template>
          <ui-pagination-item>
            <ui-pagination-next>
              <button data-variant="ghost">
                <span data-slot="visually-hidden">Next</span>
                ${createElement(ChevronRight, { "aria-hidden": "true" }).outerHTML}
              </button>
            </ui-pagination-next>
          </ui-pagination-item>
        </ui-pagination-list>
      </ui-pagination>
    </div>
  `
  const pagination = root.querySelector("ui-pagination")!
  const select = root.querySelector("select")!
  const showing = (page: number) => {
    const size = Number(select.value)
    root.querySelector("p")!.textContent =
      `Showing ${(page - 1) * size + 1}–${Math.min(page * size, 95)} of 95`
  }
  pagination.addEventListener("pagechange", (event) => {
    showing(event.detail.value)
    if (event.detail.reason !== "imperative") {
      log(root, `Page ${event.detail.value}`)
    }
  })
  select.addEventListener("change", () => {
    pagination.setAttribute("page-size", select.value)
    pagination.page = 1
    showing(1)
    log(root, `${select.value} rows per page`)
  })
}

export { mount }
```

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

## 简单
只有几页时，范围里没有空缺，所以可以直接把链接写出来，省掉步进。你自己写的链接会带一个 `page` 属性，并且需要自己的数字。

```html
<ui-pagination aria-label="Pagination" page-count="5">
  <ui-pagination-list>
    <ui-pagination-item
      ><ui-pagination-link page="1"
        ><button>1</button></ui-pagination-link
      ></ui-pagination-item
    >
    <ui-pagination-item
      ><ui-pagination-link page="2"
        ><button>2</button></ui-pagination-link
      ></ui-pagination-item
    >
    <ui-pagination-item
      ><ui-pagination-link page="3"
        ><button>3</button></ui-pagination-link
      ></ui-pagination-item
    >
    <ui-pagination-item
      ><ui-pagination-link page="4"
        ><button>4</button></ui-pagination-link
      ></ui-pagination-item
    >
    <ui-pagination-item
      ><ui-pagination-link page="5"
        ><button>5</button></ui-pagination-link
      ></ui-pagination-item
    >
  </ui-pagination-list>
</ui-pagination>
```

## 链接
设置 `getHref` property 把每一页映射到一个 URL，并包住 `<a>` 元素而不是按钮。

```html
<ui-pagination aria-label="Pagination" page-count="10">
  <ui-pagination-list>
    <ui-pagination-item>
      <ui-pagination-previous><a>Previous</a></ui-pagination-previous>
    </ui-pagination-item>
    <template>
      <ui-pagination-item>
        <ui-pagination-link><a></a></ui-pagination-link>
      </ui-pagination-item>
    </template>
    <ui-pagination-item>
      <ui-pagination-next><a>Next</a></ui-pagination-next>
    </ui-pagination-item>
  </ui-pagination-list>
</ui-pagination>
```

```ts
document.querySelector("ui-pagination")!.getHref = (page) =>
  `/posts?page=${page}`
```

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

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

## 路由器链接
在客户端渲染你的路由器链接来翻页。部件会绑定它们包住的任何 `<a>`，所以监听链接点击的路由器可以继续工作。分页的点击处理函数先运行：当变更被取消或步进位于端点时，它会调用 `preventDefault()`。导航之前检查 `event.defaultPrevented`。

从 URL 读取当前页，比如你路由器的搜索参数，并用它设置 [`page` property](https://ui-sdk.cn/docs/web-components/components/pagination#controlled)。

```ts
const pagination = document.querySelector("ui-pagination")!
pagination.getHref = (page) => `?page=${page}`
pagination.page = Number(new URL(location.href).searchParams.get("page") ?? 1)
```

## 受控
元素自己拥有它的页。监听 `pagechange`，在它上面调用 `preventDefault()` 可以保留当前页。`page` property 读取当前页，设置它会前往该页。

```ts
const pagination = document.querySelector("ui-pagination")!
pagination.addEventListener("pagechange", (event) =>
  console.log(event.detail.value, event.detail.reason)
)
pagination.page = 1
```

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

## 默认页
`default-page` 是非受控时起始的页。默认是 1。

```html
<ui-pagination aria-label="Pagination" page-count="10" default-page="5">
  ...
</ui-pagination>
```

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

```html
<ui-pagination
  aria-label="Pagination"
  page-count="20"
  default-page="10"
  siblings="2"
>
  ...
</ui-pagination>
```

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

```html
<ui-pagination
  aria-label="Pagination"
  page-count="20"
  default-page="10"
  boundaries="2"
>
  ...
</ui-pagination>
```

## 从任意位置翻页
元素的 `api` property 就是它的[控制器](https://ui-sdk.cn/docs/web-components/components/pagination#controller)：它可以从任何地方翻页，比如页面别处的按钮或键盘快捷键。也可以用 `createPaginationController()` 创建一个，并设置 `controller` property。

```html
<button type="button" data-action="next">Next Page</button>
<ui-pagination aria-label="Pagination" page-count="10"> ... </ui-pagination>
```

```ts
const pagination = document.querySelector("ui-pagination")!.api
document
  .querySelector('[data-action="next"]')!
  .addEventListener("click", () => pagination.next())
```

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

```html
<div role="group" aria-label="Slides"></div>
```

```ts
import { paginationRange } from "@ui-sdk/core/pagination"

function renderDots(group: HTMLElement, slide: number) {
  const items = paginationRange({
    page: slide,
    pageCount: 20,
    siblings: 2,
    boundaries: 1,
  })
  group.replaceChildren(
    ...items.map((item) => {
      if (typeof item !== "number") {
        const gap = document.createElement("span")
        gap.setAttribute("aria-hidden", "true")
        return gap
      }
      const dot = document.createElement("button")
      dot.setAttribute("aria-label", `Slide ${item}`)
      if (item === slide) dot.setAttribute("aria-current", "true")
      dot.addEventListener("click", () => renderDots(group, item))
      return dot
    })
  )
}
```

## 自定义渲染
元素没有渲染函数。链接和步进会包住你自己的元素，所以直接更改它们，并从它们的属性、`page` property 或 `pagechange` 事件读取状态：链接是否是当前页，对于步进，还有它要去的页以及它是否禁用。这里一个 `pagechange` 监听器会把 Page 3 写进当前链接，并给每个箭头它要去的页和一个标题。

```ts title="render.ts"
import "@ui-sdk/web/pagination"
import { ArrowLeft, ArrowRight, createElement } from "lucide"

function mount(root: HTMLElement) {
  root.innerHTML = `
    <ui-pagination aria-label="Pagination" page-count="10">
      <ui-pagination-list>
        <ui-pagination-item>
          <ui-pagination-previous>
            <button aria-label="Previous page">
              ${createElement(ArrowLeft, { "aria-hidden": "true" }).outerHTML}
              <span aria-hidden="true"></span>
            </button>
          </ui-pagination-previous>
        </ui-pagination-item>
        <template>
          <ui-pagination-item>
            <ui-pagination-link>
              <button></button>
            </ui-pagination-link>
          </ui-pagination-item>
        </template>
        <ui-pagination-item>
          <ui-pagination-next>
            <button aria-label="Next page">
              <span aria-hidden="true"></span>
              ${createElement(ArrowRight, { "aria-hidden": "true" }).outerHTML}
            </button>
          </ui-pagination-next>
        </ui-pagination-item>
      </ui-pagination-list>
    </ui-pagination>
  `
  const pagination = root.querySelector("ui-pagination")!

  function step(selector: string, page: number) {
    const button = root.querySelector<HTMLButtonElement>(`${selector} button`)!
    const disabled = page < 1 || page > pagination.api.getPageCount()
    button.querySelector("span")!.hidden = disabled
    button.querySelector("span")!.textContent = String(page)
    if (disabled) {
      button.removeAttribute("title")
    } else {
      button.title = `Go to page ${page}`
    }
  }

  function update() {
    const page = pagination.page
    step("ui-pagination-previous", page - 1)
    step("ui-pagination-next", page + 1)
    for (const link of root.querySelectorAll("ui-pagination-link[page]")) {
      const n = Number(link.getAttribute("page"))
      link.querySelector("button")!.textContent =
        n === page ? `Page ${n}` : String(n)
    }
  }

  queueMicrotask(update)
  pagination.addEventListener("pagechange", () => queueMicrotask(update))
}

export { mount }
```

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

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

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

列表和它的条目是 `<ui-pagination-list>` 和 `<ui-pagination-item>`，它们显示为块。给列表设置 `flex`，让页面排成一行。

## 数据属性
### `<ui-pagination-link>`
`[data-slot="pagination-link"]`

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

### `<ui-pagination-previous>`
`[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.

### `<ui-pagination-next>`
`[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.

### `<ui-pagination-first>`
`[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.

### `<ui-pagination-last>`
`[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 参考
Props 是 kebab case 的属性，比如 `page-count`、`default-page` 和 `page-size`，数字按数字处理。`getHref` 和 `controller` 是 property。`page` 是实时 property。回调是 DOM 事件。

### Pagination
- `page?` (`number`): The current page, from 1. Pass it to control the pagination.
- `defaultPage?` (`number`): The page it starts on, when uncontrolled.
- `pagechange event`: 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。

### 状态
相同的状态会作为属性显示在每个链接和步进上。

`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.

### 原因
`event.detail.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.

### 控制器
元素的 `api` property 有相同的方法。

每个写入方法都接受可选的 `{ reason, event }`，传给 `pagechange`，并在变更被取消或无处可去时返回 `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.

### 事件
事件在各自的元素上触发，不会冒泡，新的页码位于 `event.detail.value`，`reason` 和 `event` 与它并列。调用 `preventDefault()` 会取消变更。把元素类型写成 `UiPaginationElement`，监听器就有类型。

| Member                | 所属元素        | 说明                                             |
| --------------------- | --------------- | ------------------------------------------------ |
| `page` property       | `ui-pagination` | 当前页。设置它会前往该页                         |
| `api` property        | `ui-pagination` | [控制器](https://ui-sdk.cn/docs/web-components/components/pagination#controller)                            |
| `getHref` property    | `ui-pagination` | 某一页的 URL。有了它，就包住链接而不是按钮       |
| `controller` property | `ui-pagination` | 来自 `createPaginationController()` 的控制器     |
| `pagechange` event    | `ui-pagination` | `detail: { value: page, reason, event, source }` |

## 无障碍
分页没有 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.
