# Trigger Menu

"输入 @、/ 或 # 这类触发字符时，在光标处打开建议。"

触发器菜单在有人输入触发字符时提示可以插入什么，比如用 `@` 提到人、用 `/` 调出命令。它在光标处打开，随着输入收窄范围，并把选中的内容插入文本。

```svelte title="demo.svelte"
<script lang="ts">
  import { Field, FieldControl, FieldLabel } from "@ui-sdk/svelte/field"
  import {
    type TriggerMenuDataItem,
    TriggerMenu,
    TriggerMenuContent,
    TriggerMenuEmpty,
    TriggerMenuInput,
    TriggerMenuItem,
    TriggerMenuList,
    TriggerMenuStatus,
  } from "@ui-sdk/svelte/trigger-menu"

  const people = [
    { value: "hollis", label: "Hollis Grant" },
    { value: "ines", label: "Inès Moreau" },
    { value: "kofi", label: "Kofi Mensah" },
    { value: "wren", label: "Wren Takahashi" },
    { value: "tomasz", label: "Tomasz Wójcik" },
  ]
</script>

<TriggerMenu triggers={[{ char: "@", type: "mention", items: people }]}>
  <Field>
    <FieldLabel>Message</FieldLabel>
    <FieldControl>
      {#snippet render({ props })}
        <TriggerMenuInput {...props} placeholder="Type @ to mention someone…" />
      {/snippet}
    </FieldControl>
  </Field>
  <div data-slot="visually-hidden">
    <TriggerMenuStatus />
  </div>
  <TriggerMenuContent>
    <TriggerMenuEmpty>No one found</TriggerMenuEmpty>
    <TriggerMenuList>
      {#snippet children(state)}
        {#each state.items as TriggerMenuDataItem[] as item (item.value)}
          <TriggerMenuItem value={item.value} label={item.label}>
            {item.label}
          </TriggerMenuItem>
        {/each}
      {/snippet}
    </TriggerMenuList>
  </TriggerMenuContent>
</TriggerMenu>
```

输入 @，用名字收窄列表，然后按 Enter 插入高亮的人。

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

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

```text
TriggerMenu
├── TriggerMenuInput
├── TriggerMenuStatus
└── TriggerMenuContent
    ├── TriggerMenuEmpty
    └── TriggerMenuList
        ├── TriggerMenuItem
        └── TriggerMenuItem
```

`TriggerMenu` 持有各个触发器以及每个触发器列出的内容。`TriggerMenuInput` 是用户输入的字段，`TriggerMenuContent` 是带建议的浮层。如果直接子级里没有 `TriggerMenuContent`，菜单会替你渲染当前触发器的条目。放在 [Token Input](/docs/svelte/components/token-input) 内部时，省略 `TriggerMenuInput`：菜单会向 token input 提供建议。

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

```svelte
<script lang="ts">
  import {
    TriggerMenu,
    TriggerMenuContent,
    TriggerMenuInput,
    TriggerMenuItem,
    TriggerMenuList,
  } from "@ui-sdk/svelte/trigger-menu"
</script>

<TriggerMenu triggers={[{ char: "@" }]}>
  <TriggerMenuInput
    aria-label="Message"
    placeholder="Type @ to mention someone…"
  />
  <TriggerMenuContent>
    <TriggerMenuList>
      <TriggerMenuItem value="hollis" label="Hollis Grant">
        Hollis Grant
      </TriggerMenuItem>
      <TriggerMenuItem value="ines" label="Inès Moreau">
        Inès Moreau
      </TriggerMenuItem>
    </TriggerMenuList>
  </TriggerMenuContent>
</TriggerMenu>
```

`label` 是条目用来匹配和插入的文本。选择 Hollis Grant 会把 `@` 以及它后面输入的内容替换成 `@Hollis Grant `。

## Trigger Menu 还是 Token Input
Trigger Menu 提示可以插入什么：它匹配触发器、过滤、移动高亮、加载条目，并询问命令的参数。[Token Input](/docs/svelte/components/token-input) 持有一个混合了文本和 token 的值。

