# Token Input

输入文字，并混入文件、人员、标签等引用标记。

Token Input 是一个文本框，在文字之间存放标记，比如消息里提到的人，或者提示词附带的文件。每个标记都作为一个整体移动、删除和复制。

```svelte title="demo.svelte"
<script lang="ts">
  import { XIcon } from "@lucide/svelte"
  import { Field, FieldLabel } from "@ui-sdk/svelte/field"
  import {
    TokenInput,
    TokenInputEditor,
    TokenInputToken,
    TokenInputTokenRemove,
  } from "@ui-sdk/svelte/token-input"
  import {
    type TriggerMenuDataItem,
    TriggerMenu,
    TriggerMenuContent,
    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>

<Field>
  <FieldLabel>Message</FieldLabel>
  <TokenInput>
    {#snippet token(token)}
      <TokenInputToken>
        {token.label}
        <TokenInputTokenRemove>
          <XIcon aria-hidden="true" />
        </TokenInputTokenRemove>
      </TokenInputToken>
    {/snippet}
    <TokenInputEditor placeholder="Type @ to mention someone…" />
    <TriggerMenu triggers={[{ char: "@", type: "mention", items: people }]}>
      <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>
  </TokenInput>
</Field>
```

输入 @，用方向键和 Enter 选择一个人。用 Backspace 移除标记，或按压它的移除按钮。

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

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

```text
TokenInput
├── TokenInputEditor
└── TriggerMenu
```

每个标记则放在 `token` snippet 里：

```text
TokenInputToken
└── TokenInputTokenRemove
```

`TokenInput` 保存值，`TokenInputEditor` 是人们编辑的文字。它里面的 [Trigger Menu](/docs/svelte/components/trigger-menu) 在有人输入 `@`、`/` 或其他触发字符时建议标记。传入 `token` snippet 为每个标记提供你自己的渲染结构。

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

```svelte
<script lang="ts">
  import {
    TokenInput,
    TokenInputEditor,
    type TokenInputValue,
  } from "@ui-sdk/svelte/token-input"

  const draft: TokenInputValue = [
    "Explain ",
    { type: "file", value: "src/routes.ts", label: "routes.ts" },
  ]
</script>

<TokenInput defaultValue={draft}>
  <TokenInputEditor aria-label="Prompt" />
</TokenInput>
```

值是文字和标记组成的数组。每个标记有一个类型、一个供你的应用使用的值，以及一个供人阅读的标签。编辑器自己管理它的内容，包括标记、选择和撤销，所以让它渲染这些内容，自定义标记时用 `token` snippet。

## Token Input 还是 Trigger Menu
Token Input 保存文字和标记。[Trigger Menu](/docs/svelte/components/trigger-menu) 在有人输入触发字符时建议要插入的内容。

当你的代码提供标记时，单独使用 Token Input。需要建议时加上 Trigger Menu，就像上面的示例。Trigger Menu 也能配合普通输入框和文本域工作。

## 提示词输入
把文件建议、技能和发送动作组合在一起。这个示例在文件加载期间把它们标记为待处理，然后用 `updateToken()` 显示正在运行的技能。Enter 发送；Shift+Enter 换行。打开的建议菜单或正在使用的输入法优先于发送。

