# Carousel

用原生滚动、键盘操作和可选的自动轮播逐页浏览幻灯片。

用 Carousel 一次显示一屏幻灯片，比如产品照片或精选故事。它使用原生滚动，所以滑动和触控板都能用，Previous 和 Next 按钮用来翻页。

```vue title="basic.vue"
<script setup lang="ts">
import { ChevronLeftIcon, ChevronRightIcon } from "@lucide/vue"
import {
  Carousel,
  CarouselContent,
  CarouselItem,
  CarouselNext,
  CarouselPrevious,
  CarouselViewport,
} from "@ui-sdk/vue/carousel"

const slides = [1, 2, 3, 4, 5]
</script>

<template>
  <Carousel aria-label="Featured">
    <div data-slot="row">
      <CarouselPrevious aria-label="Previous slide">
        <ChevronLeftIcon />
      </CarouselPrevious>
      <CarouselViewport>
        <CarouselContent>
          <CarouselItem v-for="slide in slides" :key="slide">
            <div data-slot="tile">{{ slide }}</div>
          </CarouselItem>
        </CarouselContent>
      </CarouselViewport>
      <CarouselNext aria-label="Next slide">
        <ChevronRightIcon />
      </CarouselNext>
    </div>
  </Carousel>
</template>
```

用 Previous 和 Next，滑动幻灯片，或者聚焦视口并使用方向键。

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

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

```text
Carousel
├── CarouselViewport
│   └── CarouselContent
│       ├── CarouselItem
│       └── CarouselItem
├── CarouselPrevious
└── CarouselNext
```

把幻灯片放进视口，然后加上你需要的控件。

视口是滚动的窗口，内容则是里面那一排幻灯片，一个 flex 行（垂直时是列）。用 `aria-label` 给轮播命名，比如“Featured products”；给 Previous、Next、指示器和播放切换按钮提供文字，当它们只放图标时提供 `aria-label`。

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

```vue
<script setup lang="ts">
import {
  Carousel,
  CarouselViewport,
  CarouselContent,
  CarouselItem,
  CarouselPrevious,
  CarouselNext,
} from "@ui-sdk/vue/carousel"
</script>

<template>
  <Carousel aria-label="Featured">
    <CarouselViewport>
      <CarouselContent>
        <CarouselItem>First slide</CarouselItem>
        <CarouselItem>Second slide</CarouselItem>
      </CarouselContent>
    </CarouselViewport>
    <CarouselPrevious>Previous</CarouselPrevious>
    <CarouselNext>Next</CarouselNext>
  </Carousel>
</template>
```

## 垂直
`orientation="vertical"` 让幻灯片上下滚动。给视口一个高度。上下方向键用来翻页，而不是左右方向键。

```vue title="vertical.vue"
<script setup lang="ts">
import { ChevronDownIcon, ChevronUpIcon } from "@lucide/vue"
import {
  Carousel,
  CarouselContent,
  CarouselItem,
  CarouselNext,
  CarouselPrevious,
  CarouselViewport,
} from "@ui-sdk/vue/carousel"

const slides = [1, 2, 3, 4, 5]
</script>

<template>
  <Carousel aria-label="Featured" orientation="vertical">
    <CarouselViewport>
      <CarouselContent>
        <CarouselItem v-for="slide in slides" :key="slide">
          <div data-slot="tile">
            {{ slide }}
          </div>
        </CarouselItem>
      </CarouselContent>
    </CarouselViewport>
    <div data-slot="row">
      <CarouselPrevious aria-label="Previous slide">
        <ChevronUpIcon />
      </CarouselPrevious>
      <CarouselNext aria-label="Next slide">
        <ChevronDownIcon />
      </CarouselNext>
    </div>
  </Carousel>
</template>
```

垂直滚动，或者使用上下的控件。

## 循环
`loop` 让幻灯片首尾相接。在最后一页按 Next 会到第一页，而第一页排在最后一张之后；从第一页往回滑动、拖动或滚轮滚动，会到达最后一页，全程都是原生滚动。自动轮播始终循环。

轮播停稳时，幻灯片用 CSS `order` 轮流出现在内容的两端，所以当前页的两侧始终都有幻灯片。它们在文档里保持原来的位置，所以屏幕阅读器和 Tab 都按幻灯片自身的顺序移动。内容需要像 flex 和 grid 那样，把幻灯片排成一行并保持均匀的间隔，还要在当前页两侧各放一页幻灯片。数量不够时，比如一次一屏只有两张幻灯片，最后一页的 Next 会改为滚回第一页。要移动一张卡片，比如让它在离开时滑走，请变换幻灯片内部的元素，而不是幻灯片本身，并给幻灯片设置 `overflow: clip`。浏览器测量幻灯片滚动了多远时，会把任何越过幻灯片的东西计算在内，循环就会在错误的位置绕回。

```vue title="loop.vue"
<script setup lang="ts">
import { ChevronLeftIcon, ChevronRightIcon } from "@lucide/vue"
import {
  Carousel,
  CarouselContent,
  CarouselItem,
  CarouselNext,
  CarouselPrevious,
  CarouselViewport,
} from "@ui-sdk/vue/carousel"

const slides = [1, 2, 3, 4, 5]
</script>

<template>
  <Carousel aria-label="Featured" loop>
    <div data-slot="row">
      <CarouselPrevious aria-label="Previous slide">
        <ChevronLeftIcon />
      </CarouselPrevious>
      <CarouselViewport>
        <CarouselContent>
          <CarouselItem v-for="slide in slides" :key="slide">
            <div data-slot="tile">{{ slide }}</div>
          </CarouselItem>
        </CarouselContent>
      </CarouselViewport>
      <CarouselNext aria-label="Next slide">
        <ChevronRightIcon />
      </CarouselNext>
    </div>
  </Carousel>
</template>
```

