# Carousel

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

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

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

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

<Carousel aria-label="Featured">
  <div data-slot="row">
    <CarouselPrevious aria-label="Previous slide">
      <ChevronLeftIcon />
    </CarouselPrevious>
    <CarouselViewport>
      <CarouselContent>
        {#each slides as slide (slide)}
          <CarouselItem>
            <div data-slot="tile">{slide}</div>
          </CarouselItem>
        {/each}
      </CarouselContent>
    </CarouselViewport>
    <CarouselNext aria-label="Next slide">
      <ChevronRightIcon />
    </CarouselNext>
  </div>
</Carousel>
```

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

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

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

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

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

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

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

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

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

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

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

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

<Carousel aria-label="Featured" orientation="vertical">
  <CarouselViewport>
    <CarouselContent>
      {#each slides as slide (slide)}
        <CarouselItem>
          <div data-slot="tile">
            {slide}
          </div>
        </CarouselItem>
      {/each}
    </CarouselContent>
  </CarouselViewport>
  <div data-slot="row">
    <CarouselPrevious aria-label="Previous slide">
      <ChevronUpIcon />
    </CarouselPrevious>
    <CarouselNext aria-label="Next slide">
      <ChevronDownIcon />
    </CarouselNext>
  </div>
</Carousel>
```

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

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

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

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

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

<Carousel aria-label="Featured" loop>
  <div data-slot="row">
    <CarouselPrevious aria-label="Previous slide">
      <ChevronLeftIcon />
    </CarouselPrevious>
    <CarouselViewport>
      <CarouselContent>
        {#each slides as slide (slide)}
          <CarouselItem>
            <div data-slot="tile">{slide}</div>
          </CarouselItem>
        {/each}
      </CarouselContent>
    </CarouselViewport>
    <CarouselNext aria-label="Next slide">
      <ChevronRightIcon />
    </CarouselNext>
  </div>
</Carousel>
```

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

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

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

  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" },
  ]

  let align = $state<Align>("center")
</script>

<div data-slot="stack">
  <div data-slot="controls">
    <Select
      items={alignments}
      value={align}
      onValueChange={(next) => next && (align = next as Align)}
    >
      <SelectLabel>Align</SelectLabel>
      <SelectTrigger>
        <SelectValue />
        <ChevronDownIcon />
      </SelectTrigger>
      <SelectContent>
        {#each alignments as option (option.value)}
          <SelectItem value={option.value}>
            {option.label}
            <SelectItemIndicator>
              <CheckIcon />
            </SelectItemIndicator>
          </SelectItem>
        {/each}
      </SelectContent>
    </Select>
  </div>
  <Carousel aria-label="Photos" {align} defaultPage={2}>
    <div data-slot="row">
      <CarouselPrevious aria-label="Previous slide">
        <ChevronLeftIcon />
      </CarouselPrevious>
      <CarouselViewport>
        <CarouselContent>
          {#each photos as photo (photo.name)}
            <CarouselItem>
              <div data-slot="tile">{photo.name}</div>
            </CarouselItem>
          {/each}
        </CarouselContent>
      </CarouselViewport>
      <CarouselNext aria-label="Next slide">
        <ChevronRightIcon />
      </CarouselNext>
    </div>
  </Carousel>
</div>
```

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

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

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

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

<Carousel aria-label="Featured" defaultPage={3}>
  <div data-slot="row">
    <CarouselPrevious aria-label="Previous slide">
      <ChevronLeftIcon />
    </CarouselPrevious>
    <CarouselViewport>
      <CarouselContent>
        {#each slides as slide (slide)}
          <CarouselItem>
            <div data-slot="tile">{slide}</div>
          </CarouselItem>
        {/each}
      </CarouselContent>
    </CarouselViewport>
    <CarouselNext aria-label="Next slide">
      <ChevronRightIcon />
    </CarouselNext>
  </div>
</Carousel>
```

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

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

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

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

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

<Carousel aria-label="Photos">
  <CarouselViewport>
    <CarouselContent>
      {#each photos as photo (photo.name)}
        <CarouselItem>
          <div data-slot="tile">
            {photo.name}
          </div>
        </CarouselItem>
      {/each}
    </CarouselContent>
  </CarouselViewport>
  <CarouselIndicatorGroup aria-label="Choose a photo">
    {#each photos as photo, index (photo.name)}
      <CarouselIndicator page={index + 1} aria-label={photo.name} />
    {/each}
  </CarouselIndicatorGroup>
</Carousel>
```

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

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

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

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

<Carousel aria-label="Products" slidesPerPage={3}>
  <div data-slot="row">
    <CarouselPrevious aria-label="Previous page">
      <ChevronLeftIcon />
    </CarouselPrevious>
    <CarouselViewport>
      <CarouselContent>
        {#each products as product (product)}
          <CarouselItem>
            <div data-slot="tile">{product}</div>
          </CarouselItem>
        {/each}
      </CarouselContent>
    </CarouselViewport>
    <CarouselNext aria-label="Next page">
      <ChevronRightIcon />
    </CarouselNext>
  </div>
  <div data-slot="row">
    <CarouselIndicatorGroup aria-label="Choose a page">
      {#snippet children(state)}
        {#each { length: state.pageCount ?? 3 }, index (index)}
          <CarouselIndicator
            page={index + 1}
            aria-label={`Page ${index + 1}`}
          />
        {/each}
      {/snippet}
    </CarouselIndicatorGroup>
  </div>
</Carousel>
```

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

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

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

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

  let page = $state(1)
  let block: HTMLElement | undefined = $state()
  const follow = (next: number) =>
    block
      ?.querySelectorAll("button")
      [next - 1]?.scrollIntoView({ block: "nearest", inline: "nearest" })
</script>

<div data-slot="stack" bind:this={block}>
  <Carousel bind:page aria-label="Photos" onPageChange={follow}>
    <CarouselViewport>
      <CarouselContent>
        {#each photos as photo (photo.name)}
          <CarouselItem>
            <div data-slot="tile">
              {photo.name}
            </div>
          </CarouselItem>
        {/each}
      </CarouselContent>
    </CarouselViewport>
  </Carousel>
  <Carousel aria-label="Thumbnails" dragFree slidesPerPage="auto">
    <CarouselViewport>
      <CarouselContent>
        {#each photos as photo, index (photo.name)}
          <CarouselItem aria-label={photo.name}>
            <button
              type="button"
              aria-pressed={page === index + 1}
              onclick={() => (page = index + 1)}
            >
              {photo.name}
            </button>
          </CarouselItem>
        {/each}
      </CarouselContent>
    </CarouselViewport>
  </Carousel>
</div>
```

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

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

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

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

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

  const log = useLog()

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

<Carousel
  aria-label="Photos"
  defaultPlaying
  interval={4000}
  onPlayingChange={(playing, details) =>
    log(`${playing ? "Playing" : "Stopped"} (${details.reason})`)}
>
  <div data-slot="controls">
    <CarouselPlayToggle>
      {#snippet children(state)}
        {state.playing ? "Pause" : "Play"}
      {/snippet}
    </CarouselPlayToggle>
  </div>
  <div data-slot="row">
    <CarouselPrevious aria-label="Previous slide">
      <ChevronLeftIcon />
    </CarouselPrevious>
    <CarouselViewport>
      <CarouselContent>
        {#each photos as photo (photo.name)}
          <CarouselItem>
            <div data-slot="tile">{photo.name}</div>
          </CarouselItem>
        {/each}
      </CarouselContent>
    </CarouselViewport>
    <CarouselNext aria-label="Next slide">
      <ChevronRightIcon />
    </CarouselNext>
  </div>
</Carousel>
```

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

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

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

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

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

  const log = useLog()

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

<Carousel
  aria-label="Featured"
  onPageChangeComplete={(page) => log(`Rested on slide ${page}`)}
>
  <div data-slot="row">
    <CarouselPrevious aria-label="Previous slide">
      <ChevronLeftIcon />
    </CarouselPrevious>
    <CarouselViewport>
      <CarouselContent>
        {#each slides as slide (slide)}
          <CarouselItem>
            <div data-slot="tile">{slide}</div>
          </CarouselItem>
        {/each}
      </CarouselContent>
    </CarouselViewport>
    <CarouselNext aria-label="Next slide">
      <ChevronRightIcon />
    </CarouselNext>
  </div>
  <div data-slot="row">
    <div data-slot="bar">
      <div></div>
    </div>
  </div>
</Carousel>
```

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

## 受控
用 `bind:page` 绑定 `page` 来控制页，从 1 开始。不带 `bind:` 的 `page={x}` 是起始值，在 `x` 变化之前轮播可以改变它。用 `bind:page={x}` 绑定它，让两者保持一致；或者用函数绑定 `bind:page={() => x, (next) => (x = next)}` 来决定。根的 `children` 片段会收到它的状态，其中有 `pageCount`，在幻灯片测量完成之前为 null。

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

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

  const log = useLog()

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

  let page = $state(1)
</script>

<Carousel
  bind:page
  aria-label="Featured"
  onPageChange={(next, details) => log(`Page ${next} (${details.reason})`)}
>
  <div data-slot="row">
    <CarouselPrevious aria-label="Previous slide">
      <ChevronLeftIcon />
    </CarouselPrevious>
    <CarouselViewport>
      <CarouselContent>
        {#each slides as slide (slide)}
          <CarouselItem>
            <div data-slot="tile">{slide}</div>
          </CarouselItem>
        {/each}
      </CarouselContent>
    </CarouselViewport>
    <CarouselNext aria-label="Next slide">
      <ChevronRightIcon />
    </CarouselNext>
  </div>
</Carousel>
```

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

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

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

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

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

  const carousel = createCarouselController()
</script>

<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" onclick={() => carousel.setPage(5)}
      >Show the Last Slide</button
    >
  </div>
  <Carousel aria-label="Featured" controller={carousel} drag={false}>
    <CarouselViewport>
      <CarouselContent>
        {#each slides as slide (slide)}
          <CarouselItem>
            <div data-slot="tile">{slide}</div>
          </CarouselItem>
        {/each}
      </CarouselContent>
    </CarouselViewport>
  </Carousel>
</div>
```

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

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

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

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

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

```svelte
<script lang="ts">
  import { MediaQuery } from "svelte/reactivity"
  import { Carousel } from "@ui-sdk/svelte/carousel"

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

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

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

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

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

  let nextFocused = false
  const rememberFocus = () => {
    nextFocused =
      typeof document !== "undefined" &&
      document.activeElement?.getAttribute("data-slot") === "carousel-next"
  }
  const focusIf = (link: HTMLElement) => {
    if (nextFocused) {
      link.focus()
    }
  }
</script>

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

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

## 样式
在到达两端时给 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/svelte/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 参考
属性与回调与下面相同，都作为 Svelte props。`page` 和 `playing` 可以用 `bind:` 绑定。

### 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.
- `onPageChange?` (`((page: number, details: ChangeDetails<CarouselPageChangeReason>) => void)`): Runs when the page wants to change. `details.reason` says why, and `details.cancel()` stays on the page.
- `onPageChangeComplete?` (`((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.
- `onPlayingChange?` (`((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。

### 状态
每个部件的 `render` 和 `children` 片段会收到什么。

`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` (`TouchEvent | PointerEvent`): 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` (`TouchEvent | PointerEvent`): 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.

### 事件
回调先收到新值，然后收到详情。绑定的 `page` 或 `playing` 只在变更回调没有被取消时更新。

| 属性                   | 所属       | 收到                                          |
| ---------------------- | ---------- | --------------------------------------------- |
| `onPageChange`         | `Carousel` | `(page, details)`：新页，以及[原因](https://ui-sdk.cn/docs/svelte/components/carousel#reasons) |
| `onPageChangeComplete` | `Carousel` | `(page)`：幻灯片停稳时所在的页                |
| `onPlayingChange`      | `Carousel` | `(playing, details)`：是否在轮播，以及原因    |
| `bind:page`            | `Carousel` | 当前页                                        |
| `bind:playing`         | `Carousel` | 是否在轮播                                    |

## 无障碍
它遵循 [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.