```svelte title="prompt-input.svelte"
<script lang="ts">
  import {
    ArrowUpIcon,
    CheckIcon,
    ClockIcon,
    CodeIcon,
    FileIcon,
    XIcon,
  } from "@lucide/svelte"
  import {
    createTokenInputController,
    toText,
    TokenInput,
    TokenInputEditor,
    TokenInputToken,
    TokenInputTokenRemove,
    type TokenInputValue,
  } from "@ui-sdk/svelte/token-input"
  import {
    type TriggerMenuDataItem,
    TriggerMenu,
    TriggerMenuContent,
    TriggerMenuEmpty,
    TriggerMenuHint,
    TriggerMenuItem,
    TriggerMenuList,
  } from "@ui-sdk/svelte/trigger-menu"
  import { onDestroy } from "svelte"
  import { useLog } from "./log"

  const files = [
    { value: "src/app.tsx", label: "app.tsx", keywords: ["src"] },
    { value: "src/routes.ts", label: "routes.ts", keywords: ["src"] },
    { value: "src/styles.css", label: "styles.css", keywords: ["src"] },
    { value: "README.md", label: "README.md" },
    { value: "package.json", label: "package.json" },
  ]

  const skills = [
    {
      value: "search",
      label: "search",
      arguments: [{ name: "query", hint: "<query>", required: true }],
    },
    { value: "review", label: "review" },
    { value: "summarize", label: "summarize" },
  ]

  const loadFile = () =>
    new Promise<void>((resolve) => setTimeout(resolve, 800))

  const log = useLog()
  const prompt = createTokenInputController()
  let running = $state(false)
  let sendTimer: ReturnType<typeof setTimeout> | undefined

  onDestroy(() => clearTimeout(sendTimer))

  function send(value: TokenInputValue) {
    if (running || !prompt.getLabel().trim()) {
      return
    }
    running = true
    const skillTokens = value.filter(
      (segment) => typeof segment !== "string" && segment.type === "skill"
    )
    for (const skill of skillTokens) {
      if (typeof skill !== "string") {
        prompt.updateToken(skill.id!, {
          data: { ...skill.data, run: "running" },
        })
      }
    }
    sendTimer = setTimeout(() => {
      for (const skill of skillTokens) {
        if (typeof skill !== "string") {
          prompt.updateToken(skill.id!, {
            data: { ...skill.data, run: "done" },
          })
        }
      }
      log(`Sent ${toText(prompt.getValue())}`)
      prompt.clear()
      running = false
    }, 1500)
  }
</script>

<TokenInput controller={prompt} onSubmit={send}>
  {#snippet token(token)}
    <TokenInputToken>
      {#if token.type === "skill"}
        <CodeIcon aria-hidden="true" />
      {:else}
        <FileIcon aria-hidden="true" />
      {/if}
      {token.type === "skill" ? `/${token.label}` : token.label}
      {#if token.data?.run === "running"}
        <ClockIcon aria-hidden="true" />
      {/if}
      {#if token.data?.run === "done"}
        <CheckIcon aria-hidden="true" />
      {/if}
      <TokenInputTokenRemove>
        <XIcon aria-hidden="true" />
      </TokenInputTokenRemove>
    </TokenInputToken>
  {/snippet}
  <div data-slot="card">
    <TokenInputEditor
      aria-label="Prompt"
      placeholder="Ask anything. Type @ or /"
    />
    <div data-slot="row">
      <button
        type="button"
        data-size="sm"
        onmousedown={(event) => event.preventDefault()}
        onclick={() =>
          prompt.insert(
            { type: "file", value: "README.md", label: "README.md" },
            { resolve: loadFile() }
          )}
      >
        Attach README
      </button>
      <button
        type="button"
        data-variant="solid"
        data-size="sm"
        data-shape="round"
        onclick={() => send(prompt.getValue())}
        aria-label={running ? "Running" : "Send"}
        disabled={running}
      >
        {#if running}
          <ClockIcon aria-hidden="true" />
        {:else}
          <ArrowUpIcon aria-hidden="true" />
        {/if}
      </button>
    </div>
  </div>
  <TriggerMenu
    triggers={[
      { char: "@", type: "file", items: files },
      { char: "/", boundary: "start", type: "skill", items: skills },
    ]}
    onSelect={(value, details) =>
      details.trigger === "@" ? loadFile() : undefined}
  >
    <TriggerMenuHint />
    <TriggerMenuContent>
      <TriggerMenuEmpty>No matches</TriggerMenuEmpty>
      <TriggerMenuList>
        {#snippet children(state)}
          {#each state.items as TriggerMenuDataItem[] as item (item.value)}
            <TriggerMenuItem
              value={item.value}
              label={item.label}
              disabled={item.disabled}
            >
              {item.label}
            </TriggerMenuItem>
          {/each}
        {/snippet}
      </TriggerMenuList>
    </TriggerMenuContent>
  </TriggerMenu>
</TokenInput>
```

输入 @ 选择文件，或在开头输入 / 选择技能。对于 /search，输入查询并按 Enter 插入命令。再按 Enter 发送，控制台会记录这条消息。

## 删除标记
用 `tokenDeletion` 选择在标记处按 Backspace 时做什么：

- `whole` 一次按压就移除标记。
- `select` 先选中它，再在下一次按压时移除。
- `revert` 把它变回可编辑的文字，触发菜单会在它上面重新打开。