一直向前或向后移动，幻灯片会绕回另一端。

## 对齐
`align` 让页面对齐到视口的 `start`（默认）、`center` 或 `end`。居中时，比视口窄的幻灯片会让相邻的幻灯片露出来。第一页和最后一页留在内容的两端，所以第一张幻灯片前面没有空白。

```vue title="align.vue"
<script setup lang="ts">
import {
  CheckIcon,
  ChevronDownIcon,
  ChevronLeftIcon,
  ChevronRightIcon,
} from "@lucide/vue"
import {
  Carousel,
  CarouselContent,
  CarouselItem,
  CarouselNext,
  CarouselPrevious,
  CarouselViewport,
} from "@ui-sdk/vue/carousel"
import {
  Select,
  SelectContent,
  SelectItem,
  SelectItemIndicator,
  SelectLabel,
  SelectTrigger,
  SelectValue,
} from "@ui-sdk/vue/select"
import { ref } from "vue"

type Align = "start" | "center" | "end"

const photos = [
  { name: "Dunes" },
  { name: "Forest" },
  { name: "Glacier" },
  { name: "Canyon" },
  { name: "Meadow" },
  { name: "Harbor" },
]
const alignments = [
  { value: "start", label: "Start" },
  { value: "center", label: "Center" },
  { value: "end", label: "End" },
]

const align = ref<Align>("center")
</script>

<template>
  <div data-slot="stack">
    <div data-slot="controls">
      <Select
        :items="alignments"
        :value="align"
        @value-change="(next) => next && (align = next as Align)"
      >
        <SelectLabel>Align</SelectLabel>
        <SelectTrigger>
          <SelectValue />
          <ChevronDownIcon />
        </SelectTrigger>
        <SelectContent>
          <SelectItem
            v-for="option in alignments"
            :key="option.value"
            :value="option.value"
          >
            {{ option.label }}
            <SelectItemIndicator>
              <CheckIcon />
            </SelectItemIndicator>
          </SelectItem>
        </SelectContent>
      </Select>
    </div>
    <Carousel aria-label="Photos" :align="align" :default-page="2">
      <div data-slot="row">
        <CarouselPrevious aria-label="Previous slide">
          <ChevronLeftIcon />
        </CarouselPrevious>
        <CarouselViewport>
          <CarouselContent>
            <CarouselItem v-for="photo in photos" :key="photo.name">
              <div data-slot="tile">{{ photo.name }}</div>
            </CarouselItem>
          </CarouselContent>
        </CarouselViewport>
        <CarouselNext aria-label="Next slide">
          <ChevronRightIcon />
        </CarouselNext>
      </div>
    </Carousel>
  </div>
</template>
```

选择 Start、Center 或 End，然后翻页。居中时，两侧都会露出相邻的幻灯片。

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

```vue title="default-page.vue"
<script setup lang="ts">
import { ChevronLeftIcon, ChevronRightIcon } from "@lucide/vue"
import {
  Carousel,
  CarouselContent,
  CarouselItem,
  CarouselNext,
  CarouselPrevious,
  CarouselViewport,
} from "@ui-sdk/vue/carousel"

const slides = [1, 2, 3, 4, 5]
</script>

<template>
  <Carousel aria-label="Featured" :default-page="3">
    <div data-slot="row">
      <CarouselPrevious aria-label="Previous slide">
        <ChevronLeftIcon />
      </CarouselPrevious>
      <CarouselViewport>
        <CarouselContent>
          <CarouselItem v-for="slide in slides" :key="slide">
            <div data-slot="tile">{{ slide }}</div>
          </CarouselItem>
        </CarouselContent>
      </CarouselViewport>
      <CarouselNext aria-label="Next slide">
        <ChevronRightIcon />
      </CarouselNext>
    </div>
  </Carousel>
</template>
```

从选中的页开始，然后向前或向后移动。

## 指示器
指示器是一个选项卡列表：当前页只有一个 Tab 停靠点，方向键在它们之间移动并显示对应的页，Home 和 End 跳到两端。每个指示器控制它那一页的幻灯片。

每张幻灯片写一个。超出页数的指示器会隐藏自己，所以同一份标记在任意数量的幻灯片下都能用。指示器的 `page` 从它们的顺序推断；传入它，才能在服务端渲染出选中的那个。

```vue title="indicators.vue"
<script setup lang="ts">
import {
  Carousel,
  CarouselContent,
  CarouselIndicator,
  CarouselIndicatorGroup,
  CarouselItem,
  CarouselViewport,
} from "@ui-sdk/vue/carousel"

const photos = [
  { name: "Dunes" },
  { name: "Forest" },
  { name: "Glacier" },
  { name: "Canyon" },
  { name: "Meadow" },
  { name: "Harbor" },
]
</script>

<template>
  <Carousel aria-label="Photos">
    <CarouselViewport>
      <CarouselContent>
        <CarouselItem v-for="photo in photos" :key="photo.name">
          <div data-slot="tile">
            {{ photo.name }}
          </div>
        </CarouselItem>
      </CarouselContent>
    </CarouselViewport>
    <CarouselIndicatorGroup aria-label="Choose a photo">
      <CarouselIndicator
        v-for="(photo, index) in photos"
        :key="photo.name"
        :page="index + 1"
        :aria-label="photo.name"
      />
    </CarouselIndicatorGroup>
  </Carousel>
</template>
```

选择一个带名称的指示器，然后用方向键、Home 和 End 在它们之间移动。

## 页
`slides-per-page` 是一页放多少张幻灯片：Next 每次移动这么多，每个指示器也代表这么多。`"auto"` 按能显示的数量来放。无法从起始位置排满的页，比如最后几张幻灯片，会并入最后一页。在显示三张幻灯片的情况下，五张幻灯片按每页一张算有三页，按每页三张算有两页。

