# Pagination

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

```tsx title="basic.tsx"
import {
  Pagination,
  PaginationEllipsis,
  PaginationItem,
  PaginationLink,
  PaginationList,
  PaginationNext,
  PaginationPrevious,
} from "@ui-sdk/solid/pagination"
import { For } from "solid-js"
import { useLog } from "./log"

function Example() {
  const log = useLog()

  return (
    <Pagination
      aria-label="Pagination"
      pageCount={10}
      onPageChange={(page, details) => log(`Page ${page} (${details.reason})`)}
    >
      <PaginationList>
        {({ items }) => (
          <>
            <PaginationItem>
              <PaginationPrevious data-variant="ghost">
                <svg
                  viewBox="0 0 24 24"
                  fill="none"
                  stroke="currentColor"
                  stroke-width="2"
                  stroke-linecap="round"
                  stroke-linejoin="round"
                  aria-hidden="true"
                >
                  <path d="m15 18-6-6 6-6" />
                </svg>
                <span data-slot="visually-hidden">Previous</span>
              </PaginationPrevious>
            </PaginationItem>
            <For each={items}>
              {(item) => (
                <PaginationItem>
                  {typeof item === "number" ? (
                    <PaginationLink data-variant="ghost" page={item} />
                  ) : (
                    <PaginationEllipsis>
                      <svg
                        viewBox="0 0 24 24"
                        fill="none"
                        stroke="currentColor"
                        stroke-width="2"
                        stroke-linecap="round"
                        stroke-linejoin="round"
                        aria-hidden="true"
                      >
                        <circle cx="12" cy="12" r="1" />
                        <circle cx="19" cy="12" r="1" />
                        <circle cx="5" cy="12" r="1" />
                      </svg>
                    </PaginationEllipsis>
                  )}
                </PaginationItem>
              )}
            </For>
            <PaginationItem>
              <PaginationNext data-variant="ghost">
                <span data-slot="visually-hidden">Next</span>
                <svg
                  viewBox="0 0 24 24"
                  fill="none"
                  stroke="currentColor"
                  stroke-width="2"
                  stroke-linecap="round"
                  stroke-linejoin="round"
                  aria-hidden="true"
                >
                  <path d="m9 18 6-6-6-6" />
                </svg>
              </PaginationNext>
            </PaginationItem>
          </>
        )}
      </PaginationList>
    </Pagination>
  )
}

export { Example }
```

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

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

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

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

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

`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`，可以对每一页和每个步进做同样的事，比如在结果加载期间。控制器仍然可以更改当前页。

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

```tsx
import {
  Pagination,
  PaginationEllipsis,
  PaginationItem,
  PaginationLink,
  PaginationList,
  PaginationNext,
  PaginationPrevious,
} from "@ui-sdk/solid/pagination"
import { For } from "solid-js"

function PageNavigation() {
  return (
    <Pagination aria-label="Pagination" pageCount={10}>
      <PaginationList>
        {({ items }) => (
          <>
            <PaginationItem>
              <PaginationPrevious>Previous</PaginationPrevious>
            </PaginationItem>
            <For each={items}>
              {(item) => (
                <PaginationItem>
                  {typeof item === "number" ? (
                    <PaginationLink page={item} />
                  ) : (
                    <PaginationEllipsis />
                  )}
                </PaginationItem>
              )}
            </For>
            <PaginationItem>
              <PaginationNext>Next</PaginationNext>
            </PaginationItem>
          </>
        )}
      </PaginationList>
    </Pagination>
  )
}

export { PageNavigation }
```

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

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

```tsx title="total.tsx"
import {
  Pagination,
  PaginationEllipsis,
  PaginationItem,
  PaginationLink,
  PaginationList,
  PaginationNext,
  PaginationPrevious,
} from "@ui-sdk/solid/pagination"
import { createSignal, For } from "solid-js"
import { useLog } from "./log"

function Example() {
  const log = useLog()
  const [page, setPage] = createSignal(2)
  const [pageSize, setPageSize] = createSignal(20)
  const total = 95

  return (
    <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={(event) => {
              setPageSize(Number(event.currentTarget.value))
              setPage(1)
              log(`${event.currentTarget.value} rows per page`)
            }}
          >
            <option value={10}>10</option>
            <option value={20}>20</option>
            <option value={50}>50</option>
          </select>
        </label>
      </div>
      <Pagination
        aria-label="Pagination"
        total={total}
        pageSize={pageSize()}
        page={page()}
        onPageChange={(next) => {
          setPage(next)
          log(`Page ${next}`)
        }}
      >
        <PaginationList>
          {({ items }) => (
            <>
              <PaginationItem>
                <PaginationPrevious data-variant="ghost">
                  <svg
                    viewBox="0 0 24 24"
                    fill="none"
                    stroke="currentColor"
                    stroke-width="2"
                    stroke-linecap="round"
                    stroke-linejoin="round"
                    aria-hidden="true"
                  >
                    <path d="m15 18-6-6 6-6" />
                  </svg>
                  <span data-slot="visually-hidden">Previous</span>
                </PaginationPrevious>
              </PaginationItem>
              <For each={items}>
                {(item) => (
                  <PaginationItem>
                    {typeof item === "number" ? (
                      <PaginationLink data-variant="ghost" page={item} />
                    ) : (
                      <PaginationEllipsis>
                        <svg
                          viewBox="0 0 24 24"
                          fill="none"
                          stroke="currentColor"
                          stroke-width="2"
                          stroke-linecap="round"
                          stroke-linejoin="round"
                          aria-hidden="true"
                        >
                          <circle cx="12" cy="12" r="1" />
                          <circle cx="19" cy="12" r="1" />
                          <circle cx="5" cy="12" r="1" />
                        </svg>
                      </PaginationEllipsis>
                    )}
                  </PaginationItem>
                )}
              </For>
              <PaginationItem>
                <PaginationNext data-variant="ghost">
                  <span data-slot="visually-hidden">Next</span>
                  <svg
                    viewBox="0 0 24 24"
                    fill="none"
                    stroke="currentColor"
                    stroke-width="2"
                    stroke-linecap="round"
                    stroke-linejoin="round"
                    aria-hidden="true"
                  >
                    <path d="m9 18 6-6-6-6" />
                  </svg>
                </PaginationNext>
              </PaginationItem>
            </>
          )}
        </PaginationList>
      </Pagination>
    </div>
  )
}

export { Example }
```

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

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

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

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

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

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

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