```svelte title="deletion.svelte"
<script lang="ts">
  import { CheckIcon, ChevronDownIcon, FileIcon } from "@lucide/svelte"
  import { Field, FieldLabel } from "@ui-sdk/svelte/field"
  import {
    Select,
    SelectContent,
    SelectItem,
    SelectItemIndicator,
    SelectLabel,
    SelectTrigger,
    SelectValue,
  } from "@ui-sdk/svelte/select"
  import {
    TokenInput,
    TokenInputEditor,
    TokenInputToken,
    type TokenDeletion,
    type TokenInputValue,
  } from "@ui-sdk/svelte/token-input"
  import {
    type TriggerMenuDataItem,
    TriggerMenu,
    TriggerMenuContent,
    TriggerMenuItem,
    TriggerMenuList,
  } from "@ui-sdk/svelte/trigger-menu"
  import { useLog } from "./log"

  const modes = [
    { value: "whole", label: "Whole" },
    { value: "select", label: "Select" },
    { value: "revert", label: "Revert" },
  ]

  const files = [
    { value: "src/app.tsx", label: "app.tsx", keywords: ["src"] },
    { value: "src/routes.ts", label: "routes.ts", keywords: ["src"] },
    { value: "src/styles.css", label: "styles.css", keywords: ["src"] },
    { value: "README.md", label: "README.md" },
    { value: "package.json", label: "package.json" },
  ]

  const draft: TokenInputValue = [
    "Explain ",
    {
      type: "file",
      value: "src/routes.ts",
      label: "routes.ts",
      data: { trigger: "@" },
    },
    " in two sentences.",
  ]

  const log = useLog()
  let deletion = $state<TokenDeletion>("whole")
</script>

<div data-slot="stack">
  <div data-slot="controls">
    <Select
      items={modes}
      value={deletion}
      onValueChange={(next) => next && (deletion = next as TokenDeletion)}
    >
      <SelectLabel>Backspace</SelectLabel>
      <SelectTrigger>
        <SelectValue />
        <ChevronDownIcon aria-hidden="true" />
      </SelectTrigger>
      <SelectContent>
        {#each modes as mode (mode.value)}
          <SelectItem value={mode.value}>
            {mode.label}
            <SelectItemIndicator>
              <CheckIcon aria-hidden="true" />
            </SelectItemIndicator>
          </SelectItem>
        {/each}
      </SelectContent>
    </Select>
  </div>
  <Field>
    <FieldLabel>Prompt</FieldLabel>
    <TokenInput
      tokenDeletion={deletion}
      defaultValue={draft}
      onValueChange={(value, details) => {
        for (const token of details.removed) {
          log(`Removed ${token.label} (${deletion})`)
        }
      }}
    >
      {#snippet token(token)}
        <TokenInputToken>
          <FileIcon aria-hidden="true" />
          {token.label}
        </TokenInputToken>
      {/snippet}
      <TokenInputEditor />
      <TriggerMenu triggers={[{ char: "@", type: "file", items: files }]}>
        <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>
    </TokenInput>
  </Field>
</div>
```

选择一种 Backspace 行为，点击 routes.ts 之后的位置，然后按 Backspace。撤销后再试另一种行为。

## 编解码器
编解码器（codec）把标记转换成文本，用于剪贴板、表单和保存的草稿。默认格式写出 `[@label](type:value)`。把这段文本复制到另一个应用，再粘贴回来，标记就会恢复。

用 `toText`、`fromText` 和 `toLabel` 自己转换值。为其他格式提供自定义编解码器，就像这个示例为 `<@hollis>` 所做的那样。使用 `copy="label"` 时，复制会写出人们读到的内容，粘贴回 Token Input 仍然会恢复标记。默认解析器接受标记类型里的字母、数字、`_` 和 `-`；其他类型需要自定义编解码器。

```svelte title="codec.svelte"
<script lang="ts">
  import { Field, FieldLabel } from "@ui-sdk/svelte/field"
  import {
    fromText,
    toText,
    TokenInput,
    TokenInputEditor,
    type TokenCodec,
  } from "@ui-sdk/svelte/token-input"
  import { useLog } from "./log"

  const chat: TokenCodec = {
    format: (token) => `<@${token.value}>`,
    parse: (text) =>
      text.split(/(<@[\w.-]+>)/).map((part) => {
        const id = /^<@([\w.-]+)>$/.exec(part)?.[1]
        return id ? { type: "mention", value: id, label: `@${id}` } : part
      }),
  }

  const draft = fromText("Ping <@hollis> and <@ines> about the launch", chat)

  const log = useLog()
</script>

<Field>
  <FieldLabel>Message</FieldLabel>
  <TokenInput
    codec={chat}
    copy="label"
    defaultValue={draft}
    onValueChange={(value) => log(toText(value, chat))}
  >
    <TokenInputEditor />
  </TokenInput>
</Field>
```

