# Autocomplete

输入时给出建议，又不限制能输入的内容。

需要带建议的文本字段时，用 Autocomplete。选中一条建议会把它填进字段，但任何文字都是有效的值。如果值应该是一个选中的选项，改用 [Combobox](/docs/svelte/components/combobox)。

```svelte title="demo.svelte"
<script lang="ts">
  import {
    Autocomplete,
    AutocompleteContent,
    AutocompleteEmpty,
    AutocompleteInput,
    AutocompleteItem,
    AutocompleteLabel,
    AutocompleteList,
  } from "@ui-sdk/svelte/autocomplete"

  const fruits = [
    "Apple",
    "Apricot",
    "Avocado",
    "Banana",
    "Blackberry",
    "Blueberry",
    "Cherry",
    "Grape",
    "Lemon",
    "Mango",
    "Orange",
    "Peach",
    "Pear",
    "Pineapple",
    "Strawberry",
  ]
</script>

<Autocomplete>
  <div data-slot="stack">
    <AutocompleteLabel>Favorite fruit</AutocompleteLabel>
    <AutocompleteInput placeholder="e.g. Mango" />
  </div>
  <AutocompleteContent>
    <AutocompleteEmpty>No fruits found.</AutocompleteEmpty>
    <AutocompleteList>
      {#each fruits as fruit (fruit)}
        <AutocompleteItem value={fruit}>
          {fruit}
        </AutocompleteItem>
      {/each}
    </AutocompleteList>
  </AutocompleteContent>
</Autocomplete>
```

输入 “man”，按 Down Arrow，再按 Enter 填入 Mango。也可以留下不在列表里的文字。

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

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

```text
Autocomplete
├── AutocompleteLabel
├── AutocompleteInput
└── AutocompleteContent
    ├── AutocompleteEmpty
    └── AutocompleteList
        ├── AutocompleteItem
        └── AutocompleteItem
```

给输入框命名，然后把建议放进浮层里的列表。每条建议需要一个唯一的值。

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

```svelte
<script lang="ts">
  import {
    Autocomplete,
    AutocompleteContent,
    AutocompleteInput,
    AutocompleteItem,
    AutocompleteLabel,
    AutocompleteList,
  } from "@ui-sdk/svelte/autocomplete"
</script>

<Autocomplete>
  <AutocompleteLabel>Fruit</AutocompleteLabel>
  <AutocompleteInput placeholder="Type a fruit…" />
  <AutocompleteContent>
    <AutocompleteList>
      <AutocompleteItem value="Apple">Apple</AutocompleteItem>
      <AutocompleteItem value="Banana">Banana</AutocompleteItem>
    </AutocompleteList>
  </AutocompleteContent>
</Autocomplete>
```

## Autocomplete 与 Combobox
两者都会在你输入时过滤列表。区别在于值是什么。

- **Autocomplete**：值就是文字。建议帮助你把它填完，输入的任何内容都有效。用于搜索框、地址或自由输入字段。
- **[Combobox](/docs/svelte/components/combobox)**：值是列表中的一个选项，使用 `multiple` 时则是多个。文字只是查询；未选择就关闭会恢复已选中项的标签文字，表单提交的是值，不是文字。用于国家、负责人或一组标签。

## 自己构建
`@ui-sdk/svelte/autocomplete` 自带一个现成的 Autocomplete。如果你想用自己的名字自己构建，从 `@ui-sdk/core` 的 `autocomplete` 原语（primitive）开始：

```ts title="fruit-search.ts"
import { autocomplete } from "@ui-sdk/core/autocomplete"
import { createParts } from "@ui-sdk/svelte/primitive"

const {
  Root: FruitSearch,
  Label: FruitLabel,
  Input: FruitInput,
  Content: FruitPopup,
  List: FruitList,
  Item: FruitOption,
  Empty: FruitEmpty,
} = createParts(autocomplete, {
  label: "label",
  input: "input",
  content: "div",
  list: "div",
  item: "div",
  empty: "div",
})

export {
  FruitEmpty,
  FruitInput,
  FruitLabel,
  FruitList,
  FruitOption,
  FruitPopup,
  FruitSearch,
}
```

```svelte
<FruitSearch>
  <FruitLabel>Fruit</FruitLabel>
  <FruitInput />
  <FruitPopup>
    <FruitEmpty>No fruits found.</FruitEmpty>
    <FruitList>
      <FruitOption value="Apple">Apple</FruitOption>
      <FruitOption value="Mango">Mango</FruitOption>
    </FruitList>
  </FruitPopup>
</FruitSearch>
```

每个部件都保留它对应的现成部件的行为、状态和数据属性：输入会过滤选项，方向键移动高亮，浮层在顶层打开。更多内容见[渲染](/docs/svelte/rendering)和[自定义部件](/docs/svelte/custom-parts)。

## 禁用
禁用的字段无法聚焦或修改，也不会提交任何内容。只读的字段仍可聚焦并提交它的值，但不会打开或接受修改。键盘导航会跳过禁用的建议，也无法用它填入字段。

```svelte title="disabled.svelte"
<script lang="ts">
  import {
    Autocomplete,
    AutocompleteContent,
    AutocompleteInput,
    AutocompleteItem,
    AutocompleteLabel,
    AutocompleteList,
  } from "@ui-sdk/svelte/autocomplete"

  const fruits = [
    "Apple",
    "Apricot",
    "Avocado",
    "Banana",
    "Blackberry",
    "Blueberry",
    "Cherry",
    "Grape",
    "Lemon",
    "Mango",
    "Orange",
    "Peach",
    "Pear",
    "Pineapple",
    "Strawberry",
  ]
</script>

<div data-slot="stack">
  <Autocomplete disabled defaultValue="Banana">
    <div data-slot="stack">
      <AutocompleteLabel>Disabled</AutocompleteLabel>
      <AutocompleteInput />
    </div>
  </Autocomplete>
  <Autocomplete readOnly defaultValue="Cherry">
    <div data-slot="stack">
      <AutocompleteLabel>Read-only</AutocompleteLabel>
      <AutocompleteInput />
    </div>
  </Autocomplete>
  <Autocomplete>
    <div data-slot="stack">
      <AutocompleteLabel>Some suggestions disabled</AutocompleteLabel>
      <AutocompleteInput placeholder="Type “b”" />
    </div>
    <AutocompleteContent>
      <AutocompleteList>
        {#each fruits as fruit, index (fruit)}
          <AutocompleteItem value={fruit} disabled={index % 3 === 0}>
            {fruit}
          </AutocompleteItem>
        {/each}
      </AutocompleteList>
    </AutocompleteContent>
  </Autocomplete>
</div>
```

试试 Disabled 和 Read-only 两个字段。在 Disabled suggestion 里输入 “b”：方向键会跳过 Banana，按压也不能选中它。

## 清除与触发器
`AutocompleteClear` 清空字段并把焦点还给它。`AutocompleteTrigger` 让人不用输入就能打开建议。给触发器一个名称，描述它会打开什么。

```svelte title="clear.svelte"
<script lang="ts">
  import { ChevronDownIcon, XIcon } from "@lucide/svelte"
  import {
    Autocomplete,
    AutocompleteClear,
    AutocompleteContent,
    AutocompleteEmpty,
    AutocompleteInput,
    AutocompleteItem,
    AutocompleteLabel,
    AutocompleteList,
    AutocompleteTrigger,
  } from "@ui-sdk/svelte/autocomplete"

  const fruits = [
    "Apple",
    "Apricot",
    "Avocado",
    "Banana",
    "Blackberry",
    "Blueberry",
    "Cherry",
    "Grape",
    "Lemon",
    "Mango",
    "Orange",
    "Peach",
    "Pear",
    "Pineapple",
    "Strawberry",
  ]
</script>

<Autocomplete defaultValue="Mango">
  <div data-slot="stack">
    <AutocompleteLabel>Fruit</AutocompleteLabel>
    <div data-slot="row">
      <AutocompleteInput />
      <AutocompleteClear aria-label="Clear">
        <XIcon aria-hidden="true" />
      </AutocompleteClear>
      <AutocompleteTrigger aria-label="Show fruits">
        <ChevronDownIcon aria-hidden="true" />
      </AutocompleteTrigger>
    </div>
  </div>
  <AutocompleteContent>
    <AutocompleteEmpty>No fruits found.</AutocompleteEmpty>
    <AutocompleteList>
      {#each fruits as fruit (fruit)}
        <AutocompleteItem value={fruit}>
          {fruit}
        </AutocompleteItem>
      {/each}
    </AutocompleteList>
  </AutocompleteContent>
</Autocomplete>
```

清除 Mango，然后按 Show fruits 打开建议。字段为空时，清除按钮会消失。

## 聚焦时打开
加上 `openOnFocus`，在输入框获得焦点时就提供建议。在有人输入之前就有有用的选项时，这很合适。

