Token Input
输入文字,并混入文件、人员、标签等引用标记。
Token Input 是一个文本框,在文字之间存放标记,比如消息里提到的人,或者提示词附带的文件。每个标记都作为一个整体移动、删除和复制。
import "@ui-sdk/web/token-input"
import "@ui-sdk/web/trigger-menu"
import "@ui-sdk/web/field"
import { createElement, X } from "lucide"
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" },
]
function mount(root: HTMLElement) {
root.innerHTML = `
<ui-field>
<ui-field-label>Message</ui-field-label>
<ui-token-input>
<ui-token-input-editor placeholder="Type @ to mention someone…"></ui-token-input-editor>
<template>
<ui-token-input-token>
<span data-token-label></span>
<ui-token-input-token-remove>${createElement(X, { "aria-hidden": "true" }).outerHTML}</ui-token-input-token-remove>
</ui-token-input-token>
</template>
<ui-trigger-menu>
<ui-trigger-menu-content>
<ui-trigger-menu-list></ui-trigger-menu-list>
</ui-trigger-menu-content>
</ui-trigger-menu>
</ui-token-input>
</ui-field>
`
root.querySelector("ui-trigger-menu")!.triggers = [
{ char: "@", type: "mention", items: people },
]
}
export { mount }安装
npm install @ui-sdk/web @ui-sdk/core导入组件会定义它的元素。如果用到触发菜单和字段,也一并导入。在服务器上,导入不做任何事。
import "@ui-sdk/web/token-input"
import "@ui-sdk/web/trigger-menu"
import "@ui-sdk/web/field"组合
用下面的组合构建 ui-token-input:
ui-token-input
├── ui-token-input-editor
└── ui-trigger-menu每个标记则放在 <template> 里:
ui-token-input-token
└── ui-token-input-token-removeui-token-input 保存值,ui-token-input-editor 是人们编辑的文字。它里面的 Trigger Menu 在有人输入 @、/ 或其他触发字符时建议标记。在它里面放一个 <template>,或设置它的 renderToken property,为每个标记提供你自己的渲染结构。
用法
导入部件并把它们组合起来:
<script type="module">
import "@ui-sdk/web/token-input"
</script>
<ui-token-input value="Explain [@routes.ts](file:src/routes.ts)">
<ui-token-input-editor aria-label="Prompt"></ui-token-input-editor>
</ui-token-input>值是文字和标记组成的数组。每个标记有一个类型、一个供你的应用使用的值,以及一个供人阅读的标签。value 属性按编解码器文本写入;要在元素连接前设置 defaultValue property 才能传入数组。编辑器自己管理它的内容,包括标记、选择和撤销,所以让它渲染这些内容,自定义标记时用 <template> 或 renderToken。
Token Input 还是 Trigger Menu
Token Input 保存文字和标记。Trigger Menu 在有人输入触发字符时建议要插入的内容。
当你的代码提供标记时,单独使用 Token Input。需要建议时加上 Trigger Menu,就像上面的示例。Trigger Menu 也能配合普通输入框和文本域工作。
提示词输入
把文件建议、技能和发送动作组合在一起。这个示例在文件加载期间把它们标记为待处理,然后用 updateToken() 显示正在运行的技能。Enter 发送;Shift+Enter 换行。打开的建议菜单或正在使用的输入法优先于发送。Enter 提交输入框所在的表单,所以发送按钮就是那个表单的提交按钮。
import "@ui-sdk/web/trigger-menu"
import { toText, type Token } from "@ui-sdk/web/token-input"
import { ArrowUp, Check, Clock, Code, createElement, File, X } from "lucide"
import { log } 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))
function mount(root: HTMLElement) {
root.innerHTML = `
<form>
<ui-token-input>
<div data-slot="card">
<ui-token-input-editor aria-label="Prompt" placeholder="Ask anything. Type @ or /"></ui-token-input-editor>
<div data-slot="row">
<button type="button" data-size="sm">Attach README</button>
<button type="submit" data-variant="solid" data-size="sm" data-shape="round" aria-label="Send">
${createElement(ArrowUp, { "aria-hidden": "true" }).outerHTML}
</button>
</div>
</div>
<ui-trigger-menu>
<ui-trigger-menu-hint></ui-trigger-menu-hint>
<ui-trigger-menu-content>
<ui-trigger-menu-empty>No matches</ui-trigger-menu-empty>
<ui-trigger-menu-list></ui-trigger-menu-list>
</ui-trigger-menu-content>
</ui-trigger-menu>
</ui-token-input>
</form>
`
const input = root.querySelector("ui-token-input")!
const prompt = input.api
const menu = root.querySelector("ui-trigger-menu")!
const [attach, send] = root.querySelectorAll("button")
let running = false
let sendTimer: ReturnType<typeof setTimeout> | undefined
input.renderToken = (token, host) => {
host.innerHTML = `
<ui-token-input-token>
${createElement(token.type === "skill" ? Code : File, { "aria-hidden": "true" }).outerHTML}
<span></span>
${token.data?.run === "running" ? createElement(Clock, { "aria-hidden": "true" }).outerHTML : ""}
${token.data?.run === "done" ? createElement(Check, { "aria-hidden": "true" }).outerHTML : ""}
<ui-token-input-token-remove>${createElement(X, { "aria-hidden": "true" }).outerHTML}</ui-token-input-token-remove>
</ui-token-input-token>
`
host.querySelector("span")!.textContent =
token.type === "skill" ? `/${token.label}` : token.label
}
menu.triggers = [
{ char: "@", type: "file", items: files },
{ char: "/", boundary: "start", type: "skill", items: skills },
]
menu.addEventListener("itemselect", (event) => {
if (event.detail.trigger === "@") {
event.detail.waitUntil(loadFile())
}
})
const setRunning = (next: boolean) => {
running = next
send.disabled = next
send.setAttribute("aria-label", next ? "Running" : "Send")
send.innerHTML = createElement(next ? Clock : ArrowUp, {
"aria-hidden": "true",
}).outerHTML
}
attach.addEventListener("mousedown", (event) => event.preventDefault())
attach.addEventListener("click", () =>
prompt.insert(
{ type: "file", value: "README.md", label: "README.md" },
{ resolve: loadFile() }
)
)
root.querySelector("form")!.addEventListener("submit", (event) => {
event.preventDefault()
if (running || !prompt.getLabel().trim()) {
return
}
setRunning(true)
const skillTokens = prompt
.getValue()
.filter(
(segment): segment is Token =>
typeof segment !== "string" && segment.type === "skill"
)
for (const skill of skillTokens) {
prompt.updateToken(skill.id!, { data: { ...skill.data, run: "running" } })
}
sendTimer = setTimeout(() => {
for (const skill of skillTokens) {
prompt.updateToken(skill.id!, { data: { ...skill.data, run: "done" } })
}
log(root, `Sent ${toText(prompt.getValue())}`)
prompt.clear()
setRunning(false)
}, 1500)
})
return () => clearTimeout(sendTimer)
}
export { mount }删除标记
用 token-deletion 选择在标记处按 Backspace 时做什么:
whole一次按压就移除标记。select先选中它,再在下一次按压时移除。revert把它变回可编辑的文字,触发菜单会在它上面重新打开。
import "@ui-sdk/web/token-input"
import "@ui-sdk/web/select"
import "@ui-sdk/web/trigger-menu"
import "@ui-sdk/web/field"
import type { TokenDeletion, TokenInputValue } from "@ui-sdk/web/token-input"
import { Check, ChevronDown, createElement, File } from "lucide"
import { log } 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.",
]
function mount(root: HTMLElement) {
root.innerHTML = `
<div data-slot="stack">
<div data-slot="controls">
<ui-select default-value="whole">
<ui-select-label>Backspace</ui-select-label>
<ui-select-trigger>
<button>
<ui-select-value></ui-select-value>
${createElement(ChevronDown, { "aria-hidden": "true" }).outerHTML}
</button>
</ui-select-trigger>
<ui-select-content>
${modes
.map(
(mode) => `
<ui-select-item value="${mode.value}">
${mode.label}
<ui-select-item-indicator>${createElement(Check, { "aria-hidden": "true" }).outerHTML}</ui-select-item-indicator>
</ui-select-item>
`
)
.join("")}
</ui-select-content>
</ui-select>
</div>
<ui-field>
<ui-field-label>Prompt</ui-field-label>
</ui-field>
</div>
`
const prompt = document.createElement("ui-token-input")
prompt.tokenDeletion = "whole"
prompt.defaultValue = draft
prompt.innerHTML = `
<ui-token-input-editor></ui-token-input-editor>
<template>
<ui-token-input-token>
${createElement(File, { "aria-hidden": "true" }).outerHTML}
<span data-token-label></span>
</ui-token-input-token>
</template>
<ui-trigger-menu>
<ui-trigger-menu-content>
<ui-trigger-menu-list></ui-trigger-menu-list>
</ui-trigger-menu-content>
</ui-trigger-menu>
`
root.querySelector("ui-field")!.append(prompt)
root.querySelector("ui-trigger-menu")!.triggers = [
{ char: "@", type: "file", items: files },
]
root.querySelector("ui-select")!.addEventListener("valuechange", (event) => {
if (event.detail.value) {
prompt.tokenDeletion = event.detail.value as TokenDeletion
}
})
prompt.addEventListener("valuechange", (event) => {
for (const token of event.detail.removed) {
log(root, `Removed ${token.label} (${prompt.tokenDeletion})`)
}
})
}
export { mount }编解码器
编解码器(codec)把标记转换成文本,用于剪贴板、表单和保存的草稿。默认格式写出 [@label](type:value)。把这段文本复制到另一个应用,再粘贴回来,标记就会恢复。
用 toText、fromText 和 toLabel 自己转换值。为其他格式设置 codec property,就像这个示例为 <@hollis> 所做的那样。使用 copy="label" 时,复制会写出人们读到的内容,粘贴回 Token Input 仍然会恢复标记。默认解析器接受标记类型里的字母、数字、_ 和 -;其他类型需要自定义编解码器。value 属性按默认编解码器读取,所以在元素连接前设置 codec 和 defaultValue。
import "@ui-sdk/web/field"
import { fromText, toText, type TokenCodec } from "@ui-sdk/web/token-input"
import { log } 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)
function mount(root: HTMLElement) {
root.innerHTML = `
<ui-field>
<ui-field-label>Message</ui-field-label>
</ui-field>
`
const message = document.createElement("ui-token-input")
message.codec = chat
message.setAttribute("copy", "label")
message.defaultValue = draft
message.innerHTML = `<ui-token-input-editor></ui-token-input-editor>`
message.addEventListener("valuechange", (event) =>
log(root, toText(event.detail.value, chat))
)
root.querySelector("ui-field")!.append(message)
}
export { mount }表单
给输入框一个 name 来提交它序列化后的文本。required、disabled 和 read-only 控制表单行为。form 属性把它和页面上别处的表单关联起来,就像这里展示的那样。
import "@ui-sdk/web/checkbox"
import "@ui-sdk/web/field"
import { toText, type TokenInputValue } from "@ui-sdk/web/token-input"
import { Check, createElement } from "lucide"
import { log } from "./log"
const draft: TokenInputValue = [
"Explain ",
{ type: "file", value: "src/routes.ts", label: "routes.ts" },
" in two sentences.",
]
function mount(root: HTMLElement) {
const formId = crypto.randomUUID()
root.innerHTML = `
<div data-slot="stack">
<div data-slot="controls">
<label data-slot="label">
<ui-checkbox>
<ui-checkbox-indicator>${createElement(Check, { "aria-hidden": "true" }).outerHTML}</ui-checkbox-indicator>
</ui-checkbox>
Disabled
</label>
<label data-slot="label">
<ui-checkbox>
<ui-checkbox-indicator>${createElement(Check, { "aria-hidden": "true" }).outerHTML}</ui-checkbox-indicator>
</ui-checkbox>
Read-only
</label>
</div>
<div data-slot="stack">
<ui-field>
<ui-field-label>Prompt</ui-field-label>
<ui-token-input form="${formId}" name="prompt" required value="${toText(draft)}">
<ui-token-input-editor></ui-token-input-editor>
</ui-token-input>
</ui-field>
<form id="${formId}" data-slot="row">
<button type="submit" data-variant="solid">Submit</button>
<button type="reset">Reset</button>
</form>
</div>
</div>
`
const field = root.querySelector("ui-field")!
const prompt = root.querySelector("ui-token-input")!
const [disabled, readOnly] = root.querySelectorAll("ui-checkbox")
disabled.addEventListener("checkedchange", (event) => {
field.toggleAttribute("disabled", event.detail.value === true)
})
readOnly.addEventListener("checkedchange", (event) => {
prompt.toggleAttribute("read-only", event.detail.value === true)
})
const form = root.querySelector("form")!
form.addEventListener("submit", (event) => {
event.preventDefault()
log(root, `Submitted ${new FormData(form).get("prompt") ?? ""}`)
})
}
export { mount }受控
设置 value 属性或 property,并监听 valuechange。事件的 detail 包括原因、输入类型和被移除的标记。输入框仍然管理自己的编辑历史。
import "@ui-sdk/web/trigger-menu"
import "@ui-sdk/web/field"
import { toText, type TokenInputValue } from "@ui-sdk/web/token-input"
import { log } 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.",
]
function mount(root: HTMLElement) {
root.innerHTML = `
<ui-field>
<ui-field-label>Prompt</ui-field-label>
<ui-token-input value="${toText(draft)}">
<ui-token-input-editor></ui-token-input-editor>
<ui-trigger-menu>
<ui-trigger-menu-content>
<ui-trigger-menu-list></ui-trigger-menu-list>
</ui-trigger-menu-content>
</ui-trigger-menu>
</ui-token-input>
</ui-field>
`
const prompt = root.querySelector("ui-token-input")!
prompt.history = { limit: 50, groupDelay: 1000 }
prompt.getTokenDescription = (token) =>
token.type === "file" ? "attached file" : token.type
root.querySelector("ui-trigger-menu")!.triggers = [
{ char: "@", type: "file", items: files },
]
prompt.addEventListener("valuechange", (event) => {
const { value, reason } = event.detail
const removed = event.detail.removed.map((token) => token.label).join(", ")
log(
root,
`${toText(value)} (${reason}${removed ? `, removed ${removed}` : ""})`
)
})
}
export { mount }控制器
用元素的 api 从代码里插入、更新或移除标记。把一个 Promise 作为 resolve 传入,让插入的标记在数据就绪前保持待处理。更新标记不会增加撤销步骤。
import "@ui-sdk/web/field"
import {
toText,
type Token,
type TokenInputValue,
} from "@ui-sdk/web/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))
function mount(root: HTMLElement) {
root.innerHTML = `
<div data-slot="stack">
<div data-slot="controls">
<button type="button" data-action="attach">Attach File</button>
<button type="button" data-action="path">Show Path</button>
<button type="button" data-action="remove">Remove First</button>
<button type="button" data-action="undo">Undo</button>
<button type="button" data-action="clear">Clear</button>
</div>
<ui-field>
<ui-field-label>Prompt</ui-field-label>
<ui-token-input value="${toText(draft)}">
<ui-token-input-editor></ui-token-input-editor>
</ui-token-input>
</ui-field>
</div>
`
const prompt = root.querySelector("ui-token-input")!.api
const firstToken = () =>
prompt
.getValue()
.find((segment): segment is Token => typeof segment !== "string")
const actions: Record<string, () => void> = {
attach: () =>
prompt.insert(
{ type: "file", value: "package.json", label: "package.json" },
{ at: "end", resolve: loadFile() }
),
path: () => {
const token = firstToken()
if (token) {
prompt.updateToken(token.id!, { label: token.value })
}
},
remove: () => {
const token = firstToken()
if (token) {
prompt.removeToken(token.id!)
}
},
undo: () => prompt.undo(),
clear: () => prompt.clear(),
}
root
.querySelector("[data-slot=controls]")!
.addEventListener("mousedown", (event) => event.preventDefault())
root
.querySelectorAll<HTMLButtonElement>("[data-action]")
.forEach((button) => {
button.addEventListener("click", () => actions[button.dataset.action!]())
})
}
export { mount }提交快捷键
为多行消息把 submit-shortcut 设为 mod+enter。这样 Enter 会插入一行,Command 或 Control+Enter 提交输入框所在的表单。
import "@ui-sdk/web/field"
import { toLabel } from "@ui-sdk/web/token-input"
import { log } from "./log"
function mount(root: HTMLElement) {
root.innerHTML = `
<form>
<ui-field>
<ui-field-label>Message</ui-field-label>
<ui-token-input submit-shortcut="mod+enter">
<ui-token-input-editor placeholder="Write a message…"></ui-token-input-editor>
</ui-token-input>
</ui-field>
</form>
`
const message = root.querySelector("ui-token-input")!
root.querySelector("form")!.addEventListener("submit", (event) => {
event.preventDefault()
log(root, `Sent ${toLabel(message.value)}`)
})
}
export { mount }自定义渲染
在 ui-token-input 里放一个 <template> 来渲染每个标记的内容,通常是 ui-token-input-token,里面带一个 ui-token-input-token-remove。模板里带 data-token-label 的元素会得到标记的标签。要按标记的类型选择图标或显示它的 data,改用 renderToken property:它接收标记和容纳它的元素。两者都没有时,每个标记显示自己的标签。
元素没有渲染函数。渲染约定见部件与组合,每个部件的字段见状态。
样式
为编辑器、标记和它们的移除按钮设置样式。编辑器在没有任何内容时显示 data-empty;在它的 ::before 上用 content: attr(aria-placeholder) 显示占位文字。标记会显示 data-token-type、data-pending、data-unresolved 和 data-selected。没有模板或 renderToken 时,容纳每个标记的元素 token-input-host 也带有相同的属性,所以不用自定义结构也能给标记设置样式。
每个部件都有一个 data-slot,比如 token-input-token,并通过数据属性下列出的属性展示它的状态。
数据属性
<ui-token-input-editor>
[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. |
<ui-token-input-token>
[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. |
<ui-token-input-token-remove>
[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 是以短横线连接的属性,比如 submit-shortcut 和 token-deletion。codec、defaultValue、getTokenDescription、history、controller 和 renderToken 是 property。回调是 DOM 事件。
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.
valuechange event- 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 event- 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.
renderToken(token, host) 把每个标记的内容渲染到 host 里。不传它时,元素里的 <template> 会为每个标记复制一份。
TokenInputEditor
placeholder?string- Text shown while the input is empty, through
aria-placeholder. Show it withdata-empty:before:content-[attr(aria-placeholder)].
TokenInputToken
标记的内容,位于模板或 renderToken 内,带有用于样式设置的状态。
TokenInputTokenRemove
按压时移除它所在的标记,并让焦点留在编辑器里。它对辅助技术隐藏,因为键盘用户用 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.
控制器
元素的 api property 有相同的方法。或者用 createTokenInputController() 创建一个,并设置为 controller property。
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.
事件
事件在各自的元素上触发,不冒泡,新状态在 event.detail.value 里。
| 成员 | 所属 | 说明 |
|---|---|---|
value property, attribute | ui-token-input | 值。属性和字符串 property 按编解码器文本读取 |
api property | ui-token-input | 控制器 |
valuechange event | ui-token-input | detail: { value, reason, inputType, removed }:还有原因 |
没有 submit 事件:提交快捷键提交输入框所在的表单,所以表单自己的 submit 事件会收到它。设置 value property 是一个可撤销的步骤,和 setValue() 一样。
无障碍
编辑器是一个多行文本框:它有 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。