```vue title="pages.vue"
<script setup lang="ts">
import { ChevronLeftIcon, ChevronRightIcon } from "@lucide/vue"
import {
  Carousel,
  CarouselContent,
  CarouselIndicator,
  CarouselIndicatorGroup,
  CarouselItem,
  CarouselNext,
  CarouselPrevious,
  CarouselViewport,
} from "@ui-sdk/vue/carousel"

const products = [1, 2, 3, 4, 5, 6, 7, 8]
</script>

<template>
  <Carousel aria-label="Products" :slides-per-page="3">
    <div data-slot="row">
      <CarouselPrevious aria-label="Previous page">
        <ChevronLeftIcon />
      </CarouselPrevious>
      <CarouselViewport>
        <CarouselContent>
          <CarouselItem v-for="product in products" :key="product">
            <div data-slot="tile">{{ product }}</div>
          </CarouselItem>
        </CarouselContent>
      </CarouselViewport>
      <CarouselNext aria-label="Next page">
        <ChevronRightIcon />
      </CarouselNext>
    </div>
    <div data-slot="row">
      <CarouselIndicatorGroup v-slot="{ state }" aria-label="Choose a page">
        <CarouselIndicator
          v-for="index in state.pageCount ?? 3"
          :key="index"
          :page="index"
          :aria-label="`Page ${index}`"
        />
      </CarouselIndicatorGroup>
    </div>
  </Carousel>
</template>
```

用翻页控件在多组幻灯片之间移动。

## 缩略图
图库和一条缩略图带共享选中的页。缩略图轮播用 `drag-free` 自由滚动，按能显示的数量来放。按压缩略图会选中它的幻灯片。

```vue title="thumbnails.vue"
<script setup lang="ts">
import {
  Carousel,
  CarouselContent,
  CarouselItem,
  CarouselViewport,
} from "@ui-sdk/vue/carousel"
import { ref, useTemplateRef, watch } from "vue"

const photos = [
  { name: "Dunes" },
  { name: "Forest" },
  { name: "Glacier" },
  { name: "Canyon" },
  { name: "Meadow" },
  { name: "Harbor" },
]

const page = ref(1)
const strip = useTemplateRef<{ $el: HTMLElement }>("strip")
watch(page, (next) =>
  strip.value?.$el
    .querySelectorAll("button")
    [next - 1]?.scrollIntoView({ block: "nearest", inline: "nearest" })
)
</script>

<template>
  <div data-slot="stack">
    <Carousel v-model:page="page" aria-label="Photos">
      <CarouselViewport>
        <CarouselContent>
          <CarouselItem v-for="photo in photos" :key="photo.name">
            <div data-slot="tile">
              {{ photo.name }}
            </div>
          </CarouselItem>
        </CarouselContent>
      </CarouselViewport>
    </Carousel>
    <Carousel
      ref="strip"
      aria-label="Thumbnails"
      drag-free
      slides-per-page="auto"
    >
      <CarouselViewport>
        <CarouselContent>
          <CarouselItem
            v-for="(photo, index) in photos"
            :key="photo.name"
            :aria-label="photo.name"
          >
            <button
              type="button"
              :aria-pressed="page === index + 1"
              @click="page = index + 1"
            >
              {{ photo.name }}
            </button>
          </CarouselItem>
        </CarouselContent>
      </CarouselViewport>
    </Carousel>
  </div>
</template>
```

选择一张缩略图来切换图库，或者滚动这两条带中的任意一条。

## 自动轮播
`default-playing` 让轮播开始自动播放，每隔 `interval` 毫秒换一页（默认 5000）。`CarouselPlayToggle` 启动和停止它；用它的 slot 状态里的 `playing` 给它设置名称。

按照轮播模式的要求，键盘焦点移入时轮播停止，在用户要求之前不会重新开始，鼠标悬停时也会暂停。标签页隐藏、轮播滚出视野以及手指按住期间，它同样会暂停。自己切换幻灯片会停止轮播。只有不在轮播时，幻灯片才是礼貌的实时区域（polite live region），所以屏幕阅读器不会每隔几秒被打断。用户偏好减少动态效果时，它不会自行开始。

根上的 `--carousel-interval` 是间隔，暂停期间带有 `data-paused`，所以进度条可以用 CSS 自己计时。

```vue title="autoplay.vue"
<script setup lang="ts">
import { ChevronLeftIcon, ChevronRightIcon } from "@lucide/vue"
import {
  Carousel,
  CarouselContent,
  CarouselItem,
  CarouselNext,
  CarouselPlayToggle,
  CarouselPrevious,
  CarouselViewport,
} from "@ui-sdk/vue/carousel"
import { useLog } from "./log"

const photos = [
  { name: "Dunes" },
  { name: "Forest" },
  { name: "Glacier" },
  { name: "Canyon" },
  { name: "Meadow" },
  { name: "Harbor" },
]

const log = useLog()
</script>

<template>
  <Carousel
    aria-label="Photos"
    default-playing
    :interval="4000"
    @playing-change="
      (playing: boolean, details: { reason: string }) =>
        log(`${playing ? 'Playing' : 'Stopped'} (${details.reason})`)
    "
  >
    <div data-slot="controls">
      <CarouselPlayToggle v-slot="{ state }">{{
        state.playing ? "Pause" : "Play"
      }}</CarouselPlayToggle>
    </div>
    <div data-slot="row">
      <CarouselPrevious aria-label="Previous slide">
        <ChevronLeftIcon />
      </CarouselPrevious>
      <CarouselViewport>
        <CarouselContent>
          <CarouselItem v-for="photo in photos" :key="photo.name">
            <div data-slot="tile">{{ photo.name }}</div>
          </CarouselItem>
        </CarouselContent>
      </CarouselViewport>
      <CarouselNext aria-label="Next slide">
        <ChevronRightIcon />
      </CarouselNext>
    </div>
  </Carousel>
</template>
```