把 Trigger Menu 与文本域或输入框一起使用，插入文本。把它放进 Token Input，则改为插入 token。其他编辑器通过[适配器](https://ui-sdk.cn/docs/svelte/components/trigger-menu#any-editor)连接。

## 以数据形式提供的触发器
给每个触发器一个 `char` 和它的 `items`。条目可以是字符串、对象、分组或加载函数，省略 `TriggerMenuContent` 时它们会自己渲染。同一个字段可以在 `@` 之后提供人、在 `/` 之后提供命令、在 `#` 之后提供频道。

```svelte title="data.svelte"
<script lang="ts">
  import { Field, FieldControl, FieldLabel } from "@ui-sdk/svelte/field"
  import {
    type TriggerDefinition,
    TriggerMenu,
    TriggerMenuInput,
  } from "@ui-sdk/svelte/trigger-menu"

  const people = [
    { value: "hollis", label: "Hollis Grant" },
    { value: "ines", label: "Inès Moreau" },
    { value: "kofi", label: "Kofi Mensah" },
    { value: "wren", label: "Wren Takahashi" },
    { value: "tomasz", label: "Tomasz Wójcik" },
  ]

  const commands = ["away", "remind", "search", "status"]

  const channels = [
    "announcements",
    "design",
    "design-reviews",
    "engineering",
    "general",
    "launches",
    "support",
  ]

  function searchChannels(query: string, { signal }: { signal: AbortSignal }) {
    return new Promise<string[]>((resolve, reject) => {
      const timer = setTimeout(
        () =>
          resolve(
            channels.filter((channel) => channel.includes(query.toLowerCase()))
          ),
        400
      )
      signal.addEventListener("abort", () => {
        clearTimeout(timer)
        reject(signal.reason)
      })
    })
  }

  const triggers: TriggerDefinition[] = [
    { char: "@", items: people },
    { char: "/", boundary: "start", items: commands },
    { char: "#", items: searchChannels },
  ]
</script>

<TriggerMenu {triggers}>
  <Field>
    <FieldLabel>Message</FieldLabel>
    <FieldControl>
      {#snippet render({ props })}
        <TriggerMenuInput {...props} placeholder="Type @, / or #…" />
      {/snippet}
    </FieldControl>
  </Field>
</TriggerMenu>
```

输入 @ 找人，在开头输入 / 找命令，或输入 # 加载频道。

## 带参数的命令
`boundary: "start"` 的触发器只在文本开头匹配，所以前面加一个空格就能跳出它。带 `arguments` 的条目会按顺序询问每个参数：`TriggerMenuHint` 在光标处显示还剩哪些，Tab 接受高亮的建议并移到下一个参数，只剩可选参数时 Enter 完成，Backspace 越过某个参数的起点则返回上一个。没有 `items` 的参数是自由文本。`after: "submit"` 在条目插入后发送表单。

```svelte title="commands.svelte"
<script lang="ts">
  import { Field, FieldControl, FieldLabel } from "@ui-sdk/svelte/field"
  import {
    TriggerMenu,
    TriggerMenuHint,
    TriggerMenuInput,
  } from "@ui-sdk/svelte/trigger-menu"
  import { useLog } from "./log"

  const commands = [
    {
      value: "status",
      label: "status",
      arguments: [
        {
          name: "status",
          hint: "<status>",
          required: true,
          items: ["available", "busy", "away"],
        },
        {
          name: "until",
          hint: "[until]",
          items: ["30m", "1h", "4h", "today"],
          allowCustomValue: false,
        },
      ],
    },
    {
      value: "search",
      label: "search",
      arguments: [{ name: "query", hint: "<query>", required: true }],
    },
    { value: "away", label: "away", after: "submit" as const },
    { value: "clear", label: "clear" },
  ]

  const log = useLog()
</script>

<form
  data-slot="stack"
  onsubmit={(event) => {
    event.preventDefault()
    log(`Sent ${new FormData(event.currentTarget).get("message")}`)
  }}
>
  <TriggerMenu
    triggers={[
      { char: "/", boundary: "start", type: "command", items: commands },
    ]}
    onSelect={(value, details) =>
      log(
        ["Chose", `/${value}`, ...Object.values(details.arguments)].join(" ")
      )}
  >
    <Field name="message">
      <FieldLabel>Message</FieldLabel>
      <FieldControl>
        {#snippet render({ props })}
          <TriggerMenuInput {...props} placeholder="Type / for commands…" />
        {/snippet}
      </FieldControl>
    </Field>
    <TriggerMenuHint />
  </TriggerMenu>
</form>
```

输入 /status，然后按 Tab 选择状态和一个可选时间，按 Enter 完成。选择 /away 会立即发送。控制台会记录每条命令。

## 图标
把条目的图标放进 `TriggerMenuItemIcon`，放在它的文本之前。屏幕阅读器会跳过它，过滤和选项插入的文本也会忽略它，所以 SVG 的 `<title>`、图标字体的字形或 emoji 都不会混进条目的名称或字段。以数据形式提供的条目没有图标，所以要显示图标时就自己组合条目。

- **有方向性的图标**，比如箭头和回复，在从右到左的文本中用 `mirror` 翻转。
- **只有图标的条目** 需要 `aria-label`，过滤也会匹配它。在开发环境中，没有名称的条目会发出警告。
- **对齐条目。** 带图标的条目会得到 `data-has-icon`，只要有任何条目带图标，列表就得到 `data-has-icons`，这样没有图标的条目可以用内边距留出同样的空间。

```svelte title="icons.svelte"
<script lang="ts">
  import {
    ClockIcon,
    ReplyIcon,
    SearchIcon,
    ShareIcon,
    TrashIcon,
  } from "@lucide/svelte"
  import { Field, FieldControl, FieldLabel } from "@ui-sdk/svelte/field"
  import {
    TriggerMenu,
    TriggerMenuContent,
    TriggerMenuInput,
    TriggerMenuItem,
    TriggerMenuItemIcon,
    TriggerMenuList,
  } from "@ui-sdk/svelte/trigger-menu"

  const commands = [
    { value: "reply", icon: ReplyIcon, mirror: true },
    { value: "remind", icon: ClockIcon },
    { value: "search", icon: SearchIcon },
    { value: "share", icon: ShareIcon },
    { value: "clear", icon: TrashIcon },
  ]
</script>

<TriggerMenu triggers={[{ char: "/", boundary: "start", type: "command" }]}>
  <Field>
    <FieldLabel>Message</FieldLabel>
    <FieldControl>
      {#snippet render({ props })}
        <TriggerMenuInput {...props} placeholder="Type / for commands…" />
      {/snippet}
    </FieldControl>
  </Field>
  <TriggerMenuContent>
    <TriggerMenuList>
      {#each commands as command (command.value)}
        <TriggerMenuItem value={command.value}>
          <TriggerMenuItemIcon mirror={command.mirror}>
            <command.icon />
          </TriggerMenuItemIcon>
          {command.value}
        </TriggerMenuItem>
      {/each}
    </TriggerMenuList>
  </TriggerMenuContent>
</TriggerMenu>
```

输入 / 打开命令，然后输入 re 收窄它们。每个图标都在名称之前，过滤会忽略它。

## 加载条目
触发器的 `items` 可以是加载函数，输入停顿后会用查询和 `AbortSignal` 调用。更新的查询会中止更早的加载，所以只有它的结果会被采用，下一批加载期间上一次的结果会保留。`TriggerMenuStatus` 和 `TriggerMenuEmpty` 会得到 `loading`，加载运行时 `aria-busy` 会标记列表，这样你可以淡出即将变化的结果。

```svelte title="async.svelte"
<script lang="ts">
  import { Field, FieldControl, FieldLabel } from "@ui-sdk/svelte/field"
  import {
    type TriggerMenuDataItem,
    TriggerMenu,
    TriggerMenuContent,
    TriggerMenuEmpty,
    TriggerMenuInput,
    TriggerMenuItem,
    TriggerMenuList,
    TriggerMenuStatus,
  } from "@ui-sdk/svelte/trigger-menu"

  const channels = [
    "announcements",
    "design",
    "design-reviews",
    "engineering",
    "general",
    "launches",
    "support",
  ]

  function searchChannels(query: string, { signal }: { signal: AbortSignal }) {
    return new Promise<{ value: string; label: string }[]>(
      (resolve, reject) => {
        const timer = setTimeout(
          () =>
            resolve(
              channels
                .filter((channel) => channel.includes(query.toLowerCase()))
                .map((channel) => ({ value: channel, label: channel }))
            ),
          600
        )
        signal.addEventListener("abort", () => {
          clearTimeout(timer)
          reject(signal.reason)
        })
      }
    )
  }
</script>

<TriggerMenu triggers={[{ char: "#", type: "channel", items: searchChannels }]}>
  <Field>
    <FieldLabel>Message</FieldLabel>
    <FieldControl>
      {#snippet render({ props })}
        <TriggerMenuInput {...props} placeholder="Type # to link a channel…" />
      {/snippet}
    </FieldControl>
  </Field>
  <TriggerMenuContent>
    <TriggerMenuStatus>
      {#snippet children(state)}
        {state.loading
          ? "Loading channels…"
          : state.count
            ? `${state.count} ${state.count === 1 ? "channel" : "channels"}`
            : ""}
      {/snippet}
    </TriggerMenuStatus>
    <TriggerMenuEmpty>
      {#snippet children(state)}
        {#if state.empty && !state.loading}No channels match “{state.query}”{/if}
      {/snippet}
    </TriggerMenuEmpty>
    <TriggerMenuList>
      {#snippet children(state)}
        {#each state.items as TriggerMenuDataItem[] as item (item.value)}
          <TriggerMenuItem value={item.value} label={item.label}>
            {item.label}
          </TriggerMenuItem>
        {/each}
      {/snippet}
    </TriggerMenuList>
  </TriggerMenuContent>
</TriggerMenu>
```

输入 # 和频道名。列表会提示正在加载，加载新结果时旧结果会淡出。

## 自定义条目
用任意内容组合 `TriggerMenuItem`，可以放在分组里。`label` 是被匹配和插入的内容，`keywords` 增加可匹配的词，`disabled` 让条目留在列表里但不能被选中。触发器的 `spaces`、`pattern` 和 `maxLength` 决定查询可以包含什么，`filter` 决定它如何收窄条目，`insert` 决定用什么替换触发器和查询。条目自己的 `onSelect` 先运行，可以用 `details.insert()` 插入别的内容。

```svelte title="custom-items.svelte"
<script lang="ts">
  import { UsersIcon } from "@lucide/svelte"
  import { Field, FieldControl, FieldLabel } from "@ui-sdk/svelte/field"
  import {
    TriggerMenu,
    TriggerMenuContent,
    TriggerMenuGroup,
    TriggerMenuGroupLabel,
    TriggerMenuInput,
    TriggerMenuItem,
    TriggerMenuItemIcon,
    TriggerMenuList,
    TriggerMenuSeparator,
  } from "@ui-sdk/svelte/trigger-menu"

  const people = [
    { value: "hollis", label: "Hollis Grant" },
    { value: "ines", label: "Inès Moreau" },
    { value: "kofi", label: "Kofi Mensah" },
    { value: "wren", label: "Wren Takahashi" },
    { value: "tomasz", label: "Tomasz Wójcik", disabled: true },
  ]
</script>

<TriggerMenu
  triggers={[
    {
      char: "@",
      spaces: 2,
      maxLength: 30,
      pattern: /[\p{L}.'-]/u,
      filter: "startsWith",
      insert: (item) => `@${item.label.split(" ")[0]} `,
    },
  ]}
>
  <Field>
    <FieldLabel>Message</FieldLabel>
    <FieldControl>
      {#snippet render({ props })}
        <TriggerMenuInput {...props} placeholder="Type @ and a first name…" />
      {/snippet}
    </FieldControl>
  </Field>
  <TriggerMenuContent>
    <TriggerMenuList>
      <TriggerMenuGroup>
        <TriggerMenuGroupLabel>People</TriggerMenuGroupLabel>
        {#each people as person (person.value)}
          <TriggerMenuItem
            value={person.value}
            label={person.label}
            disabled={person.disabled}
          >
            {person.label}
            <span data-slot="hint"
              >{person.disabled ? "Deactivated" : `@${person.value}`}</span
            >
          </TriggerMenuItem>
        {/each}
      </TriggerMenuGroup>
      <TriggerMenuSeparator />
      <TriggerMenuItem
        value="here"
        label="here"
        keywords={["everyone", "channel"]}
        onSelect={(value, details) => details.insert("@here ")}
      >
        <TriggerMenuItemIcon>
          <UsersIcon />
        </TriggerMenuItemIcon>
        Notify everyone here
      </TriggerMenuItem>
    </TriggerMenuList>
  </TriggerMenuContent>
</TriggerMenu>
```

输入 @ 和名字的开头来插入这个人，或选择 Notify everyone here 插入 @here。停用的人不能被选中。

## 输入框
把输入部件渲染成 `<input>` 来使用单行。它是一个带 `aria-expanded` 的组合框。在单行里，Enter 常常会提交表单，所以这个示例设置了 `autoHighlight={false}`：只有方向键高亮了某个人之后，Enter 才会选择；`loop={false}` 让方向键在列表两端停住。

```svelte title="input.svelte"
<script lang="ts">
  import { Field, FieldControl, FieldLabel } from "@ui-sdk/svelte/field"
  import {
    type TriggerMenuDataItem,
    TriggerMenu,
    TriggerMenuContent,
    TriggerMenuInput,
    TriggerMenuItem,
    TriggerMenuList,
  } from "@ui-sdk/svelte/trigger-menu"

  const people = [
    { value: "hollis", label: "Hollis Grant" },
    { value: "ines", label: "Inès Moreau" },
    { value: "kofi", label: "Kofi Mensah" },
    { value: "wren", label: "Wren Takahashi" },
    { value: "tomasz", label: "Tomasz Wójcik" },
  ]
</script>

<TriggerMenu
  triggers={[{ char: "@", items: people }]}
  autoHighlight={false}
  loop={false}
>
  <Field>
    <FieldLabel>Task</FieldLabel>
    <FieldControl>
      {#snippet render({ props })}
        <TriggerMenuInput {...props} placeholder="Type @ to assign someone…">
          {#snippet render({ props })}
            <input {...props} />
          {/snippet}
        </TriggerMenuInput>
      {/snippet}
    </FieldControl>
  </Field>
  <TriggerMenuContent>
    <TriggerMenuList>
      {#snippet children(state)}
        {#each state.items as TriggerMenuDataItem[] as item (item.value)}
          <TriggerMenuItem value={item.value} label={item.label}>
            {item.label}
          </TriggerMenuItem>
        {/each}
      {/snippet}
    </TriggerMenuList>
  </TriggerMenuContent>
</TriggerMenu>
```

在空任务里输入 @。在你按 ArrowDown 之前没有任何条目高亮，之后按 Enter 会指派这个人。

## 定位
默认情况下，列表在光标处、触发器的下方打开，放不下时会翻转以留在屏幕内。`side`、`align` 和各个偏移量决定它的位置，`anchor` 让它贴着另一个元素定位。这个示例把列表开在整个字段的上方，让它的条目与标签对齐，并用 `container` 把它渲染在字段内部。

```svelte title="positioning.svelte"
<script lang="ts">
  import { Field, FieldControl, FieldLabel } from "@ui-sdk/svelte/field"
  import {
    type TriggerMenuDataItem,
    TriggerMenu,
    TriggerMenuContent,
    TriggerMenuInput,
    TriggerMenuItem,
    TriggerMenuList,
  } from "@ui-sdk/svelte/trigger-menu"

  const people = [
    { value: "hollis", label: "Hollis Grant" },
    { value: "ines", label: "Inès Moreau" },
    { value: "kofi", label: "Kofi Mensah" },
    { value: "wren", label: "Wren Takahashi" },
    { value: "tomasz", label: "Tomasz Wójcik" },
  ]

  let field: HTMLElement | undefined = $state()
</script>

<TriggerMenu triggers={[{ char: "@", items: people }]}>
  <Field
    {@attach (element) => {
      field = element
    }}
  >
    <FieldLabel>Comment</FieldLabel>
    <FieldControl>
      {#snippet render({ props })}
        <TriggerMenuInput {...props} placeholder="Type @ to mention someone…" />
      {/snippet}
    </FieldControl>
  </Field>
  <TriggerMenuContent
    side="top"
    align="start"
    sideOffset={8}
    alignOffset={-5}
    collisionPadding={16}
    anchor={field}
    container={field}
    keepMounted
  >
    <TriggerMenuList>
      {#snippet children(state)}
        {#each state.items as TriggerMenuDataItem[] as item (item.value)}
          <TriggerMenuItem value={item.value} label={item.label}>
            {item.label}
          </TriggerMenuItem>
        {/each}
      {/snippet}
    </TriggerMenuList>
  </TriggerMenuContent>
</TriggerMenu>
```

在评论里输入 @。列表在字段上方打开，与它的标签对齐。

## 受控
用 `bind:open` 绑定 `open`，自己持有浮层状态，并在 `onOpenChange` 中读取每次变更。详情会说明它为什么变化。`onQueryChange` 报告触发器后面的文本和正在输入的参数，`onOpenChangeComplete` 在菜单完成打开或关闭后运行。Escape 会关闭匹配项，`shortcut` 可以重新打开它，默认是 Control+Space。

```svelte title="controlled.svelte"
<script lang="ts">
  import { Field, FieldControl, FieldLabel } from "@ui-sdk/svelte/field"
  import { TriggerMenu, TriggerMenuInput } from "@ui-sdk/svelte/trigger-menu"
  import { useLog } from "./log"

  const people = [
    { value: "hollis", label: "Hollis Grant" },
    { value: "ines", label: "Inès Moreau" },
    { value: "kofi", label: "Kofi Mensah" },
    { value: "wren", label: "Wren Takahashi" },
    { value: "tomasz", label: "Tomasz Wójcik" },
  ]

  const commands = [
    {
      value: "status",
      label: "status",
      arguments: [
        {
          name: "status",
          hint: "<status>",
          required: true,
          items: ["available", "busy", "away"],
        },
      ],
    },
  ]

  const log = useLog()
  let open = $state(false)
</script>

<TriggerMenu
  triggers={[
    { char: "@", items: people },
    { char: "/", boundary: "start", items: commands },
  ]}
  bind:open
  onOpenChange={(next, details) =>
    log(`${next ? "Opening" : "Closing"} (${details.reason})`)}
  onOpenChangeComplete={(next) => log(next ? "Open" : "Closed")}
  onQueryChange={(query, details) =>
    log(
      `Query “${query}”${details.argument ? ` for ${details.argument}` : ""}`
    )}
  shortcut="ctrl+j"
>
  <Field>
    <FieldLabel>Message</FieldLabel>
    <FieldControl>
      {#snippet render({ props })}
        <TriggerMenuInput {...props} placeholder="Type @ or /…" />
      {/snippet}
    </FieldControl>
  </Field>
</TriggerMenu>
```

输入 @ 和一个名字，按 Escape，然后按 Control+J 重新打开列表。控制台会记录每个回调及其原因。

## 控制器
用 `createTriggerMenuController()` 创建控制器，并作为 `controller` 传入，用来打开建议、在光标处插入文本，或读取当前的匹配项。`open()` 会在光标处输入触发器，并返回一个在菜单关闭时兑现的 Promise。

```svelte title="controller.svelte"
<script lang="ts">
  import { Field, FieldControl, FieldLabel } from "@ui-sdk/svelte/field"
  import {
    type TriggerMenuDataItem,
    TriggerMenu,
    TriggerMenuContent,
    TriggerMenuInput,
    TriggerMenuItem,
    TriggerMenuList,
    createTriggerMenuController,
  } from "@ui-sdk/svelte/trigger-menu"
  import { useLog } from "./log"

  const people = [
    { value: "hollis", label: "Hollis Grant" },
    { value: "ines", label: "Inès Moreau" },
    { value: "kofi", label: "Kofi Mensah" },
    { value: "wren", label: "Wren Takahashi" },
    { value: "tomasz", label: "Tomasz Wójcik" },
  ]

  const log = useLog()
  const menu = createTriggerMenuController()

  async function mention() {
    const closed = await menu.open({ trigger: "@" })
    log(`Closed (${closed.reason})`)
  }
</script>

<div data-slot="stack">
  <div data-slot="controls">
    <button
      type="button"
      onmousedown={(event) => event.preventDefault()}
      onclick={mention}>Mention</button
    >
    <button
      type="button"
      onmousedown={(event) => event.preventDefault()}
      onclick={() =>
        menu.insert(
          new Date().toLocaleDateString("en-US", {
            month: "long",
            day: "numeric",
          })
        )}
    >
      Insert Date
    </button>
  </div>
  <TriggerMenu controller={menu} triggers={[{ char: "@", items: people }]}>
    <Field>
      <FieldLabel>Message</FieldLabel>
      <FieldControl>
        {#snippet render({ props })}
          <TriggerMenuInput {...props} placeholder="Write a message…" />
        {/snippet}
      </FieldControl>
    </Field>
    <TriggerMenuContent>
      <TriggerMenuList>
        {#snippet children(state)}
          {#each state.items as TriggerMenuDataItem[] as item (item.value)}
            <TriggerMenuItem value={item.value} label={item.label}>
              {item.label}
            </TriggerMenuItem>
          {/each}
        {/snippet}
      </TriggerMenuList>
    </TriggerMenuContent>
  </TriggerMenu>
</div>
```

按 Mention 并选择一个人。控制台会记录列表关闭的原因。Insert Date 会在光标处加入今天的日期。

## 任意编辑器
传入 `editor`，把菜单连接到你自己渲染的字段，或另一个编辑器。`textFieldAdapter()` 可以为文本域或输入框创建一个。

```svelte title="editor.svelte"
<script lang="ts">
  import { Field, FieldControl, FieldLabel } from "@ui-sdk/svelte/field"
  import {
    type TriggerMenuDataItem,
    TriggerMenu,
    TriggerMenuContent,
    TriggerMenuItem,
    TriggerMenuList,
    textFieldAdapter,
  } from "@ui-sdk/svelte/trigger-menu"

  const people = [
    { value: "hollis", label: "Hollis Grant" },
    { value: "ines", label: "Inès Moreau" },
    { value: "kofi", label: "Kofi Mensah" },
    { value: "wren", label: "Wren Takahashi" },
    { value: "tomasz", label: "Tomasz Wójcik" },
  ]

  let field: HTMLTextAreaElement | undefined = $state()
  const editor = $derived(field ? textFieldAdapter(field) : undefined)
</script>

<TriggerMenu {editor} triggers={[{ char: "@", items: people }]}>
  <Field>
    <FieldLabel>Notes</FieldLabel>
    <FieldControl>
      {#snippet render({ props })}
        <textarea
          bind:this={field}
          {...props}
          placeholder="Type @ to mention someone…"></textarea>
      {/snippet}
    </FieldControl>
  </Field>
  <TriggerMenuContent>
    <TriggerMenuList>
      {#snippet children(state)}
        {#each state.items as TriggerMenuDataItem[] as item (item.value)}
          <TriggerMenuItem value={item.value} label={item.label}>
            {item.label}
          </TriggerMenuItem>
        {/each}
      {/snippet}
    </TriggerMenuList>
  </TriggerMenuContent>
</TriggerMenu>
```

在备注（一个通过编辑器适配器连接的文本域）里输入 @，并选择一个人。

为其他编辑器编写的适配器会读取它的文本和选区，测量某个偏移处的矩形，替换一段范围，作为一步撤销，并报告变更。不是用户做出的变更要用 `user: false` 报告，比如协作者的变更，菜单就不会为它们打开。

- `element` (`HTMLElement`): The focused element that gets keys and the menu's ARIA. Undefined until it's in the page.
- `textBefore` (`(length: number) => { text: string; offset: number; } | null`): Up to `length` characters before the caret, and the offset they start at. A token reads as U+FFFC.
- `selection` (`() => TextRange | null`): The selection as text offsets, or null while unfocused.
- `rectAt` (`(offset: number) => TextRect | null`): The rectangle at a text offset, for anchoring.
- `replace` (`(range: TextRange, content: string | TokenInsert, options?: EditorReplaceOptions) => void`): Replaces a range with text or a token as one undoable step, and puts the caret after it.
- `subscribe` (`(listener: (change: EditorChange) => void) => () => void`): Calls `listener` for text edits, caret moves and composition. Returns a cleanup.
- `composing` (`() => boolean`): Whether an input method is composing.
- `tokens?` (`boolean`): Whether `replace` accepts tokens.
- `submit?` (`((event?: Event) => void)`): Sends what's typed, like a form submit, for items that end with `after: "submit"`.

## 撤销
选择条目会保留原生文本字段的撤销历史。按 Command+Z 或 Control+Z 可以恢复查询。Safari 可能把插入和之前的输入合并成一步撤销。

自定义编辑器适配器必须让每次替换成为一步撤销。[Token Input](/docs/svelte/components/token-input) 自己管理 token 历史。

## 自定义渲染
每个部件都接受 `render` snippet。把 `TriggerMenuInput` 渲染成 `<input>`，就像输入示例那样，或通过另一个组件渲染，比如 `FieldControl`，这里的每个示例都这样做来加入 [Field](/docs/svelte/components/field)。[部件与组合](https://ui-sdk.cn/docs/svelte/parts-and-composition#choose-the-element)介绍了 props 如何合并，每个部件的状态列在[状态](https://ui-sdk.cn/docs/svelte/components/trigger-menu#state)下。

## 样式
为字段、浮层和它的条目设置样式。内容会显示 `data-trigger`，所以每个触发器的列表可以长得不一样，比如用等宽字体显示命令。条目会显示 `data-highlighted` 和 `data-disabled`，在包含 `TriggerMenuItemIcon` 时显示 `data-has-icon`；只要有任何条目带图标，列表就显示 `data-has-icons`。用 `aria-busy` 让加载中的列表淡出，并把提示样式设为幽灵文本（ghost text）：它的位置会替你放在光标处。

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

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

## 数据属性
### TriggerMenuInput
`[data-slot="trigger-menu-input"]`

- `data-closed`: Present while the list is closed, including while it animates out.
- `data-open`: Present while the list is open.
- `data-trigger`: The trigger of the current match, like `@`, while there is one.

### TriggerMenuContent
`[data-slot="trigger-menu-content"]`

- `data-closed`: Present while the list is closed, including while it animates out.
- `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 list ended up, after flipping away from edges.
- `data-align` (`start`, `center`, `end`): How the list lines up with the trigger.
- `data-open`: Present while the list is open.
- `data-trigger`: The trigger of the current match, like `@`, while there is one.
- `data-has-icons`: Present while any item inside holds an icon part, so items without one can line up.

### TriggerMenuItem
`[data-slot="trigger-menu-item"]`

- `data-disabled`: Present when the item can't be chosen.
- `data-highlighted`: Present on the highlighted item. Focus stays in the field.
- `data-has-icon`: Present on an item while it holds an icon part.

### TriggerMenuEmpty
`[data-slot="trigger-menu-empty"]`

- `data-empty`: Present while no item matches.
- `data-loading`: Present while items load.

### TriggerMenuItemIcon
`[data-slot="trigger-menu-item-icon"]`

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

## API 参考
属性和回调与下面相同，都作为 Svelte props。`open` 可以用 `bind:open` 绑定。

### TriggerMenu
- `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.
- `triggers` (`TriggerDefinition<T>[]`): The texts that open the menu, and what each one lists.
- `editor?` (`TextEditorAdapter`): The editor the menu reads and writes, for editors without a part of their own, like Tiptap. TriggerMenuInput and a surrounding TokenInput set it for you.
- `open?` (`boolean`): Whether the menu is open. Pass it to control it; it shows only while there's a match.
- `onOpenChange?` (`((open: boolean, details: ChangeDetails<TriggerMenuOpenChangeReason> & { trigger: string | null; }) => void)`): Runs when the menu wants to open or close. `details.reason` says why, `details.trigger` which trigger, and `details.cancel()` stops it.
- `onOpenChangeComplete?` (`((open: boolean) => void)`): Runs once the menu has finished opening or closing, after any animation.
- `onQueryChange?` (`((query: string, details: ChangeDetails<TriggerMenuQueryChangeReason> & { trigger: string; argument?: string; }) => void)`): Runs when the text after the trigger changes. Read-only: it's the editor's text. `details.argument` names the argument being typed.
- `onSelect?` (`((value: T, details: TriggerMenuSelectDetails<T>) => void | Promise<void | Partial<TokenInsert>>)`): Runs when an item, with every required argument, is chosen. The default insertion follows unless `details.preventDefault()`. Return a Promise and a token is inserted at once as pending, updated with what it resolves to and removed if it rejects; the menu closes either way.
- `pendingAnnouncement?` (`string`): What screen readers hear once an `onSelect` Promise has been pending for a second, so a slow action doesn't pass in silence. Set it in the page's language. An empty string says nothing.
- `status?` (`AsyncOptionsStatus`): Whether items that come from outside are loading or failed, for the status and empty parts. Loaders report their own.
- `autoHighlight?` (`boolean`): Whether the first match is highlighted so Enter and Tab choose it. Visual only: screen readers hear about it once an arrow key moves the highlight, so typed characters keep being echoed.
- `loop?` (`boolean`): Whether arrow keys wrap from the last item to the first.
- `shortcut?` (`string`): Reopens a match dismissed with Escape, with the caret in it.
- `controller?` (`object`): Opens, closes and inserts from anywhere. Create one with `createTriggerMenuController()`.
- `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?` (`((details: { reason: "escape-key"; event?: KeyboardEvent | undefined; } | { reason: "outside-press"; event?: MouseEvent | undefined; }) => void)`): 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.

### 触发器
- `char` (`string`): The text that starts a match: `"@"`, `"/"`, `"#"`, or several characters like `"[["`.
- `boundary?` (`TriggerBoundary`): Where a match may start.
- `spaces?` (`number | boolean`): Whether the query may contain spaces, or up to how many words, like `@next Wednesday`.
- `pattern?` (`RegExp`): Characters a query may contain, tested one at a time.
- `maxLength?` (`number`): The longest query before the match ends.
- `type?` (`string`): The kind of token choosing an item inserts, where the editor takes tokens.
- `items?` (`TriggerItemsLoader<T> | TriggerMenuData<T>`): Suggestions as data, or a loader given the query and an AbortSignal. Without them, the composed items show.
- `filter?` (`ListFilter<T>`): How typing narrows data items. Loaded items aren't filtered.
- `insert?` (`((item: TriggerMenuDataItem<T>, details: { match: TriggerMatch; arguments: Record<string, string>; }) => string | TokenInsert)`): What replaces the trigger and query. Defaults to a token where the editor takes tokens, else the trigger, the label and a space.

### 以数据形式提供的条目
- `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.
- `after?` (`TriggerAfter`): After choosing it: `"compose"` closes the menu, `"continue"` keeps it open and lists the same trigger's items for the text typed after it, and `"submit"` asks the editor to send. Tab never submits.
- `arguments?` (`TriggerArgument[]`): Typed arguments asked for in order once it's chosen, like `/model <name>`.

### 参数
- `name` (`string`): The name it's reported under in `details.arguments`.
- `hint?` (`string`): Ghost text shown at the caret until it's typed. Defaults to `<name>`.
- `required?` (`boolean`): Whether Enter can finish the command without it.
- `items?` (`TriggerItemsLoader<string> | TriggerMenuData<string>`): Suggestions for it, as data or a loader. Without them, it's free text and no list shows.
- `allowCustomValue?` (`boolean`): Whether text that matches no suggestion is accepted, like a combobox's custom value.

### TriggerMenuInput
菜单向其提供建议的字段。渲染一个 `textarea`，或通过 `render` 渲染一个 `input`。

### TriggerMenuStatus
一个礼貌的状态区域（polite live region），在输入停顿后播报数量和按键。传入 `children` snippet 可以播报别的内容。渲染一个 `div`。

### TriggerMenuContent
- `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 trigger the list opens on.
- `align?` (`Align`): How the popup lines up with the anchor along that side. `start` and `end` follow the reading direction. How the list lines up with the trigger along that side.
- `sideOffset?` (`number`): Gap between the anchor and the popup, in pixels. Gap between the line of text and the list, in pixels.
- `alignOffset?` (`number`): Shift along the anchor, in pixels. Shift along the text, 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 list stays in the page, hidden, while closed.

### TriggerMenuEmpty
在没有条目匹配时显示。渲染它会让菜单在没有匹配时保持打开；不渲染它，菜单会一直关闭，直到有内容匹配。渲染一个 `div`。

### TriggerMenuList
列表框（listbox）。没有 children 时，它渲染当前触发器的条目。渲染一个 `div`。

### TriggerMenuItem
- `value` (`T`): What `onSelect` receives when the item is chosen.
- `label?` (`string`): The text inserted and matched, when the content isn't plain text.
- `keywords?` (`string[]`): More words filtering matches.
- `disabled?` (`boolean`): Keeps the item from being chosen. It can still be highlighted, as the listbox pattern asks.
- `onSelect?` (`((value: T, details: TriggerMenuSelectDetails<T>) => void | Promise<void | Partial<TokenInsert>>)`): Runs before the menu's `onSelect`. `details.preventDefault()` skips the default insertion.

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

### TriggerMenuGroup 与 TriggerMenuGroupLabel
一组条目，由它的标签命名。各自渲染一个 `div`。

### TriggerMenuSeparator
条目或分组之间的一条线，对屏幕阅读器隐藏。渲染一个 `div`。

### TriggerMenuHint
光标处的幽灵文本，显示还要输入的参数，比如 `<status>`。渲染一个 `span`，对屏幕阅读器隐藏。

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

`TriggerMenuInput`：

- `open` (`boolean`): Whether the menu is open. It opens on a typed trigger, and closes when nothing matches unless it's loading or renders an empty part.
- `trigger` (`string | null`): The trigger of the current match, like `"@"`, or null.

`TriggerMenuContent` and `TriggerMenuList`:

- `open` (`boolean`): Whether the menu is open. False while it animates out.
- `trigger` (`string | null`): The trigger of the current match, like `"@"`, or null.
- `query` (`string`): The text after the trigger, or after the current argument's start.
- `argument` (`string | null`): The argument being typed, by name, or null at the first level.
- `status` (`AsyncOptionsStatus`): Whether items are loading or failed.
- `items` (`TriggerMenuData<unknown>`): The visible data items, for rendering them yourself.

`TriggerMenuItem`:

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

`TriggerMenuItemIcon`:

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

`TriggerMenuEmpty`:

- `loading` (`boolean`): Whether items are loading.
- `empty` (`boolean`): Whether no item matches.
- `query` (`string`): The text after the trigger.

`TriggerMenuStatus`:

- `open` (`boolean`): Whether the menu is open. It opens on a typed trigger, and closes when nothing matches unless it's loading or renders an empty part.
- `status` (`AsyncOptionsStatus`): Whether items are loading or failed.
- `loading` (`boolean`): Whether items are loading.
- `count` (`number`): How many items match.
- `argument` (`string | null`): The argument being typed, by name, or null.

`TriggerMenuHint`:

- `argument` (`string | null`): The argument being typed, by name, or null.
- `hint` (`string`): The ghost text: the hints of the arguments still to type.

### 原因
`details.reason` 说明菜单为什么打开或关闭。

- `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.
- `caret-move` (`PointerEvent | Event | KeyboardEvent`): The caret left a trigger menu's match: an arrow key, Home or End, a click, or a selection change.
- `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).
- `close-press` (`MouseEvent | KeyboardEvent | SubmitEvent`): A Close part was pressed, or a form with `method="dialog"` was submitted.
- `outside-press` (`MouseEvent`): A press outside the layer.
- `focus-out` (`KeyboardEvent | FocusEvent`): Focus left the layer, or Tab moved it out.
- `window-blur` (`FocusEvent`): The window lost focus.
- `anchor-hidden` (`none`): The element the popup sits beside stopped rendering, like a trigger a breakpoint hides.
- `imperative` (`none`): A controller or `api` call.
- `shortcut` (`KeyboardEvent`): A keyboard shortcut, like a trigger's `shortcut`.

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

查询为什么变化：

- `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.
- `imperative` (`none`): A controller or `api` call.

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

- `isOpen()` (`() => boolean`): Whether the menu is open.
- `setOpen(open, options?)` (`(open: boolean, options?: TriggerMenuChangeOptions<TriggerMenuOpenChangeReason> | undefined) => boolean`): Opens or closes the menu. Opening needs a match; see `open()` for one that types the trigger. Returns false when the change was canceled or it was already open or closed.
- `open(options?)` (`(options?: (TriggerMenuChangeOptions<TriggerMenuOpenChangeReason> & { trigger?: string | undefined; signal?: AbortSignal | undefined; }) | undefined) => Promise<...>`): Opens the menu for `trigger`, typing it at the caret first unless a match for it is already there, and resolves once it closes. Resolves exactly once and never rejects.
- `close(options?)` (`(options?: TriggerMenuChangeOptions<TriggerMenuOpenChangeReason> | undefined) => boolean`): Closes the menu. The match isn't dismissed, so typing in it opens it again. Returns false when the close was canceled or it was already closed.
- `getQuery()` (`() => string`): The text after the trigger, or after the current argument's start. Empty while closed.
- `getMatch()` (`() => TriggerMatch | null`): The current match, or null.
- `insert(content)` (`(content: string | Token) => void`): Replaces the current match with text or a token, or inserts at the caret without one.
- `focus()` (`() => void`): Moves focus to the editor.

### 事件
回调先收到新状态，然后收到详情。只有 `onOpenChange` 没有被取消时，绑定的 `open` 才会更新。

| 属性                   | 所属                             | 收到                                                                         |
| ---------------------- | -------------------------------- | ---------------------------------------------------------------------------- |
| `bind:open`            | `TriggerMenu`                    | 菜单是否打开                                                                 |
| `onOpenChange`         | `TriggerMenu`                    | `(open, details)`：新状态、[原因](https://ui-sdk.cn/docs/svelte/components/trigger-menu#reasons) 和 `trigger`                     |
| `onOpenChangeComplete` | `TriggerMenu`                    | `(open)`，在动画之后                                                         |
| `onQueryChange`        | `TriggerMenu`                    | `(query, details)`：触发器后面的文本，以及正在输入的 `argument`              |
| `onDismissAttempt`     | `TriggerMenu`                    | `({ reason, event })`，在关闭尝试被拒绝时                                    |
| `onSelect`             | `TriggerMenu`, `TriggerMenuItem` | `(value, details)`：条目、它的 `arguments`、`insert()` 和 `preventDefault()` |

当 `onSelect` 返回 Promise 且编辑器接受 token 时，token 会立即插入并带有 `data-pending`，用 Promise 兑现的值更新，被拒绝时移除。无论哪种情况菜单都会关闭，让人可以继续输入。

## 无障碍
方向键移动高亮时，焦点留在字段里。`<textarea>` 保持 textbox 角色，这是 ARIA 允许它使用的唯一角色，并用 `aria-controls` 指向列表，按过方向键后再用 `aria-activedescendant`。`<input>` 是带 `aria-expanded` 的组合框。数量和加载状态通过 `TriggerMenuStatus` 播报，它是一个礼貌的状态区域，绝不通过字段播报，所以一定要渲染一个：视觉上隐藏（如示例所示），或放在列表顶部（如[加载条目](https://ui-sdk.cn/docs/svelte/components/trigger-menu#loading-items)所示）。通过 [Field](/docs/svelte/components/field) 或 `aria-label` 给字段一个可见的名称。

### 键盘
| 按键                 | 作用                                                    |
| -------------------- | ------------------------------------------------------- |
| ArrowDown, ArrowUp   | 列表打开时移动高亮；光标留在字段里                      |
| Enter                | 选择高亮的条目。在命令的参数中，只剩可选参数时完成      |
| Tab                  | 选择高亮的条目，或接受一个参数并移到下一个              |
| Escape               | 关闭列表并关闭这次匹配，之后继续输入不会重新打开它      |
| Control+Space        | 重新打开已关闭的匹配，光标留在其中；`shortcut` 可以换键 |
| Backspace            | 越过某个参数的起点时，返回上一个参数                    |
| Command+Z, Control+Z | 撤销插入并恢复查询                                      |

### 经过测试的行为
下面每一行都是一个自动化测试。

**Opening**

- Typing a trigger opens the list with every item.
- A field controlled through onChange keeps the typed trigger and opens the list. React only.
- Typing after the trigger filters the list.
- Text an input method commits filters the list.
- Queries match Unicode letters and ignore accents.
- A trigger mid-word doesn't open.
- A trigger followed by a space doesn't open.
- A command trigger opens only at the start, so a leading space escapes it.
- The list opens at the trigger and stays there as the query grows.
- Pasting a trigger opens the list.
- Focusing a field that already has a match doesn't open the list.
- Moving the caret into a match doesn't open the list.
- A query that matches nothing closes the list, and Backspace that matches again opens it.
- With an empty part, a query that matches nothing keeps the list open with the message.
- With an empty part, Control+Space reopens a dismissed query that matches nothing.

**Choosing**

- The first match is highlighted, and Enter inserts it with a space.
- Tab accepts the highlighted suggestion and focus stays in the field.
- Arrow keys move the highlight, and wrap.
- A disabled item can be highlighted but not chosen.
- Clicking an item inserts it and keeps focus and the caret in the field.
- Text after the caret stays where it was.

**Dismissing**

- Escape closes the list, keeps the text and focus.
- A dismissed match stays closed through caret moves, typing in it and clicks.
- A new trigger after a dismissed one opens.
- Deleting and retyping the trigger opens it again.
- Ctrl+Space reopens a dismissed match.
- Moving the caret out of the match closes the list.
- Pressing outside closes the list.

**Arguments**

- A command with arguments asks for each one, and Enter finishes with them.
- Enter finishes once only optional arguments are left.
- A free-text argument shows no list, and Enter takes the typed text.
- Backspace past an argument's start goes back a level.
- Escape in an argument keeps the inserted text.
- An item that submits sends the form once inserted.

**Loading**

- Items load for the query.
- A newer query aborts the older load, and only its results land.

**Undo**

- Undo after choosing brings the query back, never a dead undo.

**Input**

- The SDK's Textarea works as the field, and undo still works.
- An <input> field works the same.

Runs in React、Vue 和 web components.

- No axe violations while closed.
- No axe violations while open with an item highlighted.
- No axe violations while open on an input.
- No axe violations with nothing found.
- A textarea stays a textbox, without aria-expanded, and controls the list while open.
- An input is a combobox that says whether it's expanded.
- Aria-activedescendant waits for an arrow key and clears on the next edit.
- Two menus on a page have their own ids, and the role never changes.
- Options are named by their text.
- The status says the count and the keys once typing pauses, then that nothing matches.
- The hint is hidden from assistive technology, and the status names the argument.
- Accessibility tree.

Runs in React、Vue 和 web components.
