CLI 将组件源(及其内部依赖项)复制到您的项目中并安装任何所需的 npm 包。
npx boardui@latest add token-input使用共享 UI 包或自定义导入别名? 配置您的安装路径 在运行 CLI 之前。复制粘贴示例使用默认导入。
触发器
每个触发器是一个字符以及它打开的建议。匹配从词首开始,使用 boundary: "start" 时只在提示的最开头开始;菜单随输入过滤,忽略大小写和重音。items 可以是数据,也可以是在输入停顿后接收查询和 AbortSignal 的加载函数。tone: "accent" 用强调色绘制标签,emptyState 在没有匹配时让菜单保持打开。
import { RiFileCodeLine, RiSearchEyeLine } from "@remixicon/react";import type { TokenSuggestion, TokenTrigger } from "@/components/base/token-input/token-input";
const files: TokenSuggestion[] = [ { id: "app/page.tsx", label: "page.tsx", description: "app", icon: RiFileCodeLine }, { id: "components/sidebar.tsx", label: "sidebar.tsx", description: "components", icon: RiFileCodeLine },];
const triggers: TokenTrigger[] = [ // "@" at any word start, filtered as you type. { char: "@", type: "file", title: "Files", items: files }, // "/" only at the very start, as accent chips. { char: "/", type: "command", title: "Commands", boundary: "start", tone: "accent", items: commands }, // Items from a server: called with the query once typing pauses; a newer query aborts the older one. { char: "#", type: "issue", title: "Issues", emptyState: "No issues match", items: (query, signal) => fetch(`/api/issues?q=${query}`, { signal }).then((r) => r.json()), },];Token 与文本
值是按顺序排列的文本和 token。toText 把它写成文本,每个 token 写作 [@label](type:value),用于请求、表单或保存的草稿;fromText 把这段文本读回 token。复制会写出同样的文本,因此粘贴到任何 token 输入框都会还原标签。传入 codec 可使用自定义格式。
import { TokenInput, fromText, toText, type TokenInputValue } from "@/components/base/token-input/token-input";
const [value, setValue] = useState<TokenInputValue>([]);// ["Review ", { type: "file", value: "components/sidebar.tsx", label: "sidebar.tsx", id: "t1" }, " please"]
toText(value); // "Review [@sidebar.tsx](file:components/sidebar.tsx) please"fromText("Review [@sidebar.tsx](file:components/sidebar.tsx) please"); // the value again
<TokenInput aria-label="Message" value={value} onValueChange={setValue} triggers={triggers} />键盘
对光标来说,一个标签就是一个字符。输入、输入法、拼写检查和自动更正仍由浏览器处理;凡是涉及标签的操作都经过字段自己的历史记录。
删除 token
tokenDeletion 决定在标签旁按 Backspace 时的行为,ref 句柄可以用代码编辑字段:在光标处插入 token、聚焦、清空。每项操作都是一步撤销。
<TokenInput tokenDeletion="whole" /> {/* Backspace removes the chip (default) */}<TokenInput tokenDeletion="select" /> {/* first press selects it, the second removes it */}<TokenInput tokenDeletion="revert" /> {/* the chip turns back into "@label" and its menu reopens */}在对话输入面板中
Pro 版对话输入面板接受同样的 triggers:其提示框变为 Token 输入框,仍然发送字符串。
致谢
编辑和匹配规则依据 Apache License 2.0 移植自 UI SDK 的 Token Input 和 Trigger Menu,并附带其单元测试。菜单采用 React Aria 的 Autocomplete、Menu 和 Popover,使用 BoardUI 紧凑下拉菜单的样式。