启动或停止轮播。悬停会暂停它，把键盘焦点移入则会停止它。控制台会记录每次变更及其原因。

## 进度
根上的 `--carousel-progress` 表示幻灯片滚动了多远，从第一页的 0 到最后一页的 1，在滚动或弹簧动画的每一帧更新，不会引起重新渲染，所以进度条可以用 CSS 跟随它。启用 `loop` 时，它从 0 走到 1 再回到 0。控制器的 `getProgress()` 读取同一个数字。

每张幻灯片都有自己的 `--carousel-item-progress`，它的页停稳时是 0。幻灯片位于前方一页时，它向 1 上升；位于后方一页时，它向 -1 下降，所以幻灯片可以在进出时用 CSS 淡入淡出、缩放或倾斜。用 `var(--carousel-item-progress, 0)` 读取它，这样首次绘制时也有值。

`@page-change-complete` 在幻灯片停稳到某一页后触发，无论是弹簧动画、拖动还是滚动之后。把会让动画卡顿的工作放在这里，比如加载后面幻灯片的图片。

```vue title="progress.vue"
<script setup lang="ts">
import { ChevronLeftIcon, ChevronRightIcon } from "@lucide/vue"
import {
  Carousel,
  CarouselContent,
  CarouselItem,
  CarouselNext,
  CarouselPrevious,
  CarouselViewport,
} from "@ui-sdk/vue/carousel"
import { useLog } from "./log"

const slides = [1, 2, 3, 4, 5]

const log = useLog()
</script>

<template>
  <Carousel
    aria-label="Featured"
    @page-change-complete="(page: number) => log(`Rested on slide ${page}`)"
  >
    <div data-slot="row">
      <CarouselPrevious aria-label="Previous slide">
        <ChevronLeftIcon />
      </CarouselPrevious>
      <CarouselViewport>
        <CarouselContent>
          <CarouselItem v-for="slide in slides" :key="slide">
            <div data-slot="tile">{{ slide }}</div>
          </CarouselItem>
        </CarouselContent>
      </CarouselViewport>
      <CarouselNext aria-label="Next slide">
        <ChevronRightIcon />
      </CarouselNext>
    </div>
    <div data-slot="row">
      <div data-slot="bar">
        <div />
      </div>
    </div>
  </Carousel>
</template>
```

在幻灯片之间移动。进度条跟随滚动位置，控制台会记录它停稳在哪张幻灯片上。

## 受控
绑定 `v-model:page` 来控制页，从 1 开始，并监听 `@page-change` 获取原因。根的 slot 状态里有 `pageCount`，在幻灯片测量完成之前为 null。