```svelte title="open-on-focus.svelte"
<script lang="ts">
  import {
    Autocomplete,
    AutocompleteContent,
    AutocompleteEmpty,
    AutocompleteGroup,
    AutocompleteGroupLabel,
    AutocompleteInput,
    AutocompleteItem,
    AutocompleteList,
  } from "@ui-sdk/svelte/autocomplete"

  const recent = [
    "react hooks",
    "tailwind grid",
    "web components",
    "vue v-model",
  ]
</script>

<Autocomplete openOnFocus>
  <AutocompleteInput aria-label="Search" placeholder="Search…" />
  <AutocompleteContent>
    <AutocompleteEmpty>No results.</AutocompleteEmpty>
    <AutocompleteList>
      <AutocompleteGroup>
        <AutocompleteGroupLabel>Recent searches</AutocompleteGroupLabel>
        {#each recent as search (search)}
          <AutocompleteItem value={search}>
            {search}
          </AutocompleteItem>
        {/each}
      </AutocompleteGroup>
    </AutocompleteList>
  </AutocompleteContent>
</Autocomplete>
```

聚焦 Search docs，在输入前看到最近的搜索。Escape 会关闭它们；再次按压该字段会重新打开。

## 自动高亮
`autoHighlight` 在输入时高亮第一个匹配项，这样按 Enter 就能立即选中它。把 `loop` 设为 `false`，方向键会在列表两端停住。

```svelte title="auto-highlight.svelte"
<script lang="ts">
  import {
    Autocomplete,
    AutocompleteContent,
    AutocompleteEmpty,
    AutocompleteInput,
    AutocompleteItem,
    AutocompleteLabel,
    AutocompleteList,
  } from "@ui-sdk/svelte/autocomplete"

  const fruits = [
    "Apple",
    "Apricot",
    "Avocado",
    "Banana",
    "Blackberry",
    "Blueberry",
    "Cherry",
    "Grape",
    "Lemon",
    "Mango",
    "Orange",
    "Peach",
    "Pear",
    "Pineapple",
    "Strawberry",
  ]
</script>

<Autocomplete autoHighlight loop={false}>
  <div data-slot="stack">
    <AutocompleteLabel>Fruit</AutocompleteLabel>
    <AutocompleteInput placeholder="Type, then Enter" />
  </div>
  <AutocompleteContent>
    <AutocompleteEmpty>No fruits found.</AutocompleteEmpty>
    <AutocompleteList>
      {#each fruits as fruit (fruit)}
        <AutocompleteItem value={fruit}>
          {fruit}
        </AutocompleteItem>
      {/each}
    </AutocompleteList>
  </AutocompleteContent>
</Autocomplete>
```

输入 “pe” 并按 Enter，选中第一个匹配项。这个示例禁用了循环，所以方向键会在两端停住。

## 行内补全
`inlineComplete` 会把第一条以已输入文字开头的建议的剩余部分填进来，并选中补上的文字。方向键会填入它们高亮的建议。End 或 Right Arrow 接受补全；Backspace 或 Escape 撤回补全。

```svelte title="inline.svelte"
<script lang="ts">
  import {
    Autocomplete,
    AutocompleteContent,
    AutocompleteEmpty,
    AutocompleteInput,
    AutocompleteItem,
    AutocompleteLabel,
    AutocompleteList,
  } from "@ui-sdk/svelte/autocomplete"

  const fruits = [
    "Apple",
    "Apricot",
    "Avocado",
    "Banana",
    "Blackberry",
    "Blueberry",
    "Cherry",
    "Grape",
    "Lemon",
    "Mango",
    "Orange",
    "Peach",
    "Pear",
    "Pineapple",
    "Strawberry",
  ]
</script>

<Autocomplete inlineComplete>
  <div data-slot="stack">
    <AutocompleteLabel>Fruit</AutocompleteLabel>
    <AutocompleteInput placeholder="Type “bl”" />
  </div>
  <AutocompleteContent>
    <AutocompleteEmpty>No fruits found.</AutocompleteEmpty>
    <AutocompleteList>
      {#each fruits as fruit (fruit)}
        <AutocompleteItem value={fruit}>
          {fruit}
        </AutocompleteItem>
      {/each}
    </AutocompleteList>
  </AutocompleteContent>
</Autocomplete>
```

输入 “bl”，行内补全为 blackberry。Backspace 移除补全；Down Arrow 填入 Blueberry。按 End 接受这段文字。

## 高亮匹配项
`AutocompleteItemText` 会标记匹配的文字，匹配使用当前 locale 忽略大小写和变音符号。如果你想自己渲染，它的状态也会暴露匹配的 `segments`，就像这个示例用加粗来渲染。

```svelte title="highlight.svelte"
<script lang="ts">
  import {
    Autocomplete,
    AutocompleteContent,
    AutocompleteEmpty,
    AutocompleteInput,
    AutocompleteItem,
    AutocompleteItemText,
    AutocompleteLabel,
    AutocompleteList,
  } from "@ui-sdk/svelte/autocomplete"

  const fruits = [
    "Apple",
    "Apricot",
    "Avocado",
    "Banana",
    "Blackberry",
    "Blueberry",
    "Cherry",
    "Grape",
    "Lemon",
    "Mango",
    "Orange",
    "Peach",
    "Pear",
    "Pineapple",
    "Strawberry",
  ]
</script>

<Autocomplete>
  <div data-slot="stack">
    <AutocompleteLabel>Favorite fruit</AutocompleteLabel>
    <AutocompleteInput placeholder="e.g. berry" />
  </div>
  <AutocompleteContent>
    <AutocompleteEmpty>No fruits found.</AutocompleteEmpty>
    <AutocompleteList>
      {#each fruits as fruit (fruit)}
        <AutocompleteItem value={fruit}>
          <AutocompleteItemText>
            {#snippet render({ props, state })}
              <span {...props}>
                {#each state.segments as segment, index (index)}
                  {#if segment.match}
                    <strong>{segment.text}</strong>
                  {:else}
                    {segment.text}
                  {/if}
                {/each}
              </span>
            {/snippet}
          </AutocompleteItemText>
        </AutocompleteItem>
      {/each}
    </AutocompleteList>
  </AutocompleteContent>
</Autocomplete>
```

输入 “berry”。匹配的字母会加粗，每条建议仍保留原来的拼写。

## 过滤与关键词
默认的过滤会匹配建议中任意位置的文字。用 `"startsWith"` 或 `"fuzzy"` 换一种匹配方式，用一个函数实现自己的过滤，或对已经由服务器过滤过的结果用 `false`。`keywords` 增加可搜索的文字，但不改变填进字段的内容。

```svelte title="filter.svelte"
<script lang="ts">
  import {
    Autocomplete,
    AutocompleteContent,
    AutocompleteEmpty,
    AutocompleteInput,
    AutocompleteItem,
    AutocompleteLabel,
    AutocompleteList,
  } from "@ui-sdk/svelte/autocomplete"

  const tags = [
    {
      value: "feature",
      label: "feature",
      keywords: ["enhancement", "request"],
    },
    { value: "fix", label: "fix", keywords: ["bug", "patch"] },
    { value: "docs", label: "docs", keywords: ["documentation", "readme"] },
    { value: "performance", label: "performance", keywords: ["speed", "slow"] },
    { value: "security", label: "security", keywords: ["vulnerability"] },
    { value: "refactor", label: "refactor", keywords: ["cleanup"] },
  ]
</script>

<Autocomplete filter="startsWith">
  <div data-slot="stack">
    <AutocompleteLabel>Tag</AutocompleteLabel>
    <AutocompleteInput placeholder="Try “bug”" />
  </div>
  <AutocompleteContent>
    <AutocompleteEmpty>No tags found.</AutocompleteEmpty>
    <AutocompleteList>
      {#each tags as tag (tag.value)}
        <AutocompleteItem
          value={tag.value}
          label={tag.label}
          keywords={tag.keywords}
        >
          {tag.label}
          <span data-slot="hint">{tag.keywords[0]}</span>
        </AutocompleteItem>
      {/each}
    </AutocompleteList>
  </AutocompleteContent>
</Autocomplete>
```

输入 “bug”，通过关键词找到 fix。输入 “re”，找到标签或关键词以这些字母开头的建议。

## 分组
用 `AutocompleteGroup` 和 `AutocompleteGroupLabel` 给相关的建议分组命名。过滤会隐藏空分组和分隔线。