编辑消息。控制台会用自定义格式记录它，每个提及都写成 <@id>。

## 表单
给输入框一个 `name` 来提交它序列化后的文本。`required`、`disabled` 和 `readOnly` 控制表单行为。`form` 选项把它和页面上别处的表单关联起来，就像这里展示的那样。

```svelte title="form.svelte"
<script lang="ts">
  import { CheckIcon } from "@lucide/svelte"
  import { Checkbox, CheckboxIndicator } from "@ui-sdk/svelte/checkbox"
  import { Field, FieldLabel } from "@ui-sdk/svelte/field"
  import {
    TokenInput,
    TokenInputEditor,
    type TokenInputValue,
  } from "@ui-sdk/svelte/token-input"
  import { useLog } from "./log"

  const draft: TokenInputValue = [
    "Explain ",
    { type: "file", value: "src/routes.ts", label: "routes.ts" },
    " in two sentences.",
  ]

  const log = useLog()
  let disabled = $state(false)
  let readOnly = $state(false)
  const formId = $props.id()

  function onSubmit(event: SubmitEvent & { currentTarget: HTMLFormElement }) {
    event.preventDefault()
    log(`Submitted ${new FormData(event.currentTarget).get("prompt") ?? ""}`)
  }
</script>

<div data-slot="stack">
  <div data-slot="controls">
    <label data-slot="label">
      <Checkbox
        checked={disabled}
        onCheckedChange={(next) => (disabled = next === true)}
      >
        <CheckboxIndicator>
          <CheckIcon aria-hidden="true" />
        </CheckboxIndicator>
      </Checkbox>
      Disabled
    </label>
    <label data-slot="label">
      <Checkbox
        checked={readOnly}
        onCheckedChange={(next) => (readOnly = next === true)}
      >
        <CheckboxIndicator>
          <CheckIcon aria-hidden="true" />
        </CheckboxIndicator>
      </Checkbox>
      Read-only
    </label>
  </div>
  <div data-slot="stack">
    <Field {disabled}>
      <FieldLabel>Prompt</FieldLabel>
      <TokenInput
        form={formId}
        name="prompt"
        required
        defaultValue={draft}
        {readOnly}
      >
        <TokenInputEditor />
      </TokenInput>
    </Field>
    <form id={formId} data-slot="row" onsubmit={onSubmit}>
      <button type="submit" data-variant="solid">Submit</button>
      <button type="reset">Reset</button>
    </form>
  </div>
</div>
```

按 Submit 记录提示词序列化后的值。试试 Disabled 和 Read-only，然后按 Reset。

## 受控
绑定 `bind:value`，或传入 `value` 并在 `onValueChange` 里更新它。变更详情包括原因、输入类型和被移除的标记。输入框仍然管理自己的编辑历史。

```svelte title="controlled.svelte"
<script lang="ts">
  import { Field, FieldLabel } from "@ui-sdk/svelte/field"
  import {
    toText,
    TokenInput,
    TokenInputEditor,
    type TokenInputValue,
  } from "@ui-sdk/svelte/token-input"
  import {
    type TriggerMenuDataItem,
    TriggerMenu,
    TriggerMenuContent,
    TriggerMenuItem,
    TriggerMenuList,
  } from "@ui-sdk/svelte/trigger-menu"
  import { useLog } from "./log"

  const files = [
    { value: "src/app.tsx", label: "app.tsx", keywords: ["src"] },
    { value: "src/routes.ts", label: "routes.ts", keywords: ["src"] },
    { value: "src/styles.css", label: "styles.css", keywords: ["src"] },
    { value: "README.md", label: "README.md" },
    { value: "package.json", label: "package.json" },
  ]

  const draft: TokenInputValue = [
    "Explain ",
    { type: "file", value: "src/routes.ts", label: "routes.ts" },
    " in two sentences.",
  ]

  const log = useLog()
  let value = $state<TokenInputValue>(draft)
</script>

<Field>
  <FieldLabel>Prompt</FieldLabel>
  <TokenInput
    bind:value
    onValueChange={(next, details) => {
      const removed = details.removed.map((token) => token.label).join(", ")
      log(
        `${toText(next)} (${details.reason}${removed ? `, removed ${removed}` : ""})`
      )
    }}
    history={{ limit: 50, groupDelay: 1000 }}
    getTokenDescription={(token) =>
      token.type === "file" ? "attached file" : token.type}
  >
    <TokenInputEditor />
    <TriggerMenu triggers={[{ char: "@", type: "file", items: files }]}>
      <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>
  </TokenInput>
</Field>
```