每次变更都带一个[原因](https://ui-sdk.cn/docs/vue/components/carousel#reasons)：`next-press` 和 `previous-press` 来自这些部件，`item-press` 来自指示器或露出的幻灯片，`list-navigation` 来自方向键，`swipe` 来自手指或鼠标拖动，`scroll` 来自滚轮或触控板，`timeout` 来自轮播，`imperative` 来自[控制器](https://ui-sdk.cn/docs/vue/components/carousel#controller)。调用 `details.cancel()` 留在当前页：滑动或拖动会弹回。受控的页没有变化时，也会滚回原处。

```vue title="controlled.vue"
<script setup lang="ts">
import { ChevronLeftIcon, ChevronRightIcon } from "@lucide/vue"
import {
  Carousel,
  CarouselContent,
  CarouselItem,
  CarouselNext,
  CarouselPrevious,
  CarouselViewport,
} from "@ui-sdk/vue/carousel"
import { ref } from "vue"
import { useLog } from "./log"

const slides = [1, 2, 3, 4, 5]

const page = ref(1)
const log = useLog()
</script>

<template>
  <Carousel
    v-model:page="page"
    aria-label="Featured"
    @page-change="
      (next: number, details: { reason: string }) =>
        log(`Page ${next} (${details.reason})`)
    "
  >
    <div data-slot="row">
      <CarouselPrevious aria-label="Previous slide">
        <ChevronLeftIcon />
      </CarouselPrevious>
      <CarouselViewport>
        <CarouselContent>
          <CarouselItem v-for="slide in slides" :key="slide">
            <div data-slot="tile">{{ slide }}</div>
          </CarouselItem>
        </CarouselContent>
      </CarouselViewport>
      <CarouselNext aria-label="Next slide">
        <ChevronRightIcon />
      </CarouselNext>
    </div>
  </Carousel>
</template>
```

切换页。控制台会记录每一页以及变更的原因。

## 从任何地方翻页
来自 `createCarouselController()` 的[控制器](https://ui-sdk.cn/docs/vue/components/carousel#controller)可以从任何地方给轮播翻页。把它作为 `controller` 传给轮播，以及放在它外面的 `CarouselPrevious`、`CarouselNext`、`CarouselIndicatorGroup` 或 `CarouselPlayToggle`，比如放在区块标题里。

`:drag="false"` 关闭滑动和拖动，所以只有部件、按键和控制器能移动它。

```vue title="controller.vue"
<script setup lang="ts">
import { ChevronLeftIcon, ChevronRightIcon } from "@lucide/vue"
import {
  Carousel,
  CarouselContent,
  CarouselItem,
  CarouselNext,
  CarouselPrevious,
  CarouselViewport,
  createCarouselController,
} from "@ui-sdk/vue/carousel"

const slides = [1, 2, 3, 4, 5]

const carousel = createCarouselController()
</script>

<template>
  <div data-slot="stack">
    <div data-slot="controls">
      <CarouselPrevious :controller="carousel" aria-label="Previous slide">
        <ChevronLeftIcon />
      </CarouselPrevious>
      <CarouselNext :controller="carousel" aria-label="Next slide">
        <ChevronRightIcon />
      </CarouselNext>
      <button type="button" @click="carousel.setPage(5)">
        Show the Last Slide
      </button>
    </div>
    <Carousel aria-label="Featured" :controller="carousel" :drag="false">
      <CarouselViewport>
        <CarouselContent>
          <CarouselItem v-for="slide in slides" :key="slide">
            <div data-slot="tile">{{ slide }}</div>
          </CarouselItem>
        </CarouselContent>
      </CarouselViewport>
    </Carousel>
  </div>
</template>
```

用轮播外面的控件切换它的页。

## 滑动与拖动
触摸、触控板和滚轮以原生方式滚动视口，翻页由 CSS 滚动吸附完成。原生滚动和吸附在 JavaScript 加载之前也能工作。鼠标或触控笔也可以拖动幻灯片：它们跟随指针，越过两端时被拉伸，然后按松开时的速度弹到一次快速甩动会到达的页。真正移动过的拖动不会点击它起始位置上的链接，幻灯片里的字段仍然接收指针事件。按压边缘露出的幻灯片会翻到它那一页。

没有设置 `skip-snaps` 时，一次滑动最多移动一页。`drag-free` 让滑动一路滑到停下为止，最近的页成为当前页。

按钮、按键、指示器、轮播和控制器会让滚动位置产生动画。在移动过程中再次按压会更新目标位置。减少动态效果会让这些变更立即生效。

## 关闭轮播
`disabled` 暂时关掉轮播，比如在宽屏上，同样的幻灯片会排成网格。各部件会去掉自己的角色、幻灯片名称和内联样式，每张幻灯片仍然可以到达，视口不再响应按键和滑动翻页，Previous、Next、指示器和播放切换按钮都会隐藏。重新打开后，它会再次测量幻灯片并显示当前页。

```vue
<script setup lang="ts">
import { useMediaQuery } from "@vueuse/core"
import { Carousel } from "@ui-sdk/vue/carousel"

const isWide = useMediaQuery("(min-width: 768px)")
</script>

<template>
  <Carousel aria-label="Featured products" :disabled="isWide">
    <!-- Viewport, slides and controls. -->
  </Carousel>
</template>
```

## 自定义渲染
每个部件都接受一个 `render` 插槽，它接收要绑定的 props 和部件的状态，默认插槽也会收到状态：幻灯片的 `index`、`active` 和 `inView`，翻页按钮的 `disabled`，指示器的 `page` 和 `selected`，播放切换按钮的 `playing` 和 `paused`。

```vue title="render.vue"
<script setup lang="ts">
import { ChevronLeftIcon, ChevronRightIcon } from "@lucide/vue"
import {
  Carousel,
  CarouselContent,
  CarouselItem,
  CarouselNext,
  CarouselPrevious,
  CarouselViewport,
} from "@ui-sdk/vue/carousel"

const photos = [
  { name: "Dunes" },
  { name: "Forest" },
  { name: "Glacier" },
  { name: "Canyon" },
  { name: "Meadow" },
  { name: "Harbor" },
]

const nextFocused = () =>
  typeof document !== "undefined" &&
  document.activeElement?.getAttribute("data-slot") === "carousel-next"
const focusIf = (focus: boolean) => (link: unknown) => {
  if (focus) {
    ;(link as HTMLElement | null)?.focus()
  }
}
</script>

<template>
  <Carousel aria-label="Photos">
    <CarouselViewport>
      <CarouselContent>
        <CarouselItem
          v-for="photo in photos"
          :key="photo.name"
          v-slot="{ state }"
        >
          <div data-slot="tile">
            {{ photo.name }}
            <span data-slot="hint">
              {{ state.index + 1 }} / {{ photos.length
              }}{{ state.active ? " · showing" : "" }}
            </span>
          </div>
        </CarouselItem>
      </CarouselContent>
    </CarouselViewport>
    <div data-slot="row">
      <CarouselPrevious>
        <ChevronLeftIcon />
        Previous
      </CarouselPrevious>
      <CarouselNext>
        <template #render="{ props, state }">
          <a
            v-if="state.disabled"
            :ref="focusIf(nextFocused())"
            href="https://example.com/gallery"
            >See all photos</a
          >
          <button v-else v-bind="props">
            Next
            <ChevronRightIcon />
          </button>
        </template>
      </CarouselNext>
    </div>
  </Carousel>
</template>
```

切换幻灯片，看看每张幻灯片和控件如何描述自己的当前状态。

## 样式
在到达两端时给 Previous 和 Next 用 `data-disabled`，给当前指示器用 `data-selected`，给当前页的幻灯片用 `data-active`，给视野中的幻灯片用 `data-in-view`，并给根用 `data-playing` 和 `data-paused`。

幻灯片自己决定尺寸：一次显示一张时给它 100% 的 `flex-basis`，显示三张时给三分之一，并把间隔放在内容上，从每个 basis 里扣除。视口会以内联样式写入滚动所需的少数几项：它的 overflow、`scroll-snap-type` 和 `overscroll-behavior`。幻灯片会得到 `flex-shrink: 0` 和它的吸附对齐。内容是 flex 行，垂直时是列。要改为把幻灯片排成网格，在它上面设置 `--carousel-display: grid`。如果愿意，可以用 `scrollbar-width: none` 隐藏滚动条。

每个部件都有一个 `data-slot`，比如 `carousel-item`，它的状态属性列在[数据属性](https://ui-sdk.cn/docs/vue/components/carousel#data-attributes)下。

### Carousel
- `--carousel-interval`: How long each page shows while rotating, like `500ms`. Time a progress bar's animation with it.
- `--carousel-progress`: How far the slides have scrolled, from 0 at the first page to 1 at the last, or round the loop. It follows every frame of a scroll or spring.

### CarouselContent
- `--carousel-display`: Set it yourself: how the content lays out its slides, like `grid`. Flex by default.

### CarouselItem
- `--carousel-item-progress`: How far the slide is from its page's resting place, from -1 a page behind to 1 a page ahead, and 0 at rest. It follows every frame of a scroll or spring.

## 数据属性
### Carousel
`[data-slot="carousel"]`

- `data-orientation` (`horizontal`, `vertical`): Which way the slides scroll, and which arrow keys page.
- `data-playing`: Present while it rotates on its own.
- `data-paused`: Present while rotation is paused for now: hovered, the tab hidden, scrolled out of view or held. Pause a progress animation with it.

### CarouselViewport
`[data-slot="carousel-viewport"]`

- `data-orientation` (`horizontal`, `vertical`): Which way the slides scroll, and which arrow keys page.
- `data-dragging`: Present while a mouse or pen drags the slides.

### CarouselContent
`[data-slot="carousel-content"]`

- `data-orientation` (`horizontal`, `vertical`): Which way the slides scroll, and which arrow keys page.

### CarouselItem
`[data-slot="carousel-item"]`

- `data-orientation` (`horizontal`, `vertical`): Which way the slides scroll, and which arrow keys page.
- `data-active`: Present on the slides of the current page.
- `data-in-view`: Present on slides at least half in view. Slides without it are inert and hidden from screen readers.

### CarouselPrevious
`[data-slot="carousel-previous"]`

- `data-disabled`: Present on Previous or Next when there's no page that way, beside `aria-disabled`. It stays focusable and does nothing.

### CarouselIndicator
`[data-slot="carousel-indicator"]`

- `data-selected`: Present on the current page's indicator, beside `aria-selected`.

### CarouselPlayToggle
`[data-slot="carousel-play-toggle"]`

- `data-playing`: Present while it rotates on its own.
- `data-paused`: Present while rotation is paused for now: hovered, the tab hidden, scrolled out of view or held. Pause a progress animation with it.

## API 参考
属性与下面相同，回调是事件。

### Carousel
- `page?` (`number`): The current page, from 1. Pass it to control the carousel.
- `defaultPage?` (`number`): The page it starts on, from 1, when uncontrolled.
- `@page-change` (`((page: number, details: ChangeDetails<CarouselPageChangeReason>) => void)`): Runs when the page wants to change. `details.reason` says why, and `details.cancel()` stays on the page.
- `@page-change-complete` (`((page: number) => void)`): Runs once the slides come to rest on a page, after a spring, a drag or a scroll, with that page. Start work there that would stutter the motion.
- `playing?` (`boolean`): Whether it rotates through the pages on its own. Pass it to control rotation.
- `defaultPlaying?` (`boolean`): Whether it starts rotating, when uncontrolled. It doesn't when the user prefers reduced motion; the play toggle still starts it.
- `@playing-change` (`((playing: boolean, details: ChangeDetails<CarouselPlayingChangeReason>) => void)`): Runs when rotation wants to start or stop. Keyboard focus moving in and the user paging stop it, as the carousel pattern asks.
- `interval?` (`number`): How long each page shows while rotating, in ms. Hovering, a hidden tab and scrolling the carousel out of view pause it.
- `orientation?` (`CarouselOrientation`): Which way the slides scroll, and which arrow keys page.
- `align?` (`CarouselAlign`): Where a page lines up in the viewport.
- `slidesPerPage?` (`CarouselSlidesPerPage`): How many slides one page holds: Next moves this many, and each indicator stands for this many. `"auto"` fits as many as the viewport shows.
- `loop?` (`boolean`): Whether the slides go round: Next on the last page goes to the first, which comes in after the last, and a swipe back from the first page reaches the last. With fewer than a page of slides to either side, Next on the last page scrolls back to the first instead.
- `skipSnaps?` (`boolean`): Whether a fast swipe can pass over pages. Without it, one swipe moves one page.
- `dragFree?` (`boolean`): Whether swipes and drags coast to wherever they stop instead of a page. The nearest page becomes the current one.
- `drag?` (`boolean`): Whether swiping, dragging and scrolling move the slides. Without it, only the parts, keys and controllers do.
- `disabled?` (`boolean`): Whether it stops being a carousel for now, like at a breakpoint where the slides lay out as a grid. The parts drop their roles, inline styles and listeners, and the controls hide.
- `controller?` (`object`): Pages the carousel from anywhere. Create one with `createCarouselController()`.
- `debug?` (`boolean`): Logs every state change with its reason to the console, in development builds.

### CarouselViewport
滚动的区域。渲染一个原生滚动和吸附的 `div`，并为方向键接收焦点。

### CarouselContent
容纳幻灯片。渲染一个 `div`，播报进入视野的幻灯片，轮播时除外。

### CarouselItem
一张幻灯片。渲染一个带 group 角色的 `div`，按位置命名，比如“2 of 5”。

### CarouselPrevious
- `controller?` (`object`): The carousel this part drives when it isn't inside one, like buttons in a page header.

### CarouselNext
显示下一页。接受与 `CarouselPrevious` 相同的 props。

### CarouselIndicatorGroup
把指示器分组。渲染一个带 tablist 角色的 `div`。接受与 `CarouselPrevious` 相同的 props。

### CarouselIndicator
- `page?` (`number`): The page it shows and selects, from 1. Inferred from the indicators' order when left out.

### CarouselPlayToggle
启动和停止轮播。渲染一个 `button`。接受与 `CarouselPrevious` 相同的 props。

### 状态
每个部件的渲染函数、基于状态的类名和槽位会收到什么。

`Carousel`:

- `page` (`number`): The current page, from 1.
- `pageCount` (`number | null`): How many pages there are, or null before the slides are measured, like on the server.
- `playing` (`boolean`): Whether it rotates on its own.
- `orientation` (`CarouselOrientation`): Which way the slides scroll.

`CarouselViewport`:

- `orientation` (`CarouselOrientation`): Which way the slides scroll.
- `dragging` (`boolean`): Whether a mouse or pen is dragging the slides.

`CarouselContent`:

- `orientation` (`CarouselOrientation`): Which way the slides scroll.

`CarouselItem`:

- `index` (`number`): The slide's position among the slides, from 0. -1 until it's measured.
- `active` (`boolean`): Whether the slide belongs to the current page.
- `inView` (`boolean`): Whether at least half of the slide shows. Slides out of view are inert.

`CarouselPrevious` and `CarouselNext`:

- `disabled` (`boolean`): Whether there's no page that way, so pressing does nothing. It stays focusable.

`CarouselIndicatorGroup`:

- `page` (`number`): The current page, from 1.
- `pageCount` (`number | null`): How many pages there are, or null before the slides are measured.

`CarouselIndicator`:

- `page` (`number`): The page it stands for, from 1, or 0 before it's known.
- `selected` (`boolean`): Whether its page is the current one.

`CarouselPlayToggle`:

- `playing` (`boolean`): Whether it rotates on its own.
- `paused` (`boolean`): Whether rotation is paused for now: hovered, the tab hidden, scrolled out of view or held.

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

- `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.
- `item-press` (`MouseEvent | KeyboardEvent`): A member of a collection was chosen: a menu item, a tab, a radio or a checkbox item.
- `list-navigation` (`KeyboardEvent`): Arrow, Home or End keys moved the selection, typing picked an item, or Ctrl or ⌘ with A selected every item of a listbox.
- `swipe` (`PointerEvent | TouchEvent`): A swipe gesture: a finger, mouse or pen dragged it.
- `scroll` (`Event | undefined`): The user scrolled a carousel some other way: a wheel, a trackpad, a scrollbar, or the browser bringing focus or a find in page into view.
- `timeout` (`none`): A duration ran out, like a toast's, or a rotating carousel's interval.
- `content-resize` (`none`): The content or the screen changed size, and the drawer's snap point or the carousel's page went away, so it moved to the nearest one.
- `imperative` (`none`): A controller or `api` call.

以及轮播为什么开始或停止。

- `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.
- `item-press` (`MouseEvent | KeyboardEvent`): A member of a collection was chosen: a menu item, a tab, a radio or a checkbox item.
- `list-navigation` (`KeyboardEvent`): Arrow, Home or End keys moved the selection, typing picked an item, or Ctrl or ⌘ with A selected every item of a listbox.
- `swipe` (`PointerEvent | TouchEvent`): A swipe gesture: a finger, mouse or pen dragged it.
- `scroll` (`Event | undefined`): The user scrolled a carousel some other way: a wheel, a trackpad, a scrollbar, or the browser bringing focus or a find in page into view.
- `imperative` (`none`): A controller or `api` call.
- `toggle-press` (`MouseEvent | KeyboardEvent`): A toggle was pressed: a password input's, which shows or hides the password, or a carousel's, which starts or stops rotation.
- `focus-in` (`FocusEvent`): Keyboard focus moved into the component, which stops a rotating carousel, as the carousel pattern asks, or onto a canvas item, which brought it into view, or onto a calendar's day another way, like a screen reader's.

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

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

- `getPage()` (`() => number`): The current page, from 1.
- `getPageCount()` (`() => number | null`): How many pages there are, or null before the carousel has measured its slides.
- `setPage(page, options?)` (`(page: number, options?: CarouselPageOptions | undefined) => boolean`): Goes to a page, from 1, clamped to the pages there are. Returns false when canceled or already there.
- `next(options?)` (`(options?: CarouselPageOptions | undefined) => boolean`): Goes to the next page, or the first one after the last with `loop`. Returns false at the end.
- `previous(options?)` (`(options?: CarouselPageOptions | undefined) => boolean`): Goes to the previous page, or the last one before the first with `loop`. Returns false at the start.
- `canNext()` (`() => boolean`): Whether there's a next page, always with `loop`.
- `canPrevious()` (`() => boolean`): Whether there's a previous page, always with `loop`.
- `getProgress()` (`() => number`): How far the slides have scrolled, from 0 at the first page to 1 at the last, or round the loop. Also `--carousel-progress` on the root.
- `isPlaying()` (`() => boolean`): Whether it rotates on its own.
- `setPlaying(playing, options?)` (`(playing: boolean, options?: CarouselPlayingOptions | undefined) => boolean`): Starts or stops rotation. Returns false when canceled or unchanged.
- `play(options?)` (`(options?: CarouselPlayingOptions | undefined) => boolean`): Starts rotation.
- `pause(options?)` (`(options?: CarouselPlayingOptions | undefined) => boolean`): Stops rotation.

### 事件
事件先收到新值，然后收到详情。`v-model` 只在变更事件没有被取消时更新。

| 绑定                    | 所属       | 收到                                          |
| ----------------------- | ---------- | --------------------------------------------- |
| `v-model:page`          | `Carousel` | 当前页                                        |
| `v-model:playing`       | `Carousel` | 是否在轮播                                    |
| `@page-change`          | `Carousel` | `(page, details)`：新页，以及[原因](https://ui-sdk.cn/docs/vue/components/carousel#reasons) |
| `@page-change-complete` | `Carousel` | `(page)`：幻灯片停稳时所在的页                |
| `@playing-change`       | `Carousel` | `(playing, details)`：是否在轮播，以及原因    |

## 无障碍
它遵循 [WAI-ARIA 轮播模式](https://www.w3.org/WAI/ARIA/apg/patterns/carousel/)：一个描述为轮播的区域，幻灯片是 group，被描述为幻灯片并按位置命名，Previous 和 Next 控制幻灯片，一个轮播控件，指示器是选项卡列表。下面每一行都是一个自动化测试。

每张幻灯片按位置命名，比如“1 of 5”，除非它有自己的 `aria-label`，你也可以用它来翻译名称。露出不到一半的幻灯片是 `inert`，并对屏幕阅读器隐藏，所以 Tab 和虚拟光标只能到达可见的内容。

### 键盘
方向键跟随方向设置，在从右到左（RTL）的文本中会交换左右。

| 按键                                      | 作用                                                                      |
| ----------------------------------------- | ------------------------------------------------------------------------- |
| Tab                                       | 到达播放切换按钮、视野中幻灯片里的链接和控件、Previous、Next 和当前指示器 |
| ArrowRight, ArrowLeft                     | 在视口里，下一页和上一页。垂直时是 ArrowDown 和 ArrowUp                   |
| Home, End                                 | 在视口或指示器里，第一页和最后一页                                        |
| ArrowRight, ArrowLeft, ArrowDown, ArrowUp | 在指示器里，下一个和上一个指示器，并显示它对应的页                        |
| Enter, Space                              | 按压 Previous、Next、指示器或播放切换按钮                                 |

幻灯片里的字段和控件保留自己的方向键：文本字段的光标会移动，轮播保持不动。当方向键从有焦点的幻灯片翻走时，焦点会移到进入视野的那张幻灯片，所以它永远不会留在看不见的东西上。Previous 和 Next 在两端仍然可以聚焦，并带上 `aria-disabled`，所以 Next 到达最后一张幻灯片时，焦点不会掉到页面上。

### 经过测试的行为
**Structure**

- The carousel is a named region described as a carousel.
- Each slide is a group described as a slide.
- The first slide shows first.
- The content lays its slides out as --carousel-display says.

**Previous and next**

- Next shows the next slide.
- Previous shows the previous slide.
- Previous is disabled on the first slide and Next on the last.
- Next on the last slide does nothing.
- Next and Previous are buttons that don't submit a form.

**Keyboard**

- ArrowRight in a slide shows the next slide, and ArrowLeft the previous.
- ArrowLeft on the first slide stays there.

**Pages**

- With three slides to a view, Next moves one slide, and the last page shows the last three.
- Three slides to a page move three at a time.
- Auto pages fit as many slides as show.
- It can start on another page.
- A controller pages it from outside.

**Rest**

- It reports the page once the slides come to rest.

**Loop**

- Next on the last slide shows the first.
- Previous on the first slide shows the last.
- Previous and Next are never disabled.
- Next on the last slide carries on the same way to the first.
- Pressing Next quickly keeps going forward, round past the last slide.
- A loop with too few slides to go round says so in development.
- Next pressed faster than the slides land never scrolls back.
- A mouse drag back from the first slide shows the last.
- With three slides to a view, the last slide shows before the first.
- A vertical carousel drags down from the first slide to the last.

**Dragging**

- Dragging the slides with a mouse shows the next one.
- A short, slow drag settles back on the same slide.
- Dragging back shows the previous slide.
- A drag that starts on a link doesn't follow it.
- Without dragging, a drag moves nothing.

**More**

- A vertical carousel drags up and down.
- Pressing keys with no waits lands on the right slide.
- A fast flick moves one page, not more.
- The current slide stays in view when the slides change size.

Runs in React、Vue 和 web components.

模式之外：

**Focus**

- Next keeps focus when it reaches the last slide.
- Tab reaches only the slides in view.
- Slides out of view are hidden from assistive technology.
- Arrow keys bring the next slide in and move focus to it.
- A text field in a slide keeps its arrow keys.
- Home and End go to the first and last slide.

**Orientation**

- A vertical carousel pages with ArrowDown and ArrowUp.

**Indicators**

- Indicators are a tablist with the current page selected.
- Pressing an indicator shows its page.
- Arrow keys move between indicators and show their page.
- The indicators are one tab stop, on the current page.
- An indicator controls the slides of its page.
- Indicators past the page count hide themselves.

**Changes**

- A change can be canceled.
- A canceled drag springs back.
- Every change says why.
- A horizontal wheel scrolls to the next slide.
- With loop, a wheel back from the first slide scrolls natively to the last.
- --carousel-progress on the root follows the slides, for progress bars in CSS.
- With loop, --carousel-progress goes round, whatever the track's rotation.
- Disabled, it's no carousel until it's turned back on, like at a breakpoint.
- Turned off while a finger is down, it rotates again once it's back on.
- --carousel-item-progress on each slide says how far it is from rest.
- With loop, --carousel-item-progress follows the slides round.
- A press on a slide peeking in at the edge pages to it.
- A press on a control laid over a peeking slide doesn't page.
- With loop, a press on the slide peeking in before the first pages back round to it.
- Next outside the carousel works through its controller.

**Rotation**

- It rotates on its own, past the last slide to the first.
- The play toggle stops and starts rotation, and its name says which.
- Keyboard focus moving in stops rotation, as the pattern asks.
- Hovering pauses rotation, and leaving resumes it.
- Pressing Next stops rotation.
- The slides are a live region only while not rotating.
- It doesn't start rotating when the user prefers reduced motion.
- Reduced motion pages without animating.

**Pages**

- Indicators follow a change in size.

Runs in React、Vue 和 web components.

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

- Announcements while using the carousel with a keyboard.

Runs in React、Vue 和 web components.