```svelte title="groups.svelte"
<script lang="ts">
  import {
    Autocomplete,
    AutocompleteContent,
    AutocompleteEmpty,
    AutocompleteGroup,
    AutocompleteGroupLabel,
    AutocompleteInput,
    AutocompleteItem,
    AutocompleteLabel,
    AutocompleteList,
    AutocompleteSeparator,
  } from "@ui-sdk/svelte/autocomplete"

  const fruitGroups = [
    {
      label: "Tree fruits",
      items: ["Apple", "Apricot", "Cherry", "Lemon", "Peach", "Pear"],
    },
    {
      label: "Berries",
      items: ["Blackberry", "Blueberry", "Grape", "Strawberry"],
    },
    { label: "Tropical", items: ["Avocado", "Banana", "Mango", "Pineapple"] },
  ]
</script>

<Autocomplete>
  <div data-slot="stack">
    <AutocompleteLabel>Fruit</AutocompleteLabel>
    <AutocompleteInput placeholder="e.g. Pear" />
  </div>
  <AutocompleteContent>
    <AutocompleteEmpty>No fruits found.</AutocompleteEmpty>
    <AutocompleteList>
      {#each fruitGroups as group, index (group.label)}
        {#if index > 0}<AutocompleteSeparator />{/if}
        <AutocompleteGroup>
          <AutocompleteGroupLabel>{group.label}</AutocompleteGroupLabel>
          {#each group.items as fruit (fruit)}
            <AutocompleteItem value={fruit}>
              {fruit}
            </AutocompleteItem>
          {/each}
        </AutocompleteGroup>
      {/each}
    </AutocompleteList>
  </AutocompleteContent>
</Autocomplete>
```

输入 “an”。Banana 和 Mango 留在 Tropical 分组里；没有匹配项的分组会消失。

## 图标
`AutocompleteItemIcon` 让装饰性图标不进入无障碍名称、过滤和填进字段的文字。方向性图标加上 `mirror`。只有图标的建议仍然需要 `aria-label`。

```svelte title="icons.svelte"
<script lang="ts">
  import {
    ArchiveIcon,
    ClockIcon,
    FileIcon,
    PencilIcon,
    ReplyIcon,
    StarIcon,
  } from "@lucide/svelte"
  import {
    Autocomplete,
    AutocompleteContent,
    AutocompleteEmpty,
    AutocompleteInput,
    AutocompleteItem,
    AutocompleteItemIcon,
    AutocompleteList,
  } from "@ui-sdk/svelte/autocomplete"

  const mailSearches = [
    { value: "Starred", icon: StarIcon },
    { value: "Drafts", icon: PencilIcon },
    { value: "Replies", icon: ReplyIcon, mirror: true },
    { value: "Attachments", icon: FileIcon },
    { value: "Archived", icon: ArchiveIcon },
    { value: "Scheduled", icon: ClockIcon },
  ]
</script>

<Autocomplete>
  <AutocompleteInput
    type="search"
    aria-label="Search mail"
    placeholder="Search mail…"
  />
  <AutocompleteContent>
    <AutocompleteEmpty>No searches found.</AutocompleteEmpty>
    <AutocompleteList>
      {#each mailSearches as search (search.value)}
        <AutocompleteItem value={search.value}>
          <AutocompleteItemIcon mirror={search.mirror}>
            <search.icon />
          </AutocompleteItemIcon>
          {search.value}
        </AutocompleteItem>
      {/each}
    </AutocompleteList>
  </AutocompleteContent>
</Autocomplete>
```

输入 “rep” 并选择 Replies。图标不会进入填进字段的文字。

## 以数据形式提供的选项
如果你要自己写标记，可以把数组映射成部件。这个示例映射水果分组，并在分组之间加上分隔线。

```svelte title="data.svelte"
<script lang="ts">
  import {
    Autocomplete,
    AutocompleteContent,
    AutocompleteEmpty,
    AutocompleteGroup,
    AutocompleteGroupLabel,
    AutocompleteInput,
    AutocompleteItem,
    AutocompleteLabel,
    AutocompleteList,
    AutocompleteSeparator,
  } from "@ui-sdk/svelte/autocomplete"

  const fruitGroups = [
    {
      label: "Tree fruits",
      fruits: ["Apple", "Apricot", "Cherry", "Lemon", "Peach", "Pear"],
    },
    {
      label: "Berries",
      fruits: ["Blackberry", "Blueberry", "Grape", "Strawberry"],
    },
    { label: "Tropical", fruits: ["Avocado", "Banana", "Mango", "Pineapple"] },
  ]
</script>

<Autocomplete>
  <div data-slot="stack">
    <AutocompleteLabel>Fruit</AutocompleteLabel>
    <AutocompleteInput placeholder="e.g. Peach" />
  </div>
  <AutocompleteContent>
    <AutocompleteEmpty>No fruits found.</AutocompleteEmpty>
    <AutocompleteList>
      {#each fruitGroups as group, index (group.label)}
        {#if index > 0}<AutocompleteSeparator />{/if}
        <AutocompleteGroup>
          <AutocompleteGroupLabel>{group.label}</AutocompleteGroupLabel>
          {#each group.fruits as fruit (fruit)}
            <AutocompleteItem value={fruit}>{fruit}</AutocompleteItem>
          {/each}
        </AutocompleteGroup>
      {/each}
    </AutocompleteList>
  </AutocompleteContent>
</Autocomplete>
```

打开列表，看到三个水果分组。输入 “an”，把它们缩小到 Banana 和 Mango。

当 autocomplete 需要整个集合时，比如服务器结果或最近的搜索，传入 `items`。它可以为你渲染不带内容的部件。要给变化的结果设样式，从列表的 `state.items` 渲染。[列表与菜单](/docs/svelte/lists-and-menus)介绍了 `ListData` 格式。

列表打开期间，建议可以变化。高亮会留在它所在的建议上，已输入的文字保持不变。移除高亮所在的建议会清除高亮。

## 受控
值始终是字符串。用 `value` 和 `onValueChange` 控制它，或用 `defaultValue` 以非受控方式开始。建议有独立的 `open` 状态和 `onOpenChange`。回调先收到提议的值，再收到变更详情。调用 `details.cancel()` 拒绝一次文字或打开状态的变更。选中一条建议时，`details.item` 带有它的 `value` 和 `label`，所以共享同一标签的建议仍然可以区分。[状态与事件](/docs/svelte/state-and-events)介绍了受控状态和取消。

```svelte title="controlled.svelte"
<script lang="ts">
  import {
    Autocomplete,
    AutocompleteContent,
    AutocompleteEmpty,
    AutocompleteInput,
    AutocompleteItem,
    AutocompleteLabel,
    AutocompleteList,
  } from "@ui-sdk/svelte/autocomplete"
  import { useLog } from "./log"

  const fruits = [
    "Apple",
    "Apricot",
    "Avocado",
    "Banana",
    "Blackberry",
    "Blueberry",
    "Cherry",
    "Grape",
    "Lemon",
    "Mango",
    "Orange",
    "Peach",
    "Pear",
    "Pineapple",
    "Strawberry",
  ]

  const log = useLog()

  let value = $state("")
  let open = $state(false)

  function changeValue(
    next: string,
    details: { reason: string; cancel: () => void }
  ) {
    if (next.length > 12) {
      return details.cancel()
    }
    log(`text: ${details.reason}`)
  }
</script>

<div data-slot="stack">
  <Autocomplete
    bind:value
    bind:open
    debug
    onValueChange={changeValue}
    onOpenChange={(next, details) =>
      log(`${next ? "opened" : "closed"}: ${details.reason}`)}
    onOpenChangeComplete={(next) =>
      log(`${next ? "opened" : "closed"} and settled`)}
    onHighlight={(highlighted) =>
      highlighted && log(`highlighted ${highlighted}`)}
  >
    <AutocompleteLabel>Fruit (12 characters at most)</AutocompleteLabel>
    <AutocompleteInput />
    <AutocompleteContent>
      <AutocompleteEmpty>No fruits found.</AutocompleteEmpty>
      <AutocompleteList>
        {#each fruits as fruit (fruit)}
          <AutocompleteItem value={fruit}>
            {fruit}
          </AutocompleteItem>
        {/each}
      </AutocompleteList>
    </AutocompleteContent>
  </Autocomplete>
</div>
```

输入超过 12 个字符，多出的文字会被拒绝。控制台会显示每次变更及其原因。

## 控制器
为一个实例创建 `createAutocompleteController()`，并作为 `controller` 传入。它可以 `setValue()`、`clear()`、`focus()`、`setOpen()`，或读取 `getValue()` 和 `isOpen()`。`open()` 返回一个 promise，在浮层关闭时兑现，包括中止和卸载；`close()` 关闭它。[控制器](/docs/svelte/controllers)介绍了生命周期和变更选项。