输入文字，用 @ 添加文件，或移除一个标记。控制台会记录值和每次变更的原因。

## 控制器
用 `createTokenInputController()` 从代码里插入、更新或移除标记。把一个 Promise 作为 `resolve` 传入，让插入的标记在数据就绪前保持待处理。更新标记不会增加撤销步骤。

```svelte title="controller.svelte"
<script lang="ts">
  import { Field, FieldLabel } from "@ui-sdk/svelte/field"
  import {
    createTokenInputController,
    TokenInput,
    TokenInputEditor,
    type Token,
    type TokenInputValue,
  } from "@ui-sdk/svelte/token-input"

  const draft: TokenInputValue = [
    "Compare ",
    { type: "file", value: "src/routes.ts", label: "routes.ts" },
    " with ",
  ]

  const loadFile = () =>
    new Promise<void>((resolve) => setTimeout(resolve, 800))

  const prompt = createTokenInputController()
  const firstToken = () =>
    prompt
      .getValue()
      .find((segment): segment is Token => typeof segment !== "string")
  const keepFocus = (event: MouseEvent) => event.preventDefault()

  function showPath() {
    const token = firstToken()
    if (token) {
      prompt.updateToken(token.id!, { label: token.value })
    }
  }

  function removeFirst() {
    const token = firstToken()
    if (token) {
      prompt.removeToken(token.id!)
    }
  }
</script>

<div data-slot="stack">
  <div data-slot="controls">
    <button
      type="button"
      onmousedown={keepFocus}
      onclick={() =>
        prompt.insert(
          { type: "file", value: "package.json", label: "package.json" },
          { at: "end", resolve: loadFile() }
        )}
    >
      Attach File
    </button>
    <button type="button" onmousedown={keepFocus} onclick={showPath}
      >Show Path</button
    >
    <button type="button" onmousedown={keepFocus} onclick={removeFirst}
      >Remove First</button
    >
    <button type="button" onmousedown={keepFocus} onclick={() => prompt.undo()}
      >Undo</button
    >
    <button type="button" onmousedown={keepFocus} onclick={() => prompt.clear()}
      >Clear</button
    >
  </div>
  <Field>
    <FieldLabel>Prompt</FieldLabel>
    <TokenInput controller={prompt} defaultValue={draft}>
      <TokenInputEditor />
    </TokenInput>
  </Field>
</div>
```

附上一个文件，看它加载。显示第一个标记的完整路径或移除它，然后使用 Undo 或 Clear。

## 提交快捷键
为多行消息把 `submitShortcut` 设为 `mod+enter`。这样 Enter 会插入一行，Command 或 Control+Enter 提交。

```svelte title="submit-shortcut.svelte"
<script lang="ts">
  import { Field, FieldLabel } from "@ui-sdk/svelte/field"
  import {
    toLabel,
    TokenInput,
    TokenInputEditor,
  } from "@ui-sdk/svelte/token-input"
  import { useLog } from "./log"

  const log = useLog()
</script>

<Field>
  <FieldLabel>Message</FieldLabel>
  <TokenInput
    submitShortcut="mod+enter"
    onSubmit={(value) => log(`Sent ${toLabel(value)}`)}
  >
    <TokenInputEditor placeholder="Write a message…" />
  </TokenInput>
</Field>
```

写一条消息。Enter 换行；在 Mac 上按 Command+Enter，其他平台按 Control+Enter，把它发送到控制台。

## 自定义渲染
传入 `token` snippet 来渲染每个标记的内容，通常是一个 `TokenInputToken`，里面带一个 `TokenInputTokenRemove`。它接收标记，所以你可以按类型选择图标，或显示它的 `data`。不用它时，每个标记显示自己的标签。

