Token Input
输入文字,并混入文件、人员、标签等引用标记。
Token Input 是一个文本框,在文字之间存放标记,比如消息里提到的人,或者提示词附带的文件。每个标记都作为一个整体移动、删除和复制。
<script setup lang="ts">
import { XIcon } from "@lucide/vue"
import { Field, FieldLabel } from "@ui-sdk/vue/field"
import {
TokenInput,
TokenInputEditor,
TokenInputToken,
TokenInputTokenRemove,
} from "@ui-sdk/vue/token-input"
import {
type TriggerMenuDataItem,
TriggerMenu,
TriggerMenuContent,
TriggerMenuItem,
TriggerMenuList,
} from "@ui-sdk/vue/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>
<template>
<Field>
<FieldLabel>Message</FieldLabel>
<TokenInput>
<TokenInputEditor placeholder="Type @ to mention someone…" />
<TriggerMenu :triggers="[{ char: '@', type: 'mention', items: people }]">
<TriggerMenuContent>
<TriggerMenuList v-slot="{ state }">
<TriggerMenuItem
v-for="item in state.items as TriggerMenuDataItem[]"
:key="item.value"
:value="item.value"
:label="item.label"
>
{{ item.label }}
</TriggerMenuItem>
</TriggerMenuList>
</TriggerMenuContent>
</TriggerMenu>
<template #token="{ token }">
<TokenInputToken>
{{ token.label }}
<TokenInputTokenRemove>
<XIcon aria-hidden="true" />
</TokenInputTokenRemove>
</TokenInputToken>
</template>
</TokenInput>
</Field>
</template>安装
npm install @ui-sdk/vue @ui-sdk/core组合
用下面的组合构建 TokenInput:
TokenInput
├── TokenInputEditor
└── TriggerMenu每个标记则放在 #token 插槽里:
TokenInputToken
└── TokenInputTokenRemoveTokenInput 保存值,TokenInputEditor 是人们编辑的文字。它里面的 Trigger Menu 在有人输入 @、/ 或其他触发字符时建议标记。用 #token 插槽为每个标记提供你自己的渲染结构。
用法
导入部件并把它们组合起来:
<script setup lang="ts">
import {
TokenInput,
TokenInputEditor,
type TokenInputValue,
} from "@ui-sdk/vue/token-input"
const draft: TokenInputValue = [
"Explain ",
{ type: "file", value: "src/routes.ts", label: "routes.ts" },
]
</script>
<template>
<TokenInput :default-value="draft">
<TokenInputEditor aria-label="Prompt" />
</TokenInput>
</template>值是文字和标记组成的数组。每个标记有一个类型、一个供你的应用使用的值,以及一个供人阅读的标签。编辑器自己管理它的内容,包括标记、选择和撤销,所以让它渲染这些内容,自定义标记时用 #token 插槽。
Token Input 还是 Trigger Menu
Token Input 保存文字和标记。Trigger Menu 在有人输入触发字符时建议要插入的内容。
当你的代码提供标记时,单独使用 Token Input。需要建议时加上 Trigger Menu,就像上面的示例。Trigger Menu 也能配合普通输入框和文本域工作。
提示词输入
把文件建议、技能和发送动作组合在一起。这个示例在文件加载期间把它们标记为待处理,然后用 updateToken() 显示正在运行的技能。Enter 发送;Shift+Enter 换行。打开的建议菜单或正在使用的输入法优先于发送。
<script setup lang="ts">
import {
ArrowUpIcon,
CheckIcon,
ClockIcon,
CodeIcon,
FileIcon,
XIcon,
} from "@lucide/vue"
import {
createTokenInputController,
toText,
TokenInput,
TokenInputEditor,
TokenInputToken,
TokenInputTokenRemove,
type TokenInputValue,
} from "@ui-sdk/vue/token-input"
import {
type TriggerMenuDataItem,
type TriggerMenuSelectDetails,
TriggerMenu,
TriggerMenuContent,
TriggerMenuEmpty,
TriggerMenuHint,
TriggerMenuItem,
TriggerMenuList,
} from "@ui-sdk/vue/trigger-menu"
import { onBeforeUnmount, ref } from "vue"
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()
const running = ref(false)
let sendTimer: ReturnType<typeof setTimeout> | undefined
onBeforeUnmount(() => clearTimeout(sendTimer))
function send(value: TokenInputValue) {
if (running.value || !prompt.getLabel().trim()) {
return
}
running.value = 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.value = false
}, 1500)
}
function onSelect(value: string, details: TriggerMenuSelectDetails<string>) {
return details.trigger === "@" ? loadFile() : undefined
}
function attachReadme() {
prompt.insert(
{ type: "file", value: "README.md", label: "README.md" },
{ resolve: loadFile() }
)
}
</script>
<template>
<TokenInput :controller="prompt" @submit="send">
<div data-slot="card">
<TokenInputEditor
aria-label="Prompt"
placeholder="Ask anything. Type @ or /"
/>
<div data-slot="row">
<button
type="button"
data-size="sm"
@mousedown.prevent
@click="attachReadme"
>
Attach README
</button>
<button
type="button"
data-variant="solid"
data-size="sm"
data-shape="round"
:aria-label="running ? 'Running' : 'Send'"
:disabled="running"
@click="send(prompt.getValue())"
>
<ClockIcon v-if="running" aria-hidden="true" />
<ArrowUpIcon v-else aria-hidden="true" />
</button>
</div>
</div>
<TriggerMenu
:triggers="[
{ char: '@', type: 'file', items: files },
{ char: '/', boundary: 'start', type: 'skill', items: skills },
]"
@select="onSelect"
>
<TriggerMenuHint />
<TriggerMenuContent>
<TriggerMenuEmpty>No matches</TriggerMenuEmpty>
<TriggerMenuList v-slot="{ state }">
<TriggerMenuItem
v-for="item in state.items as TriggerMenuDataItem[]"
:key="item.value"
:value="item.value"
:label="item.label"
:disabled="item.disabled"
>
{{ item.label }}
</TriggerMenuItem>
</TriggerMenuList>
</TriggerMenuContent>
</TriggerMenu>
<template #token="{ token }">
<TokenInputToken>
<CodeIcon v-if="token.type === 'skill'" aria-hidden="true" />
<FileIcon v-else aria-hidden="true" />
{{ token.type === "skill" ? `/${token.label}` : token.label }}
<ClockIcon v-if="token.data?.run === 'running'" aria-hidden="true" />
<CheckIcon v-if="token.data?.run === 'done'" aria-hidden="true" />
<TokenInputTokenRemove>
<XIcon aria-hidden="true" />
</TokenInputTokenRemove>
</TokenInputToken>
</template>
</TokenInput>
</template>删除标记
用 token-deletion 选择在标记处按 Backspace 时做什么:
whole一次按压就移除标记。select先选中它,再在下一次按压时移除。revert把它变回可编辑的文字,触发菜单会在它上面重新打开。
<script setup lang="ts">
import { CheckIcon, ChevronDownIcon, FileIcon } from "@lucide/vue"
import { Field, FieldLabel } from "@ui-sdk/vue/field"
import {
Select,
SelectContent,
SelectItem,
SelectItemIndicator,
SelectLabel,
SelectTrigger,
SelectValue,
} from "@ui-sdk/vue/select"
import {
TokenInput,
TokenInputEditor,
TokenInputToken,
type TokenDeletion,
type TokenInputValue,
type TokenInputValueChangeDetails,
} from "@ui-sdk/vue/token-input"
import {
type TriggerMenuDataItem,
TriggerMenu,
TriggerMenuContent,
TriggerMenuItem,
TriggerMenuList,
} from "@ui-sdk/vue/trigger-menu"
import { ref } from "vue"
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()
const deletion = ref<TokenDeletion>("whole")
function onValueChange(
value: TokenInputValue,
details: TokenInputValueChangeDetails
) {
for (const token of details.removed) {
log(`Removed ${token.label} (${deletion.value})`)
}
}
</script>
<template>
<div data-slot="stack">
<div data-slot="controls">
<Select
:items="modes"
:value="deletion"
@value-change="(next) => next && (deletion = next as TokenDeletion)"
>
<SelectLabel>Backspace</SelectLabel>
<SelectTrigger>
<SelectValue />
<ChevronDownIcon aria-hidden="true" />
</SelectTrigger>
<SelectContent>
<SelectItem
v-for="mode in modes"
:key="mode.value"
:value="mode.value"
>
{{ mode.label }}
<SelectItemIndicator>
<CheckIcon aria-hidden="true" />
</SelectItemIndicator>
</SelectItem>
</SelectContent>
</Select>
</div>
<Field>
<FieldLabel>Prompt</FieldLabel>
<TokenInput
:token-deletion="deletion"
:default-value="draft"
@value-change="onValueChange"
>
<TokenInputEditor />
<TriggerMenu :triggers="[{ char: '@', type: 'file', items: files }]">
<TriggerMenuContent>
<TriggerMenuList v-slot="{ state }">
<TriggerMenuItem
v-for="item in state.items as TriggerMenuDataItem[]"
:key="item.value"
:value="item.value"
:label="item.label"
>
{{ item.label }}
</TriggerMenuItem>
</TriggerMenuList>
</TriggerMenuContent>
</TriggerMenu>
<template #token="{ token }">
<TokenInputToken>
<FileIcon aria-hidden="true" />
{{ token.label }}
</TokenInputToken>
</template>
</TokenInput>
</Field>
</div>
</template>编解码器
编解码器(codec)把标记转换成文本,用于剪贴板、表单和保存的草稿。默认格式写出 [@label](type:value)。把这段文本复制到另一个应用,再粘贴回来,标记就会恢复。
用 toText、fromText 和 toLabel 自己转换值。为其他格式提供自定义编解码器,就像这个示例为 <@hollis> 所做的那样。使用 copy="label" 时,复制会写出人们读到的内容,粘贴回 Token Input 仍然会恢复标记。默认解析器接受标记类型里的字母、数字、_ 和 -;其他类型需要自定义编解码器。
<script setup lang="ts">
import { Field, FieldLabel } from "@ui-sdk/vue/field"
import {
fromText,
toText,
TokenInput,
TokenInputEditor,
type TokenCodec,
} from "@ui-sdk/vue/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>
<template>
<Field>
<FieldLabel>Message</FieldLabel>
<TokenInput
:codec="chat"
copy="label"
:default-value="draft"
@value-change="(value) => log(toText(value, chat))"
>
<TokenInputEditor />
</TokenInput>
</Field>
</template>表单
给输入框一个 name 来提交它序列化后的文本。required、disabled 和 read-only 控制表单行为。form 选项把它和页面上别处的表单关联起来,就像这里展示的那样。
<script setup lang="ts">
import { CheckIcon } from "@lucide/vue"
import { Checkbox, CheckboxIndicator } from "@ui-sdk/vue/checkbox"
import { Field, FieldLabel } from "@ui-sdk/vue/field"
import {
TokenInput,
TokenInputEditor,
type TokenInputValue,
} from "@ui-sdk/vue/token-input"
import { ref, useId } from "vue"
import { useLog } from "./log"
const draft: TokenInputValue = [
"Explain ",
{ type: "file", value: "src/routes.ts", label: "routes.ts" },
" in two sentences.",
]
const log = useLog()
const disabled = ref(false)
const readOnly = ref(false)
const formId = useId()
function onSubmit(event: Event) {
log(
`Submitted ${new FormData(event.currentTarget as HTMLFormElement).get("prompt") ?? ""}`
)
}
</script>
<template>
<div data-slot="stack">
<div data-slot="controls">
<label data-slot="label">
<Checkbox
:checked="disabled"
@checked-change="(next) => (disabled = next === true)"
>
<CheckboxIndicator>
<CheckIcon aria-hidden="true" />
</CheckboxIndicator>
</Checkbox>
Disabled
</label>
<label data-slot="label">
<Checkbox
:checked="readOnly"
@checked-change="(next) => (readOnly = next === true)"
>
<CheckboxIndicator>
<CheckIcon aria-hidden="true" />
</CheckboxIndicator>
</Checkbox>
Read-only
</label>
</div>
<div data-slot="stack">
<Field :disabled="disabled">
<FieldLabel>Prompt</FieldLabel>
<TokenInput
:form="formId"
name="prompt"
required
:default-value="draft"
:read-only="readOnly"
>
<TokenInputEditor />
</TokenInput>
</Field>
<form :id="formId" data-slot="row" @submit.prevent="onSubmit">
<button type="submit" data-variant="solid">Submit</button>
<button type="reset">Reset</button>
</form>
</div>
</div>
</template>受控
绑定 v-model:value,或传入 value 并在 @value-change 里更新它。变更详情包括原因、输入类型和被移除的标记。输入框仍然管理自己的编辑历史。
<script setup lang="ts">
import { Field, FieldLabel } from "@ui-sdk/vue/field"
import {
toText,
TokenInput,
TokenInputEditor,
type Token,
type TokenInputValue,
type TokenInputValueChangeDetails,
} from "@ui-sdk/vue/token-input"
import {
type TriggerMenuDataItem,
TriggerMenu,
TriggerMenuContent,
TriggerMenuItem,
TriggerMenuList,
} from "@ui-sdk/vue/trigger-menu"
import { ref } from "vue"
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()
const value = ref<TokenInputValue>(draft)
function onValueChange(
next: TokenInputValue,
details: TokenInputValueChangeDetails
) {
const removed = details.removed.map((token) => token.label).join(", ")
log(
`${toText(next)} (${details.reason}${removed ? `, removed ${removed}` : ""})`
)
}
</script>
<template>
<Field>
<FieldLabel>Prompt</FieldLabel>
<TokenInput
v-model:value="value"
:history="{ limit: 50, groupDelay: 1000 }"
:get-token-description="
(token: Token) => (token.type === 'file' ? 'attached file' : token.type)
"
@value-change="onValueChange"
>
<TokenInputEditor />
<TriggerMenu :triggers="[{ char: '@', type: 'file', items: files }]">
<TriggerMenuContent>
<TriggerMenuList v-slot="{ state }">
<TriggerMenuItem
v-for="item in state.items as TriggerMenuDataItem[]"
:key="item.value"
:value="item.value"
:label="item.label"
>
{{ item.label }}
</TriggerMenuItem>
</TriggerMenuList>
</TriggerMenuContent>
</TriggerMenu>
</TokenInput>
</Field>
</template>控制器
用 createTokenInputController() 从代码里插入、更新或移除标记。把一个 Promise 作为 resolve 传入,让插入的标记在数据就绪前保持待处理。更新标记不会增加撤销步骤。
<script setup lang="ts">
import { Field, FieldLabel } from "@ui-sdk/vue/field"
import {
createTokenInputController,
TokenInput,
TokenInputEditor,
type Token,
type TokenInputValue,
} from "@ui-sdk/vue/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")
function attachFile() {
prompt.insert(
{ type: "file", value: "package.json", label: "package.json" },
{ at: "end", resolve: loadFile() }
)
}
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>
<template>
<div data-slot="stack">
<div data-slot="controls" @mousedown.prevent>
<button type="button" @click="attachFile">Attach File</button>
<button type="button" @click="showPath">Show Path</button>
<button type="button" @click="removeFirst">Remove First</button>
<button type="button" @click="prompt.undo()">Undo</button>
<button type="button" @click="prompt.clear()">Clear</button>
</div>
<Field>
<FieldLabel>Prompt</FieldLabel>
<TokenInput :controller="prompt" :default-value="draft">
<TokenInputEditor />
</TokenInput>
</Field>
</div>
</template>提交快捷键
为多行消息把 submit-shortcut 设为 mod+enter。这样 Enter 会插入一行,Command 或 Control+Enter 提交。
<script setup lang="ts">
import { Field, FieldLabel } from "@ui-sdk/vue/field"
import { toLabel, TokenInput, TokenInputEditor } from "@ui-sdk/vue/token-input"
import { useLog } from "./log"
const log = useLog()
</script>
<template>
<Field>
<FieldLabel>Message</FieldLabel>
<TokenInput
submit-shortcut="mod+enter"
@submit="(value) => log(`Sent ${toLabel(value)}`)"
>
<TokenInputEditor placeholder="Write a message…" />
</TokenInput>
</Field>
</template>自定义渲染
用 #token 插槽渲染每个标记的内容,通常是一个 TokenInputToken,里面带一个 TokenInputTokenRemove。它接收标记,所以你可以按类型选择图标,或显示它的 data。不用它时,每个标记显示自己的标签。
每个部件也接受 render 插槽。部件与组合介绍了 props 如何合并,每个部件的状态列在状态下。
样式
为编辑器、标记和它们的移除按钮设置样式。编辑器在没有任何内容时显示 data-empty;在它的 ::before 上用 content: attr(aria-placeholder) 显示占位文字。标记会显示 data-token-type、data-pending、data-unresolved 和 data-selected。没有 #token 插槽时,容纳每个标记的元素 token-input-host 也带有相同的属性,所以不用插槽也能给标记设置样式。
每个部件都有一个 data-slot,比如 token-input-token,并通过数据属性下列出的属性展示它的状态。
数据属性
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 | fileThe 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 与下面相同,回调是事件。
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.
@value-change((value: TokenInputValue, details: TokenInputValueChangeDetails) => void)- Runs when typing, pasting, a menu, undo or a controller wants to change the value.
details.reasonsays why,details.removedlists removed tokens, anddetails.cancel()stops it. @submit((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 插槽接收每个标记并渲染它的内容,通常是一个 TokenInputToken。
TokenInputEditor
placeholder?string- Text shown while the input is empty, through
aria-placeholder. Show it withdata-empty:before:content-[attr(aria-placeholder)].
TokenInputToken
标记的内容,位于 #token 插槽内,带有用于样式设置的状态。渲染一个 span。
TokenInputTokenRemove
按压时移除它所在的标记,并让焦点留在编辑器里。渲染一个 span,对辅助技术隐藏,因为键盘用户用 Backspace 移除标记。
Token
typestring- Kind, like
"mention","file"or"skill". valuestring- The id it stands for.
labelstring- 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
parsereads it back as text.nextis the token that follows it, if any. Defaults to the text as is.
状态
TokenInputEditor:
emptyboolean- Whether the input holds nothing.
disabledboolean- Whether the input is disabled, by itself or by a
<fieldset>. readOnlyboolean- Whether the input is read-only: it stays focusable, but typing, pastes and drops don't change it.
TokenInputToken:
tokenToken- The token this part shows: the one the token input renders its content for.
selectedboolean- Whether the token is in the selection, or selected for removal.
pendingboolean- Whether the token is loading.
unresolvedboolean- Whether the token needs the user, like an ambiguous mention.
disabledboolean- Whether the input is disabled, by itself or by a
<fieldset>. readOnlyboolean- Whether the input is read-only, so the token's remove button does nothing.
原因
input-changeEvent- 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.
pasteClipboardEvent- Files were pasted, like a screenshot, or text and tokens into a token input.
dropDragEvent- Files were dropped on a drop zone, or text and tokens on a token input.
cutClipboardEvent- A selection was cut from a token input.
undoKeyboardEvent | InputEvent- Undo, from the keyboard, the Edit menu or a controller.
redoKeyboardEvent | InputEvent- Redo, from the keyboard, the Edit menu or a controller.
remove-pressMouseEvent | KeyboardEvent- A chip's remove part was pressed, or Backspace or Delete removed a chip or a span.
item-pressMouseEvent | KeyboardEvent- A member of a collection was chosen: a menu item, a tab, a radio or a checkbox item.
resetnone- A form reset.
restorenone- The browser restored state, like after going back, or a saved value was read back from storage.
imperativenone- A controller or
apicall.
控制器
用 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.
editorTextEditorAdapter- The editor a TriggerMenu outside the token input reads and writes. A menu inside it finds it on its own.
事件
事件先收到新状态,再收到详情。v-model 只在变更事件未被取消时更新。
| 绑定 | 所属 | 收到 |
|---|---|---|
v-model:value | TokenInput | 值 |
@value-change | TokenInput | (value, details):值、原因、inputType 和 removed |
@submit | TokenInput | (value, details):值,以及提交它的按键或菜单选择 |
无障碍
编辑器是一个多行文本框:它有 textbox 角色和 aria-multiline,里面的 Trigger Menu 会为它的建议加上 aria-autocomplete 和 aria-haspopup。通过 Field 给它一个可见的标签,或者用 aria-label。每个标记都会读出它的标签和种类,比如 "routes.ts file",插入或移除标记会被播报。输入时保留浏览器的拼写标记、自动更正和输入法支持。
键盘
| 按键 | 作用 |
|---|---|
| Backspace, Delete | 按 token-deletion 的设定,移除光标前或光标后的标记 |
| ArrowLeft, ArrowRight | 一次按压让光标越过一个标记;光标从不停在标记内部 |
| Enter | 提交。触发菜单打开时,选择高亮的建议 |
| Shift+Enter | 新起一行 |
| Command+Enter, Control+Enter | submit-shortcut 为 "mod+enter" 时提交;此时 Enter 新起一行 |
| Command+Z, Control+Z | 撤销上一步。连续输入会合并;粘贴和标记变更各算一步 |
| Shift+Command+Z, Control+Y | 重做上一个撤销的步骤 |
经过测试的行为
下面每一行都是一个自动化测试。
- The editor says it offers suggestions from mount, before focus.
- 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.
- @ 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.
- 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.
- 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.
- 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.
运行于 React、Vue 和 web components。