```svelte title="controller.svelte"
<script lang="ts">
  import {
    Autocomplete,
    AutocompleteContent,
    AutocompleteEmpty,
    AutocompleteInput,
    AutocompleteItem,
    AutocompleteLabel,
    AutocompleteList,
    createAutocompleteController,
  } from "@ui-sdk/svelte/autocomplete"

  const fruits = [
    "Apple",
    "Apricot",
    "Avocado",
    "Banana",
    "Blackberry",
    "Blueberry",
    "Cherry",
    "Grape",
    "Lemon",
    "Mango",
    "Orange",
    "Peach",
    "Pear",
    "Pineapple",
    "Strawberry",
  ]

  const fruit = createAutocompleteController()
</script>

<div data-slot="stack">
  <div data-slot="controls">
    <button type="button" data-size="sm" onclick={() => fruit.open()}>
      Open
    </button>
    <button type="button" data-size="sm" onclick={() => fruit.setValue("Pea")}>
      Type “Pea”
    </button>
    <button type="button" data-size="sm" onclick={() => fruit.clear()}>
      Clear
    </button>
    <button type="button" data-size="sm" onclick={() => fruit.focus()}>
      Focus
    </button>
  </div>
  <Autocomplete controller={fruit}>
    <AutocompleteLabel>Fruit</AutocompleteLabel>
    <AutocompleteInput />
    <AutocompleteContent>
      <AutocompleteEmpty>No fruits found.</AutocompleteEmpty>
      <AutocompleteList>
        {#each fruits as item (item)}
          <AutocompleteItem value={item}>
            {item}
          </AutocompleteItem>
        {/each}
      </AutocompleteList>
    </AutocompleteContent>
  </Autocomplete>
</div>
```

用按钮打开建议、输入 Pea、清除字段，或从外部聚焦它。

## 定位
用 `side`、`align`、偏移或自定义 `anchor` 给建议定位。`container` 选择它们渲染到哪里，`keepMounted` 让关闭的内容留在 DOM 里。[浮层](/docs/svelte/popups)介绍了定位、传送门（portal）、动画和模态行为。

```svelte title="positioning.svelte"
<script lang="ts">
  import {
    Autocomplete,
    AutocompleteContent,
    AutocompleteEmpty,
    AutocompleteInput,
    AutocompleteItem,
    AutocompleteLabel,
    AutocompleteList,
  } from "@ui-sdk/svelte/autocomplete"

  const fruits = [
    "Apple",
    "Apricot",
    "Avocado",
    "Banana",
    "Blackberry",
    "Blueberry",
  ]

  let box: HTMLDivElement | undefined = $state()
</script>

<div bind:this={box} data-slot="card">
  <Autocomplete modal="pointer" container={box}>
    <div data-slot="stack">
      <AutocompleteLabel>Fruit</AutocompleteLabel>
      <AutocompleteInput />
    </div>
    <AutocompleteContent
      side="top"
      align="end"
      sideOffset={10}
      alignOffset={-4}
      collisionPadding={8}
      anchor={box}
      keepMounted
    >
      <AutocompleteEmpty>No fruits found.</AutocompleteEmpty>
      <AutocompleteList>
        {#each fruits as fruit (fruit)}
          <AutocompleteItem value={fruit}>
            {fruit}
          </AutocompleteItem>
        {/each}
      </AutocompleteList>
    </AutocompleteContent>
  </Autocomplete>
</div>
```

打开建议。它们出现在卡片上方，对齐到它的末尾。

## 动画
内容打开期间带有 `data-starting-style`，关闭期间带有 `data-ending-style`。从这些状态做过渡，浮层会保持挂载直到退场结束：

```css
[data-slot="autocomplete-content"] {
  transition:
    opacity 0.15s,
    translate 0.2s cubic-bezier(0.22, 1, 0.36, 1);

  &:is([data-starting-style], [data-ending-style]) {
    opacity: 0;
    translate: 0 -6px;
  }
}
```

```svelte title="animation.svelte"
<script lang="ts">
  import {
    Autocomplete,
    AutocompleteContent,
    AutocompleteEmpty,
    AutocompleteInput,
    AutocompleteItem,
    AutocompleteLabel,
    AutocompleteList,
  } from "@ui-sdk/svelte/autocomplete"

  const fruits = [
    "Apple",
    "Apricot",
    "Avocado",
    "Banana",
    "Blackberry",
    "Blueberry",
    "Cherry",
    "Grape",
    "Lemon",
    "Mango",
    "Orange",
    "Peach",
    "Pear",
    "Pineapple",
    "Strawberry",
  ]
</script>

<Autocomplete>
  <div data-slot="stack">
    <AutocompleteLabel>Favorite fruit</AutocompleteLabel>
    <AutocompleteInput placeholder="e.g. Mango" />
  </div>
  <AutocompleteContent>
    <AutocompleteEmpty>No fruits found.</AutocompleteEmpty>
    <AutocompleteList>
      {#each fruits as fruit (fruit)}
        <AutocompleteItem value={fruit}>
          {fruit}
        </AutocompleteItem>
      {/each}
    </AutocompleteList>
  </AutocompleteContent>
</Autocomplete>
```

输入以打开建议。它们滑入并淡入，在卸载前淡出。

## 呈现方式
`presentation="sheet"` 会以底部面板（sheet）打开建议。`"auto"` 在每次打开列表时，于小屏触摸设备上选择底部面板，在其他设备上用 popover。服务器端以 popover 开始。

同一个输入框会移进面板的头部。触摸打开时键盘不会弹出；轻点头部的输入框会弹出键盘并展开面板。选择一条建议或向下轻扫会关闭它。用键盘和鼠标打开时，输入框保持焦点。

除非把 `modal` 设为 `false`，否则面板是模态的。给它一个高度，把建议放在 `AutocompleteList` 里，并且不要动内容的 `translate`，这样拖动才能移动它。用 `data-presentation` 为两种呈现方式设样式，用 `--sheet-backdrop` 设置变暗的背景。

```svelte title="presentation.svelte"
<script lang="ts">
  import {
    Autocomplete,
    AutocompleteContent,
    AutocompleteEmpty,
    AutocompleteInput,
    AutocompleteItem,
    AutocompleteLabel,
    AutocompleteList,
  } from "@ui-sdk/svelte/autocomplete"

  const fruits = [
    "Apple",
    "Apricot",
    "Avocado",
    "Banana",
    "Blackberry",
    "Blueberry",
    "Cherry",
    "Grape",
    "Lemon",
    "Mango",
    "Orange",
    "Peach",
    "Pear",
    "Pineapple",
    "Strawberry",
  ]
</script>

<Autocomplete presentation="sheet">
  <div data-slot="stack">
    <AutocompleteLabel>Favorite fruit</AutocompleteLabel>
    <AutocompleteInput placeholder="e.g. Mango" />
  </div>
  <AutocompleteContent>
    <AutocompleteEmpty>No fruits found.</AutocompleteEmpty>
    <AutocompleteList>
      {#each fruits as fruit (fruit)}
        <AutocompleteItem value={fruit}>
          {fruit}
        </AutocompleteItem>
      {/each}
    </AutocompleteList>
  </AutocompleteContent>
</Autocomplete>
```

打开字段查看底部面板。在触摸设备上，轻点头部的字段调出键盘，或向下轻扫关闭它。

## 表单
原生输入框就是表单控件：`name` 提供提交时的键，`required` 拒绝空文字，重置会恢复 `defaultValue`。文字不必匹配任何建议。用 `form` 让这个字段加入页面别处的表单。

```svelte title="form.svelte"
<script lang="ts">
  import {
    Autocomplete,
    AutocompleteContent,
    AutocompleteEmpty,
    AutocompleteInput,
    AutocompleteItem,
    AutocompleteList,
  } from "@ui-sdk/svelte/autocomplete"
  import {
    Field,
    FieldDescription,
    FieldError,
    FieldLabel,
  } from "@ui-sdk/svelte/field"
  import { useLog } from "./log"

  const fruits = [
    "Apple",
    "Apricot",
    "Avocado",
    "Banana",
    "Blackberry",
    "Blueberry",
    "Cherry",
    "Grape",
    "Lemon",
    "Mango",
    "Orange",
    "Peach",
    "Pear",
    "Pineapple",
    "Strawberry",
  ]

  const log = useLog()

  function submit(event: SubmitEvent) {
    event.preventDefault()
    const data = [...new FormData(event.currentTarget as HTMLFormElement)].map(
      ([name, value]) => `${name}=${value}`
    )
    log(`Submitted ${data.join("&")}`)
  }
</script>

<form id="order" data-slot="stack" onsubmit={submit}>
  <Field>
    <FieldLabel>Fruit</FieldLabel>
    <Autocomplete name="fruit" form="order" required defaultValue="Apple">
      <AutocompleteInput />
      <AutocompleteContent>
        <AutocompleteEmpty>No fruits found.</AutocompleteEmpty>
        <AutocompleteList>
          {#each fruits as fruit (fruit)}
            <AutocompleteItem value={fruit}>
              {fruit}
            </AutocompleteItem>
          {/each}
        </AutocompleteList>
      </AutocompleteContent>
    </Autocomplete>
    <FieldDescription>Any fruit, listed or not.</FieldDescription>
    <div><FieldError /></div>
  </Field>
  <div data-slot="row">
    <button type="submit" data-variant="solid"> Submit </button>
    <button type="reset"> Reset </button>
  </div>
</form>
```