## 路由器链接
在客户端渲染你的路由器链接来翻页。把它传给 `render`，比如 `render={(props) => <A {...props} />}`；它会收到部件的 props，以及来自 [`getHref`](https://ui-sdk.cn/docs/solid/components/pagination#links) 的 `href`。分页的点击处理函数先运行：当变更被取消或步进位于端点时，它会调用 `preventDefault()`，路由器就不再处理这个链接。

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

```tsx
const [searchParams] = useSearchParams()
const page = () => Number(searchParams.page ?? 1)

<Pagination aria-label="Pagination" pageCount={10} page={page()} getHref={(page) => `?page=${page}`}>
  <PaginationList>
    {({ items }) => (
      <For each={items}>
        {(item) => (
          <PaginationItem>
            {typeof item === "number" ? (
              <PaginationLink page={item} render={(props) => <A {...props} />} />
            ) : (
              <PaginationEllipsis />
            )}
          </PaginationItem>
        )}
      </For>
    )}
  </PaginationList>
</Pagination>
```

## 受控
传入 `page` 和 `onPageChange` 来控制分页。

```tsx
const [page, setPage] = createSignal(1)

<Pagination aria-label="Pagination" pageCount={10} page={page()} onPageChange={(next) => setPage(next)}>
  ...
</Pagination>
```

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

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

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

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

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

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

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

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

```tsx
const pagination = createPaginationController()

<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` 导入它。这里它让一排幻灯片圆点无论有多少张幻灯片都保持同样的长度。

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

const items = () => paginationRange({ page: slide(), pageCount: 20, siblings: 2, boundaries: 1 })

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

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

```tsx title="render.tsx"
import {
  Pagination,
  PaginationEllipsis,
  PaginationItem,
  PaginationLink,
  PaginationList,
  PaginationNext,
  PaginationPrevious,
} from "@ui-sdk/solid/pagination"
import { For } from "solid-js"

function Example() {
  return (
    <Pagination aria-label="Pagination" pageCount={10}>
      <PaginationList>
        {({ items }) => (
          <>
            <PaginationItem>
              <PaginationPrevious
                aria-label="Previous page"
                render={(props, state) => (
                  <button
                    {...props}
                    title={
                      state.disabled ? undefined : `Go to page ${state.page}`
                    }
                  />
                )}
              >
                {(state) => (
                  <>
                    <svg
                      viewBox="0 0 24 24"
                      fill="none"
                      stroke="currentColor"
                      stroke-width="2"
                      stroke-linecap="round"
                      stroke-linejoin="round"
                      aria-hidden="true"
                    >
                      <path d="m12 19-7-7 7-7" />
                      <path d="M19 12H5" />
                    </svg>
                    {!state.disabled && (
                      <span aria-hidden="true">{state.page}</span>
                    )}
                  </>
                )}
              </PaginationPrevious>
            </PaginationItem>
            <For each={items}>
              {(item) => (
                <PaginationItem>
                  {typeof item === "number" ? (
                    <PaginationLink page={item}>
                      {(state) =>
                        state.current ? `Page ${state.page}` : state.page
                      }
                    </PaginationLink>
                  ) : (
                    <PaginationEllipsis />
                  )}
                </PaginationItem>
              )}
            </For>
            <PaginationItem>
              <PaginationNext
                aria-label="Next page"
                render={(props, state) => (
                  <button
                    {...props}
                    title={
                      state.disabled ? undefined : `Go to page ${state.page}`
                    }
                  />
                )}
              >
                {(state) => (
                  <>
                    {!state.disabled && (
                      <span aria-hidden="true">{state.page}</span>
                    )}
                    <svg
                      viewBox="0 0 24 24"
                      fill="none"
                      stroke="currentColor"
                      stroke-width="2"
                      stroke-linecap="round"
                      stroke-linejoin="round"
                      aria-hidden="true"
                    >
                      <path d="M5 12h14" />
                      <path d="m12 5 7 7-7 7" />
                    </svg>
                  </>
                )}
              </PaginationNext>
            </PaginationItem>
          </>
        )}
      </PaginationList>
    </Pagination>
  )
}

export { Example }
```

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

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

每个部件都有一个 `data-slot`，比如 `pagination-link`，它的状态属性列在[数据属性](https://ui-sdk.cn/docs/solid/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 参考
属性和回调与下面相同，都作为 Solid props。

### 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。

### 状态
渲染函数、基于状态的类名和槽位按部件分别收到什么。

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

### 事件
回调先收到新的页码，再收到详情。

| Prop           | 所属部件     | 收到                                              |
| -------------- | ------------ | ------------------------------------------------- |
| `onPageChange` | `Pagination` | `(page, details)`：新的页码，以及[原因](https://ui-sdk.cn/docs/solid/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.