每个部件也接受 `render` snippet。[部件与组合](https://ui-sdk.cn/docs/svelte/parts-and-composition#choose-the-element)介绍了 props 如何合并，每个部件的状态列在[状态](https://ui-sdk.cn/docs/svelte/components/token-input#state)下。

## 样式
为编辑器、标记和它们的移除按钮设置样式。编辑器在没有任何内容时显示 `data-empty`；在它的 `::before` 上用 `content: attr(aria-placeholder)` 显示占位文字。标记会显示 `data-token-type`、`data-pending`、`data-unresolved` 和 `data-selected`。没有 `token` snippet 时，容纳每个标记的元素 `token-input-host` 也带有相同的属性，所以不用它也能给标记设置样式。

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

## 数据属性
### TokenInputEditor
`[data-slot="token-input-editor"]`

- `data-empty`: Present while the input holds nothing. Show the placeholder with it.
- `data-disabled`: Present when the input is disabled, by its own prop, a field or a `<fieldset>`.
- `data-readonly`: Present when the input is read-only.

### TokenInputToken
`[data-slot="token-input-token"]`

- `data-token-type` (`file`): The token's type, like `file` or `mention`. Also on its host.
- `data-pending`: Present while the token loads. Also on its host.
- `data-disabled`: Present when the input is disabled, by its own prop, a field or a `<fieldset>`.
- `data-readonly`: Present when the input is read-only.
- `data-slot`
- `data-selected`: Present while the token is in the selection, or selected for removal. Also on its host.
- `data-unresolved`: Present while the token needs the user, like an ambiguous mention. Also on its host.

### TokenInputTokenRemove
`[data-slot="token-input-token-remove"]`

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

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

### TokenInput
- `value?` (`TokenInputValue`): The value. Pass it to control the input.
- `defaultValue?` (`TokenInputValue`): The value at first, when uncontrolled. A form reset returns to it.
- `onValueChange?` (`((value: TokenInputValue, details: TokenInputValueChangeDetails) => void)`): Runs when typing, pasting, a menu, undo or a controller wants to change the value. `details.reason` says why, `details.removed` lists removed tokens, and `details.cancel()` stops it.
- `onSubmit?` (`((value: TokenInputValue, details: TokenInputSubmitDetails) => void)`): Runs on the submit shortcut, unless an input method is composing or a trigger menu is open. Without it, the shortcut submits the form the input is in. With neither, the key is left alone, so Enter starts a new line.
- `submitShortcut?` (`"enter" | "mod+enter"`): Which keys submit: `"enter"`, with Shift+Enter for a new line, or `"mod+enter"`, with Enter for a new line, which many Japanese and Chinese writers prefer.
- `tokenDeletion?` (`TokenDeletion`): How Backspace and Delete treat a token next to the caret. `"whole"` removes it in one press, `"select"` selects it first and removes it on the second, and `"revert"` turns it back into its text, so a trigger menu opens on it again.
- `copy?` (`"codec" | "label"`): What copying writes as plain text: `"codec"` keeps tokens through any app that pastes text, `"label"` writes what people read.
- `codec?` (`TokenCodec`): How tokens become text and back, for the clipboard and forms.
- `getTokenDescription?` (`((token: Token) => string)`): What a token says to screen readers besides its label, like its kind and status.
- `history?` (`UndoStackOptions`): Undo history: how many steps it keeps, and how long a typing pause starts a new step.
- `disabled?` (`boolean`): Disables the input: it can't be focused or changed, and isn't submitted.
- `readOnly?` (`boolean`): Keeps the input focusable and submitted, but stops changes.
- `required?` (`boolean`): Blocks form submission while the input is empty.
- `name?` (`string`): The name the codec text submits under. Without one, the input submits nothing.
- `form?` (`string`): The id of a form to belong to, when the input isn't inside it.
- `controller?` (`object`): Reads, edits and focuses the input from anywhere. Create one with `createTokenInputController()`.
- `debug?` (`boolean`): Logs every state change with its reason to the console, in development builds.

`token` snippet 接收每个标记并渲染它的内容，通常是一个 `TokenInputToken`。

### TokenInputEditor
- `placeholder?` (`string`): Text shown while the input is empty, through `aria-placeholder`. Show it with `data-empty:before:content-[attr(aria-placeholder)]`.

### TokenInputToken
标记的内容，位于 `token` snippet 内，带有用于样式设置的状态。渲染一个 `span`。

### TokenInputTokenRemove
按压时移除它所在的标记，并让焦点留在编辑器里。渲染一个 `span`，对辅助技术隐藏，因为键盘用户用 Backspace 移除标记。

### Token
- `type` (`string`): Kind, like `"mention"`, `"file"` or `"skill"`.
- `value` (`string`): The id it stands for.
- `label` (`string`): The text it shows, reads as and falls back to.
- `id?` (`string`): Stable identity, generated when missing.
- `status?` (`"pending" | "unresolved"`): `"pending"` while it loads, `"unresolved"` when it needs the user, like an ambiguous mention.
- `data?` (`Record<string, unknown>`): What the chip renders from, like an icon or a run state. Never serialized.

### 编解码器
- `format` (`(token: Token) => string`): The text a token is written as.
- `parse` (`(text: string) => TokenInputValue`): Text back into a value, with tokens wherever their text appears.
- `escape?` (`((text: string, next: Token | undefined) => string)`): How plain text is written so `parse` reads it back as text. `next` is the token that follows it, if any. Defaults to the text as is.

### 状态
`TokenInputEditor`：

- `empty` (`boolean`): Whether the input holds nothing.
- `disabled` (`boolean`): Whether the input is disabled, by itself or by a `<fieldset>`.
- `readOnly` (`boolean`): Whether the input is read-only: it stays focusable, but typing, pastes and drops don't change it.

`TokenInputToken`：

- `token` (`Token`): The token this part shows: the one the token input renders its content for.
- `selected` (`boolean`): Whether the token is in the selection, or selected for removal.
- `pending` (`boolean`): Whether the token is loading.
- `unresolved` (`boolean`): Whether the token needs the user, like an ambiguous mention.
- `disabled` (`boolean`): Whether the input is disabled, by itself or by a `<fieldset>`.
- `readOnly` (`boolean`): Whether the input is read-only, so the token's remove button does nothing.

### 原因
- `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.
- `paste` (`ClipboardEvent`): Files were pasted, like a screenshot, or text and tokens into a token input.
- `drop` (`DragEvent`): Files were dropped on a drop zone, or text and tokens on a token input.
- `cut` (`ClipboardEvent`): A selection was cut from a token input.
- `undo` (`KeyboardEvent | InputEvent`): Undo, from the keyboard, the Edit menu or a controller.
- `redo` (`KeyboardEvent | InputEvent`): Redo, from the keyboard, the Edit menu or a controller.
- `remove-press` (`MouseEvent | KeyboardEvent`): A chip's remove part was pressed, or Backspace or Delete removed a chip or a span.
- `item-press` (`MouseEvent | KeyboardEvent`): A member of a collection was chosen: a menu item, a tab, a radio or a checkbox item.
- `reset` (`none`): A form reset.
- `restore` (`none`): The browser restored state, like after going back, or a saved value was read back from storage.
- `imperative` (`none`): A controller or `api` call.

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

- `getValue()` (`() => TokenInputValue`): The value: text and tokens.
- `setValue(value, options?)` (`(value: TokenInputValue, options?: TokenInputChangeOptions | undefined) => boolean`): Replaces the value as one undoable step. Returns false when the change was canceled or nothing changed.
- `getText(codec?)` (`(codec?: TokenCodec | undefined) => string`): The value as codec text, like `Ask [@Ada](mention:ada)`.
- `getLabel()` (`() => string`): The value as people read it, with each token's label.
- `insert(content, options?)` (`(content: string | Token | TokenInputValue, options?: (TokenInputChangeOptions & { at?: TextRange | "caret" | "end" | undefined; resolve?: PromiseLike<...> | undefined; }) | undefined) => boolean`): Inserts text, a token or a value at the caret, the end or a range, as one undoable step. With `resolve`, a token is pending until it settles: updated with what it resolves to, removed if it rejects. Returns false when the change was canceled.
- `updateToken(id, patch)` (`(id: string, patch: Partial<Omit<Token, "id">>) => boolean`): Changes a token's status, data or label without an undo step or a caret move. Returns false when there's no such token or nothing changed.
- `removeToken(id, options?)` (`(id: string, options?: TokenInputChangeOptions | undefined) => boolean`): Removes a token as one undoable step. Returns false when the change was canceled or nothing changed.
- `undo()` (`() => boolean`): Undoes the last step. Returns false when there was none or the change was canceled.
- `redo()` (`() => boolean`): Redoes the last undone step. Returns false when there was none or the change was canceled.
- `canUndo()` (`() => boolean`): Whether there's a step to undo.
- `canRedo()` (`() => boolean`): Whether there's a step to redo.
- `clear(options?)` (`(options?: TokenInputChangeOptions | undefined) => boolean`): Empties the input as one undoable step. Returns false when the change was canceled or nothing changed.
- `focus(options?)` (`(options?: { at?: "end" | "start" | undefined; } | undefined) => void`): Focuses the editor, with the caret at its start or end.
- `editor` (`TextEditorAdapter`): The editor a TriggerMenu outside the token input reads and writes. A menu inside it finds it on its own.

### 事件
回调先收到新状态，再收到详情。绑定的 `value` 只在 `onValueChange` 未取消变更时更新。

| 属性            | 所属         | 收到                                                               |
| --------------- | ------------ | ------------------------------------------------------------------ |
| `bind:value`    | `TokenInput` | 值                                                                 |
| `onValueChange` | `TokenInput` | `(value, details)`：值、[原因](https://ui-sdk.cn/docs/svelte/components/token-input#reasons)、`inputType` 和 `removed` |
| `onSubmit`      | `TokenInput` | `(value, details)`：值，以及提交它的按键或菜单选择                 |

## 无障碍
编辑器是一个多行文本框：它有 `textbox` 角色和 `aria-multiline`，里面的 Trigger Menu 会为它的建议加上 `aria-autocomplete` 和 `aria-haspopup`。通过 [Field](/docs/svelte/components/field) 给它一个可见的标签，或者用 `aria-label`。每个标记都会读出它的标签和种类，比如 "routes.ts file"，插入或移除标记会被播报。输入时保留浏览器的拼写标记、自动更正和输入法支持。

### 键盘
| 按键                         | 作用                                                          |
| ---------------------------- | ------------------------------------------------------------- |
| Backspace, Delete            | 按 `tokenDeletion` 的设定，移除光标前或光标后的标记           |
| ArrowLeft, ArrowRight        | 一次按压让光标越过一个标记；光标从不停在标记内部              |
| Enter                        | 提交。触发菜单打开时，选择高亮的建议                          |
| Shift+Enter                  | 新起一行                                                      |
| Command+Enter, Control+Enter | `submitShortcut` 为 `"mod+enter"` 时提交；此时 Enter 新起一行 |
| Command+Z, Control+Z         | 撤销上一步。连续输入会合并；粘贴和标记变更各算一步            |
| Shift+Command+Z, Control+Y   | 重做上一个撤销的步骤                                          |

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

- The editor says it offers suggestions from mount, before focus.

**Value**

- Renders text and tokens, each token as one chip.
- Tokens it starts with show their rendered content once, and read as their label and kind.
- Tokens and their remove parts mark a read-only or disabled input.
- Is empty with a placeholder until something is typed.
- Typing after a token goes after it.
- Shift+Enter starts a new line.

**Tokens**

- @ opens the menu inside the input, and choosing inserts a token and a space.
- A controlled input takes tokens from its menu and keeps typing in order.
- Enter in an open menu chooses and doesn't submit.
- One Backspace removes a whole token, and says so.
- Backspace removes tokens one by one, with no keystroke spent on anchors.
- Delete removes the token after the caret.
- The caret crosses a token with one arrow press each way.
- The caret can sit between two adjacent tokens.
- Clicking past a final token and typing lands after it.
- Word deletion stops at a token.
- The remove button removes its token and keeps focus.
- With tokenDeletion select, the first Backspace selects the token and the second removes it.
- With tokenDeletion revert, Backspace turns the token back into text and the menu opens on it.

**History**

- Undo and Redo step through edits, a token insertion on its own.
- Undo brings back a removed token.
- A pending token shows loading, then settles without an undo step.
- A pending token whose load fails is removed.

**Clipboard**

- Copying tokens into plain text and back keeps them.
- Copy writes codec text and HTML with the tokens.
- Pasting codec text makes tokens.
- With copy label, plain text gets what people read.

**Submit**

- Enter submits the codec text.
- With mod+enter, Enter is a new line and Cmd or Ctrl+Enter submits.
- A form submits the codec text under the input's name.
- Enter submits the form the input's form attribute names, not the one it's in.
- Enter while an input method composes doesn't submit.

Runs in React、Vue 和 web components.