提交 Apple，然后选择 Mango。选中它只会填入字段，不会提交。Reset 会恢复 Apple。

## 搜索
没有高亮建议时按 Enter，会用这段文字运行 `onSubmit` 回调，然后允许外层表单提交。如果你的处理函数已经执行了搜索，调用 `details.event` 上的 `preventDefault()`。

选择建议通常只会填入字段。加上 `submitOnSelect`，在选择一条建议时立即搜索。

```svelte title="search.svelte"
<script lang="ts">
  import {
    Autocomplete,
    AutocompleteContent,
    AutocompleteEmpty,
    AutocompleteInput,
    AutocompleteItem,
    AutocompleteList,
  } from "@ui-sdk/svelte/autocomplete"
  import { useLog } from "./log"

  const recent = [
    "react hooks",
    "tailwind grid",
    "web components",
    "vue v-model",
  ]

  const log = useLog()
</script>

<form
  role="search"
  data-slot="stack"
  onsubmit={(event) => event.preventDefault()}
>
  <Autocomplete
    submitOnSelect
    name="q"
    onSubmit={(value) => log(`Searched “${value}”`)}
  >
    <AutocompleteInput
      type="search"
      aria-label="Search"
      placeholder="Search…"
    />
    <AutocompleteContent>
      <AutocompleteEmpty>No results.</AutocompleteEmpty>
      <AutocompleteList>
        {#each recent as search (search)}
          <AutocompleteItem value={search}>
            {search}
          </AutocompleteItem>
        {/each}
      </AutocompleteList>
    </AutocompleteContent>
  </Autocomplete>
</form>
```

输入 “kotlin” 并按 Enter 搜索。选择一条建议，改为搜索那段文字。

## 最近的搜索
把 `emptyItems` 和 `items` 搭配，在字段为空时显示一个集合，有人输入后再搜索完整集合。加上 `openOnFocus`，在聚焦时显示最近的搜索。

```svelte title="recent.svelte"
<script lang="ts">
  import type { ListAnnouncement } from "@ui-sdk/core/autocomplete"
  import {
    Autocomplete,
    AutocompleteContent,
    AutocompleteEmpty,
    AutocompleteGroup,
    AutocompleteGroupLabel,
    AutocompleteInput,
    AutocompleteItem,
    AutocompleteItemText,
    AutocompleteList,
  } from "@ui-sdk/svelte/autocomplete"

  const recent = [
    "react hooks",
    "tailwind grid",
    "web components",
    "vue v-model",
  ]
  const topics = [
    ...recent,
    "react server components",
    "tailwind colors",
    "vue router",
  ]
  const recentSearches = [
    { type: "group" as const, label: "Recent searches", items: recent },
  ]

  function announcement(change: ListAnnouncement) {
    return change.type === "results"
      ? `${change.count} ${change.count === 1 ? "topic" : "topics"}`
      : null
  }
</script>

<Autocomplete
  items={topics}
  emptyItems={recentSearches}
  openOnFocus
  {announcement}
>
  <AutocompleteInput
    type="search"
    aria-label="Search docs"
    placeholder="Search docs…"
  />
  <AutocompleteContent>
    <AutocompleteEmpty>No topics found.</AutocompleteEmpty>
    <AutocompleteList>
      {#snippet children(state)}
        {#each state.items as (string | (typeof recentSearches)[number])[] as entry (typeof entry === "string" ? entry : entry.label)}
          {#if typeof entry === "string"}
            <AutocompleteItem value={entry}>
              <AutocompleteItemText />
            </AutocompleteItem>
          {:else}
            <AutocompleteGroup>
              <AutocompleteGroupLabel>{entry.label}</AutocompleteGroupLabel>
              {#each entry.items as topic (topic)}
                <AutocompleteItem value={topic}>
                  <AutocompleteItemText />
                </AutocompleteItem>
              {/each}
            </AutocompleteGroup>
          {/if}
        {/each}
      {/snippet}
    </AutocompleteList>
  </AutocompleteContent>
</Autocomplete>
```

聚焦空的字段查看 Recent searches。输入 “react” 搜索所有主题，然后清空文字回到最近的搜索。

## 异步建议
用[异步选项](/docs/svelte/utilities/async-options)等输入停顿，并丢弃过期的结果。把它的 `items` 和 `status` 传进来，把 `filter` 设为 `false`，并把文字变更发送给它的 `setQuery()` 方法。

`AutocompleteStatus` 和 `AutocompleteEmpty` 提供加载中、错误和空消息。没有状态部件时，`announcement` 控制输入停顿后屏幕阅读器听到的内容。滚动或高亮到达最后一条建议时，`onLoadMore` 可以请求下一页。

```svelte title="async.svelte"
<script lang="ts">
  import {
    Autocomplete,
    AutocompleteContent,
    AutocompleteEmpty,
    AutocompleteInput,
    AutocompleteItem,
    AutocompleteLabel,
    AutocompleteList,
    AutocompleteStatus,
  } from "@ui-sdk/svelte/autocomplete"
  import { useAsyncOptions } from "@ui-sdk/svelte/async-options"

  function searchCities(query: string, { signal }: { signal: AbortSignal }) {
    const cities = [
      "Amsterdam",
      "Athens",
      "Barcelona",
      "Berlin",
      "Boston",
      "Brussels",
      "Buenos Aires",
      "Cairo",
      "Chicago",
      "Copenhagen",
      "Dublin",
      "Lisbon",
      "London",
      "Los Angeles",
      "Madrid",
      "Paris",
      "Prague",
      "Rome",
      "Seoul",
      "Tokyo",
    ]
    return new Promise<string[]>((resolve, reject) => {
      const timer = setTimeout(() => {
        const needle = query.trim().toLowerCase()
        resolve(cities.filter((city) => city.toLowerCase().startsWith(needle)))
      }, 300)
      signal.addEventListener("abort", () => {
        clearTimeout(timer)
        reject(new DOMException("Aborted", "AbortError"))
      })
    })
  }

  const results = useAsyncOptions(searchCities, { debounce: 200 })
</script>

<Autocomplete
  items={results.state.items}
  filter={false}
  status={results.state.status}
  onValueChange={(value) => results.setQuery(value)}
  onLoadMore={results.loadMore}
>
  <div data-slot="stack">
    <AutocompleteLabel>City</AutocompleteLabel>
    <AutocompleteInput placeholder="e.g. Paris" />
  </div>
  <AutocompleteContent>
    <AutocompleteStatus>
      {#snippet children(state)}
        {state.loading
          ? "Searching…"
          : state.count
            ? `${state.count} ${state.count === 1 ? "city" : "cities"}`
            : ""}
      {/snippet}
    </AutocompleteStatus>
    <AutocompleteEmpty>
      {#snippet children(state)}
        {#if state.empty && !state.loading}No cities start with “{state.query}”.{/if}
      {/snippet}
    </AutocompleteEmpty>
    <AutocompleteList>
      {#snippet children(state)}
        {#each state.items as string[] as city (city)}
          <AutocompleteItem value={city}>
            {city}
          </AutocompleteItem>
        {/each}
      {/snippet}
    </AutocompleteList>
  </AutocompleteContent>
</Autocomplete>
```

输入 “b”，等待城市建议。继续输入会替换这次搜索；状态会描述最新的结果。

## 自定义渲染
用 `render` snippet 给建议换一个元素。这里每条建议都是一个链接，所以这个 autocomplete 可以当作跳转菜单：Enter 或点击会跟随高亮的链接，标题后的文字是不影响过滤的提示。[部件与组合](/docs/svelte/parts-and-composition)介绍了 render API。

```svelte title="custom-rendering.svelte"
<script lang="ts">
  import {
    Autocomplete,
    AutocompleteContent,
    AutocompleteEmpty,
    AutocompleteInput,
    AutocompleteItem,
    AutocompleteLabel,
    AutocompleteList,
  } from "@ui-sdk/svelte/autocomplete"

  const pages = [
    { title: "Installation", section: "Get Started", href: "#installation" },
    { title: "Composition", section: "Concepts", href: "#composition" },
    { title: "Build Your Own", section: "Concepts", href: "#build-your-own" },
    { title: "Styling", section: "Guides", href: "#styling" },
    { title: "API Reference", section: "Reference", href: "#api-reference" },
    { title: "Accessibility", section: "Reference", href: "#accessibility" },
  ]
</script>

<Autocomplete>
  <div data-slot="stack">
    <AutocompleteLabel>Jump to</AutocompleteLabel>
    <AutocompleteInput placeholder="e.g. Styling" />
  </div>
  <AutocompleteContent>
    <AutocompleteEmpty>No sections found.</AutocompleteEmpty>
    <AutocompleteList>
      {#each pages as page (page.href)}
        <AutocompleteItem value={page.title} label={page.title}>
          {#snippet render({ props })}
            <a {...props} href={page.href}>
              {page.title}
              <span data-slot="hint">{page.section}</span>
            </a>
          {/snippet}
        </AutocompleteItem>
      {/each}
    </AutocompleteList>
  </AutocompleteContent>
</Autocomplete>
```

输入 “sty” 并按 Enter，跳到本页的 Styling 小节。

## 样式
每个部件都有一个 `data-slot`，比如 `autocomplete-content`，并通过[数据属性](https://ui-sdk.cn/docs/svelte/components/autocomplete#data-attributes)下列出的属性展示它的状态。

浮层会暴露尺寸和动画相关的变量。`--anchor-width` 是输入框的宽度；在内容上使用 `--available-height`，让长列表留在视口内。

焦点留在输入框里时，用内容的 `data-modality="keyboard"` 配合项的 `data-highlighted`，在高亮的建议上显示键盘焦点指示。

### AutocompleteContent
- `--anchor-width`: Width of the anchor, usually the trigger. Use it to match widths.
- `--anchor-height`: Height of the anchor.
- `--available-width`: Space beside the popup, up to the viewport edge. Not inherited either.
- `--available-height`: Space between the anchor and the viewport edge. Use it for max-height. Not inherited, so a child that needs it copies it on the popup, like `[--list-height:var(--available-height)]`, and reads `max-h-(--list-height)`. The first popup registers both names for the whole page with `CSS.registerProperty`, so they don't inherit anywhere. A page that needs them to inherit calls it first, with `inherits: true`. An `@property` rule can't, since a registration in script wins.
- `--transform-origin`: The point on the anchor the popup opens from. Use it to scale from the right place.
- `--arrow-offset`: Where the anchor's center falls along the popup's edge, kept `arrowPadding` from the corners. Position a ::before arrow with it.
- `--drawer-progress`: While it presents as a sheet: how far open the sheet is, from 0 closed to 1 at its largest snap point. Never past 1.
- `--drawer-dim`: While it presents as a sheet: how dim the page behind is, from 0 to 1. The backdrop's opacity follows it.
- `--drawer-expand`: While it presents as a sheet: 0 at the second-largest snap point and below, 1 at the largest. With one snap point, the whole travel.
- `--drawer-stack`: While it presents as a sheet: how many sheets opened from inside this one are open above it, rising smoothly as each one opens. Push it back with it.
- `--sheet-backdrop`: Set it yourself: the color the page dims to while it presents as a sheet. Black at 0.2 by default.

### Viewport
- `--keyboard-inset`: While it presents as a sheet: how many pixels of the page the on-screen keyboard covers, 0 without one.
- `--visual-viewport-width`: While it presents as a sheet: the width of the part of the page you can see.
- `--visual-viewport-height`: While it presents as a sheet: the height of the part of the page you can see, above the keyboard.
- `--visual-viewport-top`: While it presents as a sheet: how far the part of the page you can see is scrolled from the top of the layout, as when the keyboard pushes it up.

## 数据属性
### AutocompleteLabel
`[data-slot="autocomplete-label"]`

- `data-disabled`: Present when the field is disabled, by its own prop, a field or a `<fieldset>`.
- `data-readonly`: Present when the field is read-only.
- `data-required`: Present when the field is required.

### AutocompleteInput
`[data-slot="autocomplete-input"]`

- `data-closed`: Present while the suggestions are closed, including while they animate out.
- `data-open`: Present while the suggestions are open.
- `data-disabled`: Present when the field is disabled, by its own prop, a field or a `<fieldset>`.
- `data-readonly`: Present when the field is read-only.
- `data-required`: Present when the field is required.

### AutocompleteTrigger
`[data-slot="autocomplete-trigger"]`

- `data-closed`: Present while the suggestions are closed, including while they animate out.
- `data-open`: Present while the suggestions are open.
- `data-disabled`: Present when the field is disabled, by its own prop, a field or a `<fieldset>`.
- `data-readonly`: Present when the field is read-only.
- `data-required`: Present when the field is required.

### AutocompleteClear
`[data-slot="autocomplete-clear"]`

- `data-disabled`: Present when the field is disabled or read-only.

### AutocompleteContent
`[data-slot="autocomplete-content"]`

- `data-closed`: Present while the suggestions are closed, including while they animate out.
- `data-presentation` (`popover`, `sheet`): How the suggestions present this time they're open.
- `data-open`: Present while the suggestions are open.
- `data-starting-style`: Present for the first frame. Style the state you animate from.
- `data-ending-style`: Present while the list animates out. Style the state you animate to.
- `data-side` (`top`, `right`, `bottom`, `left`): Where the suggestions ended up, after flipping away from edges.
- `data-align` (`start`, `center`, `end`): How the suggestions line up with the field.
- `data-modality` (`keyboard`, `pointer`): Whether the keyboard or a pointer moves the highlight. Style a focus ring for the keyboard only.
- `data-has-icons`: Present while any suggestion inside holds an icon part, so items without one can line up.

### AutocompleteItem
`[data-slot="autocomplete-item"]`

- `data-disabled`: Present when the suggestion can't be chosen. Arrow keys skip it.
- `data-highlighted`: Present on the highlighted suggestion, which Enter fills in. Focus stays in the field.
- `data-has-icon`: Present on a suggestion while it holds an icon part.

### AutocompleteItemText
`[data-slot="autocomplete-item-text"]`

- `data-matched`: Present on a suggestion's text while the field's text matched part of it, which is marked.

### AutocompleteEmpty
`[data-slot="autocomplete-empty"]`

- `data-loading`: Present while results load, with `status="loading"`.
- `data-empty`: Present while no suggestion matches.

### AutocompleteStatus
`[data-slot="autocomplete-status"]`

- `data-loading`: Present while results load, with `status="loading"`.

### AutocompleteArrow
`[data-slot="autocomplete-arrow"]`

- `data-closed`: Present while the suggestions are closed, including while they animate out.
- `data-open`: Present while the suggestions are open.
- `data-side` (`top`, `right`, `bottom`, `left`): Where the suggestions ended up, after flipping away from edges.
- `data-align` (`start`, `center`, `end`): How the suggestions line up with the field.
- `data-arrow-clamped`: Present on the arrow when it stops short of the middle of the field, held back by `arrowPadding`.

### AutocompleteItemIcon
`[data-slot="autocomplete-item-icon"]`

- `data-mirror`: Present on an icon that flips in right-to-left text, with `mirror`.

## API 参考
属性和回调与下面相同，都是 Svelte props。`value` 和 `open` 可以用 `bind:` 绑定。不带 `bind:` 的 `value={x}` 是一个起始值，在 `x` 变化之前 autocomplete 可以修改它。用 `bind:value={x}` 让两者保持同步，或用函数绑定 `bind:value={() => x, (next) => (x = next)}` 由你决定。

### Autocomplete
- `container?` (`DocumentFragment | Element | null`): Renders the popup into this element instead of in place, like a container inside a shadow root or an iframe. On web components, a CSS selector. Nested popups stay inside their parent.
- `value?` (`string`): The text. Pass it to control it.
- `defaultValue?` (`string`): The text at first, when uncontrolled. A form reset returns to it.
- `onValueChange?` (`((value: string, details: AutocompleteValueChangeDetails) => void)`): Runs when the text wants to change: typing, choosing a suggestion, a Clear part, a form reset or a controller. `details.cancel()` keeps it as it was.
- `open?` (`boolean`): Whether the suggestions are open. Pass it to control them.
- `defaultOpen?` (`boolean`): Whether the suggestions start open, when uncontrolled.
- `onOpenChange?` (`((open: boolean, details: ChangeDetails<AutocompleteOpenChangeReason>) => void)`): Runs when the suggestions want to open or close. `details.reason` says why, and `details.cancel()` stops it.
- `onOpenChangeComplete?` (`((open: boolean) => void)`): Runs once the suggestions have finished opening or closing, after any animation.
- `onSubmit?` (`((value: string, details: AutocompleteSubmitDetails) => void)`): Runs with the text when Enter is pressed with no suggestion highlighted, or after choosing one with `submitOnSelect`. The surrounding form submits next, unless the event's `preventDefault()` is called.
- `items?` (`ListData<string>`): The suggestions as data. Renders them for you, and filters them without rendering every one.
- `emptyItems?` (`ListData<string>`): Suggestions shown instead of `items` while the field is empty, like recent searches, with `openOnFocus`. Groups work, like `{ type: "group", label: "Recent", items }`. Needs `items`.
- `filter?` (`SearchFilter<string>`): How typing narrows the suggestions: `"contains"`, `"startsWith"`, `"fuzzy"`, a function of the item and the text, or `false` to keep every one, for results a server already filtered.
- `inlineComplete?` (`boolean`): Whether typing completes the text with the first suggestion that starts with it, with the rest selected after the caret: ArrowRight or End accepts it, Backspace and Escape take it back out, and arrow keys fill in the suggestion they highlight.
- `autoHighlight?` (`boolean`): Whether the first suggestion is highlighted while typing, so Enter chooses it.
- `openOnFocus?` (`boolean`): Whether the suggestions open when the field gets focus, like recent searches, even before anything is typed.
- `submitOnSelect?` (`boolean`): Whether choosing a suggestion submits, like a search box: `onSubmit` runs, then the form submits.
- `status?` (`AsyncOptionsStatus`): Whether results are loading or failed, for the empty and status parts. Sets `aria-busy` on the list while loading.
- `onHighlight?` (`((value: string | null, details: ListHighlightDetails) => void)`): Runs when the highlight moves, with the suggestion's index among the visible ones, so a virtualized list can scroll to it.
- `onLoadMore?` (`(() => void)`): Runs when the highlight or scrolling reaches the last suggestion, so the next page can load, like `createAsyncOptions`'s `loadMore`. Not again for the same suggestions, unless the last load failed.
- `announcement?` (`((change: ListAnnouncement) => string | null | undefined)`): What screen readers hear after typing pauses, when no `AutocompleteStatus` is rendered. Return null for nothing.
- `loop?` (`boolean`): Whether arrow keys wrap from the last suggestion to the first.
- `modal?` (`"pointer" | boolean`): `false`: the page stays usable while the suggestions are open. `"pointer"`: an outside press only closes them. `true`: also locks scroll and makes the rest of the page inert.
- `presentation?` (`PresentationSetting<"popover">`): How the suggestions present. `"sheet"` slides them up from the bottom of the screen with the field in its header, where they can be swiped away, and `"auto"` does that on small touch screens. A tap that opens a sheet leaves the keyboard closed until the field in the header is tapped. Decided each time they open; the server renders `"popover"` for `"auto"`.
- `disabled?` (`boolean`): Disables the field like a native input: it can't be focused or changed, and its text isn't submitted.
- `readOnly?` (`boolean`): Keeps the field focusable and its text submitted, but stops changes.
- `required?` (`boolean`): Blocks form submission while the field is empty, with the browser's own message.
- `name?` (`string`): The name the text submits under.
- `form?` (`string`): The id of a form to belong to, when the field isn't inside that form.
- `controller?` (`object`): Opens, closes, reads and sets the autocomplete from anywhere. Create one with `createAutocompleteController()`.
- `dismissible?` (`boolean`): Whether Escape, an outside press, focus or the window leaving, Android's back gesture and a sheet's swipe can close it. Triggers, Close parts and the controller always can. Pass `false` while it holds unsaved work, and ask in `onDismissAttempt`.
- `onDismissAttempt?` (`function`): Runs when `dismissible` refused a dismissal made on purpose: Escape, an outside press, back or a swipe. Focus or the window leaving is refused without it. Ask "Discard changes?" here.
- `debug?` (`boolean`): Logs every state change with its reason to the console, in development builds.

### AutocompleteLabel
给输入框命名。渲染一个与输入框绑定的 `label`，所以不需要 `Field`。

### AutocompleteInput
文本字段。渲染一个带 combobox 角色的 `input`，并接受它的 props。

### AutocompleteTrigger
可选的按钮，用来打开和关闭建议。渲染一个 `button`。

### AutocompleteClear
- `keepMounted?` (`boolean`): Whether the clear button stays in the page while the field is empty.

### AutocompleteContent
- `side?` (`Side`): Which side of the anchor the popup opens on. Flips to the other side when there isn't room. Which side of the field the suggestions open on.
- `align?` (`Align`): How the popup lines up with the anchor along that side. `start` and `end` follow the reading direction. How the suggestions line up with the field along that side.
- `sideOffset?` (`number`): Gap between the anchor and the popup, in pixels. Gap between the field and the suggestions, in pixels.
- `alignOffset?` (`number`): Shift along the anchor, in pixels. Shift along the field, in pixels.
- `collisionPadding?` (`number`): Space to keep from the viewport edges, in pixels.
- `arrowPadding?` (`number`): Space to keep between the arrow and the popup's corners, in pixels.
- `anchor?` (`string | Anchor | null`): Positions the popup against this instead of its trigger: an element, a CSS selector, a point like `{ x, y }`, or anything with `getBoundingClientRect()`. It's read on every check, so it can move. A controller's `open({ anchor })` wins for that open.
- `container?` (`DocumentFragment | Element | null`): Renders the popup into this element instead of in place, like a container inside a shadow root or an iframe. On web components, a CSS selector. Nested popups stay inside their parent.
- `keepMounted?` (`boolean`): Whether the suggestions stay in the page, hidden, while closed.

### AutocompleteArrow
可选的箭头，指向输入框。渲染一个定位在内容边缘的 `div`。

### AutocompleteStatus
向屏幕阅读器播报加载中和结果数量。它的 `children` snippet 会收到状态。

### AutocompleteEmpty
没有建议匹配时显示。它的 `children` snippet 会收到状态。

### AutocompleteList
容纳建议。渲染列表框，并且在你不传 children 时渲染 `items`。

### AutocompleteGroup
把相关的建议归到一起。渲染一个带 group 角色的 `div`。

### AutocompleteGroupLabel
为它的分组命名。渲染一个作为分组名称的 `div`。

### AutocompleteItem
- `value` (`string`): Identifies the suggestion. Choosing it fills the field with its `label`, or with this when there's none.
- `label?` (`string`): The text the field gets and filtering matches, when the content isn't plain text. Not the accessible name: use `aria-label` for that.
- `keywords?` (`string[]`): More words filtering matches.
- `disabled?` (`boolean`): Keeps the suggestion from being chosen. Sets `data-disabled` and `aria-disabled`.
- `index?` (`number`): The suggestion's position among all visible ones, for virtualized lists that render only some. Sets `aria-posinset` and `aria-setsize`.

### AutocompleteItemIcon
- `mirror?` (`boolean`): Flips the icon horizontally in right-to-left text, for icons that point a way, like arrows and chevrons. Icons that picture a thing, like a clock or a check, stay as they are.

### AutocompleteItemText
建议的文字，匹配的部分会被标记。它的 snippet 会收到匹配的 `segments`。

### AutocompleteSeparator
分隔建议或分组。渲染一个带 separator 角色的 `div`。

### 以数据形式提供的选项
`items` 中的每一条建议，或一个纯字符串。分组是 `{ type: "group", label, items }`，分隔符是 `{ type: "separator" }`。

- `value` (`T`): Identifies the item, and is what choosing it reports. A string, or any value with `itemToValue`.
- `label` (`string`): The text shown and matched by typeahead and filtering. A select's trigger shows it once chosen.
- `keywords?` (`string[]`): More words filtering matches, like `["team"]` for a plan called Pro.
- `disabled?` (`boolean`): Keeps the item from being chosen. The keyboard skips it, like in a native select.

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

`AutocompleteInput` 和 `AutocompleteTrigger`：

- `open` (`boolean`): Whether the suggestions are open.
- `disabled` (`boolean`): Whether the field is disabled, by itself or by a `<fieldset>`.
- `readOnly` (`boolean`): Whether the field is read-only.
- `required` (`boolean`): Whether the field is required.

`AutocompleteContent` 和 `AutocompleteList`：

- `open` (`boolean`): Whether the suggestions are open. False while they animate out.
- `presentation` (`"popover" | "sheet"`): How they present this time they're open.
- `status` (`AsyncOptionsStatus`): Whether results are loading or failed.
- `items` (`ListData<string>`): The visible suggestions, for rendering a virtualized list yourself.

`AutocompleteItem`：

- `highlighted` (`boolean`): Whether the suggestion is highlighted, by the keyboard or the pointer.
- `disabled` (`boolean`): Whether the suggestion can't be chosen.

`AutocompleteEmpty`：

- `loading` (`boolean`): Whether results are loading.
- `empty` (`boolean`): Whether no item matches.
- `query` (`string`): The text the list is filtered by.

`AutocompleteStatus`：

- `status` (`"idle" | "loading" | "error"`): Whether results are loading or failed.
- `loading` (`boolean`): Whether results are loading.
- `count` (`number`): How many items are visible.

`AutocompleteClear`：

- `disabled` (`boolean`): Whether the field is disabled or read-only.

`AutocompleteArrow`：

- `open` (`boolean`): Whether the suggestions are open.

`AutocompleteItemText`，它不接受自己的 props：

- `segments` (`MatchSegment[]`): The text in pieces, each marked when it matched. Joined, they're the whole text.
- `matched` (`boolean`): Whether any piece matched.

`AutocompleteItemIcon`：

- `mirror` (`boolean`): Whether it flips in right-to-left text.

### 原因
文字为什么变化：

- `input-change` (`Event`): Typing, pasting or dropping changed a text field's value; in a combobox it can also open or close it, or Enter keeps the typed text as the value.
- `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.
- `escape-key` (`KeyboardEvent`): Escape, or a submenu's close key (ArrowLeft in left-to-right layouts).
- `clear-press` (`MouseEvent | KeyboardEvent`): A Clear part was pressed, like on an input, a select or a combobox.
- `reset` (`none`): A form reset.
- `imperative` (`none`): A controller or `api` call.

以及建议为什么打开或关闭：

- `input-change` (`Event`): Typing, pasting or dropping changed a text field's value; in a combobox it can also open or close it, or Enter keeps the typed text as the value.
- `item-press` (`MouseEvent | KeyboardEvent`): A member of a collection was chosen: a menu item, a tab, a radio or a checkbox item.
- `escape-key` (`KeyboardEvent`): Escape, or a submenu's close key (ArrowLeft in left-to-right layouts).
- `imperative` (`none`): A controller or `api` call.
- `trigger-press` (`MouseEvent | KeyboardEvent | TouchEvent`): Click, tap, Enter or Space on the part that opens, closes or toggles. Arrow keys that open a menu or submenu count too. A tap on a combobox's input that opens a sheet reports its `touchend`.
- `trigger-focus` (`FocusEvent`): Keyboard focus reached a trigger that opens on focus, like a tooltip's.
- `input-commit` (`KeyboardEvent | FocusEvent`): Enter, or leaving a number input, committed what was typed: a number input parses, clamps and snaps it to the step, and an autocomplete closes its suggestions on it.
- `outside-press` (`MouseEvent`): A press outside the layer.
- `close-press` (`MouseEvent | KeyboardEvent | SubmitEvent`): A Close part was pressed, or a form with `method="dialog"` was submitted.
- `focus-out` (`KeyboardEvent | FocusEvent`): Focus left the layer, or Tab moved it out.
- `window-blur` (`FocusEvent`): The window lost focus.
- `back` (`Event`): Going back: the Android back button or gesture, or Backspace in an empty command input, which returns to the previous page.
- `swipe` (`TouchEvent | PointerEvent`): A swipe gesture: a finger, mouse or pen dragged it.
- `anchor-hidden` (`none`): The element the popup sits beside stopped rendering, like a trigger a breakpoint hides.

当 `dismissible` 为 false 时，`onDismissAttempt` 报告这些被拒绝的关闭：

- `escape-key` (`KeyboardEvent`): Escape, or a submenu's close key (ArrowLeft in left-to-right layouts).
- `outside-press` (`MouseEvent`): A press outside the layer.
- `back` (`Event`): Going back: the Android back button or gesture, or Backspace in an empty command input, which returns to the previous page.
- `swipe` (`TouchEvent | PointerEvent`): A swipe gesture: a finger, mouse or pen dragged it.

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

- `isOpen()` (`() => boolean`): Whether the suggestions are open.
- `setOpen(open, options?)` (`(open: boolean, options?: AutocompleteChangeOptions<AutocompleteOpenChangeReason> | undefined) => boolean`): Opens or closes the suggestions. Returns false when the change was canceled or it was already open or closed.
- `open(options?)` (`(options?: (AutocompleteChangeOptions<AutocompleteOpenChangeReason> & { signal?: AbortSignal | undefined; }) | undefined) => Promise<...>`): Opens the suggestions, and resolves once they close, with why and how. Resolves exactly once and never rejects: on the next close, when `signal` aborts, or with reason `"unmount"`.
- `close(options?)` (`(options?: AutocompleteChangeOptions<AutocompleteOpenChangeReason> | undefined) => boolean`): Closes the suggestions. Returns false when the close was canceled or it was already closed.
- `toggle(options?)` (`(options?: AutocompleteChangeOptions<AutocompleteOpenChangeReason> | undefined) => boolean`): Opens the suggestions when they're closed, and closes them when they're open. Returns false when the change was canceled.
- `getValue()` (`() => string`): The text.
- `setValue(value, options?)` (`(value: string, options?: AutocompleteChangeOptions<AutocompleteValueChangeReason> | undefined) => boolean`): Changes the text, which filters the suggestions. Returns false when the change was canceled or nothing changed.
- `clear(options?)` (`(options?: AutocompleteChangeOptions<AutocompleteValueChangeReason> | undefined) => boolean`): Empties the field. Returns false when the change was canceled or nothing changed.
- `getHighlighted()` (`() => string | null`): The value of the highlighted suggestion, or null when none is.
- `highlight(value)` (`(value: string | null) => boolean`): Highlights the suggestion with this value in the open list, scrolled into view, or none with null. Returns false when the suggestions are closed, or no enabled suggestion has the value.
- `focus()` (`() => void`): Moves focus to the field.

### 事件
回调先收到新状态，再收到详情。绑定的值只在变更回调没有被取消时更新。

| 属性                   | 所属           | 收到                                                                     |
| ---------------------- | -------------- | ------------------------------------------------------------------------ |
| `bind:value`           | `Autocomplete` | 文字                                                                     |
| `bind:open`            | `Autocomplete` | 建议是否打开                                                             |
| `onValueChange`        | `Autocomplete` | `(value, details)`：新文字、[原因](https://ui-sdk.cn/docs/svelte/components/autocomplete#reasons)，以及它是否仍在 `composing` |
| `onOpenChange`         | `Autocomplete` | `(open, details)`：新状态，以及[原因](https://ui-sdk.cn/docs/svelte/components/autocomplete#reasons)                          |
| `onOpenChangeComplete` | `Autocomplete` | `(open)`，在动画之后                                                     |
| `onSubmit`             | `Autocomplete` | `(value, { event })`：文字，在 Enter 提交时                              |
| `onHighlight`          | `Autocomplete` | `(value, { index, event })`：高亮的建议                                  |
| `onLoadMore`           | `Autocomplete` | `()`，到达最后一条建议时                                                 |
| `onDismissAttempt`     | `Autocomplete` | `({ reason, event })`，当一次关闭被拒绝时                                |

## 无障碍
Autocomplete 遵循[带列表自动完成的 WAI-ARIA 组合框模式](https://www.w3.org/WAI/ARIA/apg/patterns/combobox/examples/combobox-autocomplete-list/)，使用 `inlineComplete` 时还遵循[列表与行内自动完成](https://www.w3.org/WAI/ARIA/apg/patterns/combobox/examples/combobox-autocomplete-both/)。

输入会过滤建议。方向键移动高亮；Enter 填入高亮的文字，Escape 关闭列表。焦点通常留在输入框里，由 `aria-activedescendant` 标识高亮的建议。触摸屏阅读器使用的触发器可以把真实焦点移进列表，底部面板也有自己的[焦点行为](https://ui-sdk.cn/docs/svelte/components/autocomplete#presentation)。

下面每一行都是一个自动化测试。

**Field**

- Is a combobox named by its label, with list autocomplete.
- Typing opens the suggestions that match, and the text stays what was typed.
- Text that matches nothing stays, with the empty message.
- Typing in the middle of the text keeps the caret where it was.

**Choosing**

- Arrow keys move the highlight while focus stays in the field.
- Enter fills in the highlighted suggestion and closes, without submitting.
- Clicking a suggestion fills it in and keeps focus in the field.
- A disabled suggestion can't be chosen.
- Escape takes an inline completion back out.
- Escape closes the suggestions and keeps the text.

**Forms**

- Enter with nothing highlighted submits the text as typed.
- The field submits a chosen suggestion's text under its name.
- Required blocks submitting an empty field.
- A disabled field can't be focused or changed.

**Clear**

- The clear button empties the field and keeps focus in it.

Runs in React、Vue 和 web components.

还测试了：

**Enhancements**

- Inline completion fills in the first match with the rest selected after the caret.
- Backspace takes an inline completion out and doesn't complete again.
- ArrowRight accepts an inline completion.
- With inline completion, arrow keys fill in the suggestion they highlight.
- The suggestions open when the field gets focus.
- Enter with nothing highlighted runs onSubmit with the text.
- Filtering matches a suggestion's keywords.
- A form reset puts the default text back.
- The list is named by the field's label.
- An immediate search runs once when the autocomplete mounts.
- A newer search aborts the older one, and only its results land.
- Arrow keys keep the highlighted item in view when the … scrolls.

Runs in React、Vue 和 web components.

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

- Announcements while typing and choosing with a keyboard.

Runs in React、Vue 和 web components.
