Trigger Menu
输入 @、/ 或 # 这类触发字符时,在光标处打开建议。
触发器菜单在有人输入触发字符时提示可以插入什么,比如用 @ 提到人、用 / 调出命令。它在光标处打开,随着输入收窄范围,并把选中的内容插入文本。
import "@ui-sdk/web/trigger-menu"
import "@ui-sdk/web/field"
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-trigger-menu>
<ui-field>
<ui-field-label>Message</ui-field-label>
<ui-trigger-menu-input>
<textarea placeholder="Type @ to mention someone…"></textarea>
</ui-trigger-menu-input>
</ui-field>
<div data-slot="visually-hidden">
<ui-trigger-menu-status></ui-trigger-menu-status>
</div>
<ui-trigger-menu-content>
<ui-trigger-menu-empty>No one found</ui-trigger-menu-empty>
<ui-trigger-menu-list></ui-trigger-menu-list>
</ui-trigger-menu-content>
</ui-trigger-menu>
`
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/trigger-menu"
import "@ui-sdk/web/field"组合
用下面的组合构建 ui-trigger-menu:
ui-trigger-menu
├── ui-trigger-menu-input
│ └── textarea
├── ui-trigger-menu-status
└── ui-trigger-menu-content
├── ui-trigger-menu-empty
└── ui-trigger-menu-list
├── ui-trigger-menu-item
└── ui-trigger-menu-itemui-trigger-menu 持有各个触发器以及每个触发器列出的内容,通过它的 triggers property 设置。ui-trigger-menu-input 包装用户输入的 <textarea> 或 <input>,ui-trigger-menu-content 是带建议的浮层。如果直接子级里没有 ui-trigger-menu-content,菜单会替你渲染当前触发器的条目,没有自己条目的列表也会这样做。放在 Token Input 内部时,省略 ui-trigger-menu-input:菜单会向 token input 提供建议。
用法
导入部件并把它们组合起来:
<script type="module">
import "@ui-sdk/web/trigger-menu"
document.querySelector("ui-trigger-menu").triggers = [{ char: "@" }]
</script>
<ui-trigger-menu>
<ui-trigger-menu-input>
<textarea
aria-label="Message"
placeholder="Type @ to mention someone…"
></textarea>
</ui-trigger-menu-input>
<ui-trigger-menu-content>
<ui-trigger-menu-list>
<ui-trigger-menu-item value="hollis" label="Hollis Grant"
>Hollis Grant</ui-trigger-menu-item
>
<ui-trigger-menu-item value="ines" label="Inès Moreau"
>Inès Moreau</ui-trigger-menu-item
>
</ui-trigger-menu-list>
</ui-trigger-menu-content>
</ui-trigger-menu>label 是条目用来匹配和插入的文本。选择 Hollis Grant 会把 @ 以及它后面输入的内容替换成 @Hollis Grant 。
Trigger Menu 还是 Token Input
Trigger Menu 提示可以插入什么:它匹配触发器、过滤、移动高亮、加载条目,并询问命令的参数。Token Input 持有一个混合了文本和 token 的值。
把 Trigger Menu 与文本域或输入框一起使用,插入文本。把它放进 Token Input,则改为插入 token。其他编辑器通过适配器连接。
以数据形式提供的触发器
给每个触发器一个 char 和它的 items。条目可以是字符串、对象、分组或加载函数,省略 ui-trigger-menu-content 时它们会自己渲染。同一个字段可以在 @ 之后提供人、在 / 之后提供命令、在 # 之后提供频道。
import "@ui-sdk/web/trigger-menu"
import "@ui-sdk/web/field"
import type { TriggerDefinition } from "@ui-sdk/web/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<string>[] = [
{ char: "@", items: people },
{ char: "/", boundary: "start", items: commands },
{ char: "#", items: searchChannels },
]
function mount(root: HTMLElement) {
root.innerHTML = `
<ui-trigger-menu>
<ui-field>
<ui-field-label>Message</ui-field-label>
<ui-trigger-menu-input>
<textarea placeholder="Type @, / or #…"></textarea>
</ui-trigger-menu-input>
</ui-field>
</ui-trigger-menu>
`
root.querySelector("ui-trigger-menu")!.triggers = triggers
}
export { mount }带参数的命令
boundary: "start" 的触发器只在文本开头匹配,所以前面加一个空格就能跳出它。带 arguments 的条目会按顺序询问每个参数:ui-trigger-menu-hint 在光标处显示还剩哪些,Tab 接受高亮的建议并移到下一个参数,只剩可选参数时 Enter 完成,Backspace 越过某个参数的起点则返回上一个。没有 items 的参数是自由文本。after: "submit" 在条目插入后发送表单。
import "@ui-sdk/web/trigger-menu"
import "@ui-sdk/web/field"
import { log } 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" },
]
function mount(root: HTMLElement) {
root.innerHTML = `
<form data-slot="stack">
<ui-trigger-menu>
<ui-field name="message">
<ui-field-label>Message</ui-field-label>
<ui-trigger-menu-input>
<textarea placeholder="Type / for commands…"></textarea>
</ui-trigger-menu-input>
</ui-field>
<ui-trigger-menu-hint></ui-trigger-menu-hint>
</ui-trigger-menu>
</form>
`
const form = root.querySelector("form")!
const menu = root.querySelector("ui-trigger-menu")!
menu.triggers = [
{ char: "/", boundary: "start", type: "command", items: commands },
]
menu.addEventListener("itemselect", (event) => {
log(
root,
[
"Chose",
`/${event.detail.value}`,
...Object.values(event.detail.arguments),
].join(" ")
)
})
form.addEventListener("submit", (event) => {
event.preventDefault()
log(root, `Sent ${new FormData(form).get("message")}`)
})
}
export { mount }图标
把条目的图标放进 ui-trigger-menu-item-icon,放在它的文本之前。屏幕阅读器会跳过它,过滤和选项插入的文本也会忽略它,所以 SVG 的 <title>、图标字体的字形或 emoji 都不会混进条目的名称或字段。以数据形式提供的条目没有图标,所以要显示图标时就自己组合条目。
- 有方向性的图标,比如箭头和回复,在从右到左的文本中用
mirror翻转。 - 只有图标的条目 需要
aria-label,过滤也会匹配它。在开发环境中,没有名称的条目会发出警告。 - 对齐条目。 带图标的条目会得到
data-has-icon,只要有任何条目带图标,列表就得到data-has-icons,这样没有图标的条目可以用内边距留出同样的空间。
import "@ui-sdk/web/trigger-menu"
import "@ui-sdk/web/field"
import { Clock, createElement, Reply, Search, Share, Trash } from "lucide"
const commands = [
{ value: "reply", icon: Reply, mirror: true },
{ value: "remind", icon: Clock },
{ value: "search", icon: Search },
{ value: "share", icon: Share },
{ value: "clear", icon: Trash },
]
function mount(root: HTMLElement) {
root.innerHTML = `
<ui-trigger-menu>
<ui-field>
<ui-field-label>Message</ui-field-label>
<ui-trigger-menu-input>
<textarea placeholder="Type / for commands…"></textarea>
</ui-trigger-menu-input>
</ui-field>
<ui-trigger-menu-content>
<ui-trigger-menu-list>
${commands
.map(
(command) => `
<ui-trigger-menu-item value="${command.value}">
<ui-trigger-menu-item-icon${command.mirror ? " mirror" : ""}>
${createElement(command.icon, { "aria-hidden": "true" }).outerHTML}
</ui-trigger-menu-item-icon>
${command.value}
</ui-trigger-menu-item>`
)
.join("")}
</ui-trigger-menu-list>
</ui-trigger-menu-content>
</ui-trigger-menu>
`
root.querySelector("ui-trigger-menu")!.triggers = [
{ char: "/", boundary: "start", type: "command" },
]
}
export { mount }加载条目
触发器的 items 可以是加载函数,输入停顿后会用查询和 AbortSignal 调用。更新的查询会中止更早的加载,所以只有它的结果会被采用,下一批加载期间上一次的结果会保留。ui-trigger-menu-empty 会等到加载结束,期间得到 data-loading;加载运行时 aria-busy 会标记列表,这样你可以淡出即将变化的结果。这个示例根据 openchange、querychange 和加载函数的结果自己写入状态文本。
import "@ui-sdk/web/trigger-menu"
import "@ui-sdk/web/field"
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)
})
})
}
function mount(root: HTMLElement) {
root.innerHTML = `
<ui-trigger-menu>
<ui-field>
<ui-field-label>Message</ui-field-label>
<ui-trigger-menu-input>
<textarea placeholder="Type # to link a channel…"></textarea>
</ui-trigger-menu-input>
</ui-field>
<ui-trigger-menu-content>
<ui-trigger-menu-status>Loading channels…</ui-trigger-menu-status>
<ui-trigger-menu-empty>No channels match “<span></span>”</ui-trigger-menu-empty>
<ui-trigger-menu-list></ui-trigger-menu-list>
</ui-trigger-menu-content>
</ui-trigger-menu>
`
const menu = root.querySelector("ui-trigger-menu")!
const status = root.querySelector("ui-trigger-menu-status")!
const query = root.querySelector("ui-trigger-menu-empty span")!
const loading = () => {
status.textContent = "Loading channels…"
}
menu.triggers = [
{
char: "#",
type: "channel",
items: async (text, context) => {
const items = await searchChannels(text, context)
status.textContent = items.length
? `${items.length} ${items.length === 1 ? "channel" : "channels"}`
: ""
return items
},
},
]
menu.addEventListener("openchange", (event) => {
if (event.detail.value) {
loading()
}
})
menu.addEventListener("querychange", (event) => {
query.textContent = event.detail.value
loading()
})
}
export { mount }自定义条目
用任意内容组合 ui-trigger-menu-item,可以放在分组里。label 是被匹配和插入的内容,keywords 增加可匹配的词,disabled 让条目留在列表里但不能被选中。触发器的 spaces、pattern 和 maxLength 决定查询可以包含什么,filter 决定它如何收窄条目,insert 决定用什么替换触发器和查询。菜单的 itemselect 事件先给出选中的条目,可以用 event.detail.insert() 插入别的内容。
import "@ui-sdk/web/trigger-menu"
import "@ui-sdk/web/field"
import { createElement, Users } 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", disabled: true },
]
function mount(root: HTMLElement) {
root.innerHTML = `
<ui-trigger-menu>
<ui-field>
<ui-field-label>Message</ui-field-label>
<ui-trigger-menu-input>
<textarea placeholder="Type @ and a first name…"></textarea>
</ui-trigger-menu-input>
</ui-field>
<ui-trigger-menu-content>
<ui-trigger-menu-list>
<ui-trigger-menu-group>
<ui-trigger-menu-group-label>People</ui-trigger-menu-group-label>
${people
.map(
(person) => `
<ui-trigger-menu-item value="${person.value}" label="${person.label}"${person.disabled ? " disabled" : ""}>
${person.label}
<span data-slot="hint">${person.disabled ? "Deactivated" : `@${person.value}`}</span>
</ui-trigger-menu-item>`
)
.join("")}
</ui-trigger-menu-group>
<ui-trigger-menu-separator></ui-trigger-menu-separator>
<ui-trigger-menu-item value="here" label="here" keywords="everyone,channel">
<ui-trigger-menu-item-icon>
${createElement(Users, { "aria-hidden": "true" }).outerHTML}
</ui-trigger-menu-item-icon>
Notify everyone here
</ui-trigger-menu-item>
</ui-trigger-menu-list>
</ui-trigger-menu-content>
</ui-trigger-menu>
`
const menu = root.querySelector("ui-trigger-menu")!
menu.triggers = [
{
char: "@",
spaces: 2,
maxLength: 30,
pattern: /[\p{L}.'-]/u,
filter: "startsWith",
insert: (item) => `@${item.label.split(" ")[0]} `,
},
]
menu.addEventListener("itemselect", (event) => {
if (event.detail.value === "here") {
event.detail.insert("@here ")
}
})
}
export { mount }输入框
把 <input> 放进输入部件来使用单行。它是一个带 aria-expanded 的组合框。在单行里,Enter 常常会提交表单,所以这个示例设置了 auto-highlight="false":只有方向键高亮了某个人之后,Enter 才会选择;loop="false" 让方向键在列表两端停住。
import "@ui-sdk/web/trigger-menu"
import "@ui-sdk/web/field"
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-trigger-menu auto-highlight="false" loop="false">
<ui-field>
<ui-field-label>Task</ui-field-label>
<ui-trigger-menu-input>
<input placeholder="Type @ to assign someone…" />
</ui-trigger-menu-input>
</ui-field>
<ui-trigger-menu-content>
<ui-trigger-menu-list></ui-trigger-menu-list>
</ui-trigger-menu-content>
</ui-trigger-menu>
`
root.querySelector("ui-trigger-menu")!.triggers = [
{ char: "@", items: people },
]
}
export { mount }定位
默认情况下,列表在光标处、触发器的下方打开,放不下时会翻转以留在屏幕内。side、align 和各个偏移量决定它的位置,anchor 让它贴着另一个元素定位,用 CSS 选择器指定。这个示例把列表开在整个字段的上方,让它的条目与标签对齐。
import "@ui-sdk/web/trigger-menu"
import "@ui-sdk/web/field"
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) {
const id = `comment-${crypto.randomUUID()}`
root.innerHTML = `
<ui-trigger-menu>
<ui-field id="${id}">
<ui-field-label>Comment</ui-field-label>
<ui-trigger-menu-input>
<textarea placeholder="Type @ to mention someone…"></textarea>
</ui-trigger-menu-input>
</ui-field>
<ui-trigger-menu-content
side="top"
align="start"
side-offset="8"
align-offset="-5"
collision-padding="16"
anchor="#${id}"
container="#${id}"
keep-mounted
>
<ui-trigger-menu-list></ui-trigger-menu-list>
</ui-trigger-menu-content>
</ui-trigger-menu>
`
root.querySelector("ui-trigger-menu")!.triggers = [
{ char: "@", items: people },
]
}
export { mount }受控
设置 open property 并监听 openchange,自己持有浮层状态。详情会说明它为什么变化。querychange 报告触发器后面的文本和正在输入的参数,openchangecomplete 在菜单完成打开或关闭后触发。Escape 会关闭匹配项,shortcut 可以重新打开它,默认是 Control+Space。
import "@ui-sdk/web/trigger-menu"
import "@ui-sdk/web/field"
import { log } 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"],
},
],
},
]
function mount(root: HTMLElement) {
root.innerHTML = `
<ui-trigger-menu shortcut="ctrl+j">
<ui-field>
<ui-field-label>Message</ui-field-label>
<ui-trigger-menu-input>
<textarea placeholder="Type @ or /…"></textarea>
</ui-trigger-menu-input>
</ui-field>
</ui-trigger-menu>
`
const menu = root.querySelector("ui-trigger-menu")!
menu.triggers = [
{ char: "@", items: people },
{ char: "/", boundary: "start", items: commands },
]
menu.addEventListener("openchange", (event) => {
const { value, reason } = event.detail
log(root, `${value ? "Opening" : "Closing"} (${reason})`)
})
menu.addEventListener("openchangecomplete", (event) =>
log(root, event.detail.value ? "Open" : "Closed")
)
menu.addEventListener("querychange", (event) => {
const { value, argument } = event.detail
log(root, `Query “${value}”${argument ? ` for ${argument}` : ""}`)
})
}
export { mount }控制器
用元素的 api 打开建议、在光标处插入文本,或读取当前的匹配项。open() 会在光标处输入触发器,并返回一个在菜单关闭时兑现的 Promise。
import "@ui-sdk/web/trigger-menu"
import "@ui-sdk/web/field"
import { log } 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" },
]
function mount(root: HTMLElement) {
root.innerHTML = `
<div data-slot="stack">
<div data-slot="controls">
<button type="button">Mention</button>
<button type="button">Insert Date</button>
</div>
<ui-trigger-menu>
<ui-field>
<ui-field-label>Message</ui-field-label>
<ui-trigger-menu-input>
<textarea placeholder="Write a message…"></textarea>
</ui-trigger-menu-input>
</ui-field>
<ui-trigger-menu-content>
<ui-trigger-menu-list></ui-trigger-menu-list>
</ui-trigger-menu-content>
</ui-trigger-menu>
</div>
`
const element = root.querySelector("ui-trigger-menu")!
const menu = element.api
element.triggers = [{ char: "@", items: people }]
const [mention, date] = root.querySelectorAll("button")
root
.querySelector("[data-slot=controls]")!
.addEventListener("mousedown", (event) => event.preventDefault())
mention.addEventListener("click", async () => {
const closed = await menu.open({ trigger: "@" })
log(root, `Closed (${closed.reason})`)
})
date.addEventListener("click", () =>
menu.insert(
new Date().toLocaleDateString("en-US", { month: "long", day: "numeric" })
)
)
}
export { mount }任意编辑器
设置 editor property,把菜单连接到你自己渲染的字段,或另一个编辑器。textFieldAdapter() 可以为文本域或输入框创建一个。
import "@ui-sdk/web/trigger-menu"
import "@ui-sdk/web/field"
import { textFieldAdapter } from "@ui-sdk/web/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" },
]
function mount(root: HTMLElement) {
root.innerHTML = `
<ui-trigger-menu>
<ui-field>
<ui-field-label>Notes</ui-field-label>
<textarea placeholder="Type @ to mention someone…"></textarea>
</ui-field>
<ui-trigger-menu-content>
<ui-trigger-menu-list></ui-trigger-menu-list>
</ui-trigger-menu-content>
</ui-trigger-menu>
`
const menu = root.querySelector("ui-trigger-menu")!
menu.editor = textFieldAdapter(root.querySelector("textarea")!)
menu.triggers = [{ char: "@", items: people }]
}
export { mount }为其他编辑器编写的适配器会读取它的文本和选区,测量某个偏移处的矩形,替换一段范围,作为一步撤销,并报告变更。不是用户做出的变更要用 user: false 报告,比如协作者的变更,菜单就不会为它们打开。
elementHTMLElement- 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
lengthcharacters 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
listenerfor text edits, caret moves and composition. Returns a cleanup. composing() => boolean- Whether an input method is composing.
tokens?boolean- Whether
replaceaccepts 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 自己管理 token 历史。
自定义渲染
元素没有渲染函数。ui-trigger-menu-input 包装你自己的 <textarea>,或像输入示例那样包装一个 <input>,这里的每个示例都把它放进 ui-field 来加入 Field。把你自己标记放进其他部件里,比如自定义条目示例中每个人后面的提示。部件与组合介绍了渲染约定,每个部件的状态列在状态下。
样式
为字段、浮层和它的条目设置样式。内容会显示 data-trigger,所以每个触发器的列表可以长得不一样,比如用等宽字体显示命令。条目会显示 data-highlighted 和 data-disabled,在包含 ui-trigger-menu-item-icon 时显示 data-has-icon;只要有任何条目带图标,列表就显示 data-has-icons。用 aria-busy 让加载中的列表淡出,并把提示样式设为幽灵文本(ghost text):它的位置会替你放在光标处。
每个部件都有一个 data-slot,比如 trigger-menu-item,它的状态属性列在数据属性下。
<ui-trigger-menu-content>
| 变量 | 内容 |
|---|---|
--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. |
数据属性
<ui-trigger-menu-input>
[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. |
<ui-trigger-menu-content>
[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 | toprightbottomleftWhere the list ended up, after flipping away from edges. |
data-align | startcenterendHow 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. |
<ui-trigger-menu-item>
[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. |
<ui-trigger-menu-empty>
[data-slot="trigger-menu-empty"]
| 属性 | 含义 |
|---|---|
data-empty | Present while no item matches. |
data-loading | Present while items load. |
<ui-trigger-menu-item-icon>
[data-slot="trigger-menu-item-icon"]
| 属性 | 含义 |
|---|---|
data-mirror | Present on an icon that flips in right-to-left text, with mirror. |
API 参考
props 是 kebab 写法的属性,比如 auto-highlight 和 side-offset。triggers、editor 和 controller 是 property,anchor 接受 CSS 选择器。回调是 DOM 事件。
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.
triggersTriggerDefinition<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.
openchange event- Runs when the menu wants to open or close.
details.reasonsays why,details.triggerwhich trigger, anddetails.cancel()stops it. openchangecomplete event- Runs once the menu has finished opening or closing, after any animation.
querychange event- Runs when the text after the trigger changes. Read-only: it's the editor's text.
details.argumentnames the argument being typed. select event- 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
selectPromise 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
falsewhile it holds unsaved work, and ask indismissattempt. dismissattempt event- Runs when
dismissiblerefused 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.
触发器
charstring- 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.
以数据形式提供的条目
valueT- Identifies the item, and is what choosing it reports. A string, or any value with
itemToValue. labelstring- 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>.
参数
namestring- 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> 或一个 <input>。
TriggerMenuStatus
一个礼貌的状态区域(polite live region),在输入停顿后播报数量和按键。给它自己的内容来播报别的内容,并在菜单变化时更新这段文本。
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.
startandendfollow 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 withgetBoundingClientRect(). It's read on every check, so it can move. A controller'sopen({ 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
在没有条目匹配时显示。渲染它会让菜单在没有匹配时保持打开;不渲染它,菜单会一直关闭,直到有内容匹配。
TriggerMenuList
列表框(listbox)。没有自己的条目时,它渲染当前触发器的条目。
TriggerMenuItem
valueT- What
selectreceives 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.
select event- Runs before the menu's
select.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
一组条目,由它的标签命名。
TriggerMenuSeparator
条目或分组之间的一条线,对屏幕阅读器隐藏。
TriggerMenuHint
光标处的幽灵文本,显示还要输入的参数,比如 <status>,对屏幕阅读器隐藏。
状态
每个部件的状态包含什么。元素没有渲染函数,所以部件通过数据属性下列出的属性展示状态。
TriggerMenuInput:
openboolean- 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.
triggerstring | null- The trigger of the current match, like
"@", or null.
TriggerMenuContent and TriggerMenuList:
openboolean- Whether the menu is open. False while it animates out.
triggerstring | null- The trigger of the current match, like
"@", or null. querystring- The text after the trigger, or after the current argument's start.
argumentstring | null- The argument being typed, by name, or null at the first level.
statusAsyncOptionsStatus- Whether items are loading or failed.
itemsTriggerMenuData<unknown>- The visible data items, for rendering them yourself.
TriggerMenuItem:
highlightedboolean- Whether the item is highlighted, by the keyboard or the pointer.
disabledboolean- Whether the item can't be chosen.
TriggerMenuItemIcon:
mirrorboolean- Whether it flips in right-to-left text.
TriggerMenuEmpty:
loadingboolean- Whether items are loading.
emptyboolean- Whether no item matches.
querystring- The text after the trigger.
TriggerMenuStatus:
openboolean- 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.
statusAsyncOptionsStatus- Whether items are loading or failed.
loadingboolean- Whether items are loading.
countnumber- How many items match.
argumentstring | null- The argument being typed, by name, or null.
TriggerMenuHint:
argumentstring | null- The argument being typed, by name, or null.
hintstring- The ghost text: the hints of the arguments still to type.
原因
event.detail.reason 说明菜单为什么打开或关闭。
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.
caret-moveEvent | KeyboardEvent | PointerEvent- The caret left a trigger menu's match: an arrow key, Home or End, a click, or a selection change.
item-pressMouseEvent | KeyboardEvent- A member of a collection was chosen: a menu item, a tab, a radio or a checkbox item.
escape-keyKeyboardEvent- Escape, or a submenu's close key (ArrowLeft in left-to-right layouts).
close-pressMouseEvent | KeyboardEvent | SubmitEvent- A Close part was pressed, or a form with
method="dialog"was submitted. outside-pressMouseEvent- A press outside the layer.
focus-outKeyboardEvent | FocusEvent- Focus left the layer, or Tab moved it out.
window-blurFocusEvent- The window lost focus.
anchor-hiddennone- The element the popup sits beside stopped rendering, like a trigger a breakpoint hides.
imperativenone- A controller or
apicall. shortcutKeyboardEvent- A keyboard shortcut, like a trigger's
shortcut.
dismissible 为 false 时,dismissattempt 报告的、被拒绝的关闭尝试:
escape-keyKeyboardEvent- Escape, or a submenu's close key (ArrowLeft in left-to-right layouts).
outside-pressMouseEvent- A press outside the layer.
查询为什么变化:
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.
item-pressMouseEvent | KeyboardEvent- A member of a collection was chosen: a menu item, a tab, a radio or a checkbox item.
imperativenone- A controller or
apicall.
控制器
元素的 api property 有相同的方法。也可以用 createTriggerMenuController() 创建一个,并设置为 controller property。
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.
事件
事件在 <ui-trigger-menu> 上触发,不冒泡,新状态在 event.detail.value 中,详情在它旁边。选择条目会在菜单上触发 itemselect,而不是字段为选中文本触发的 select。
| 成员 | 所属 | 说明 |
|---|---|---|
triggers property | ui-trigger-menu | 触发器和每个触发器列出的内容 |
editor property | ui-trigger-menu | 编辑器适配器,用于没有输入部件的字段 |
open property | ui-trigger-menu | 菜单是否打开 |
api property | ui-trigger-menu | 控制器 |
openchange event | ui-trigger-menu | detail: { value: open, reason, trigger }:新状态、原因 和 trigger |
openchangecomplete event | ui-trigger-menu | detail: { value: open },在动画之后 |
querychange event | ui-trigger-menu | detail: { value: query, reason, trigger, argument }:触发器后面的文本,以及参数 |
dismissattempt event | ui-trigger-menu | detail: { reason, event },在关闭尝试被拒绝时 |
itemselect event | ui-trigger-menu | detail: { value, arguments, insert(), waitUntil(promise) }。preventDefault() 会跳过插入 |
当 itemselect 监听器把 Promise 传给 event.detail.waitUntil() 且编辑器接受 token 时,token 会立即插入并带有 data-pending,用 Promise 兑现的值更新,被拒绝时移除。无论哪种情况菜单都会关闭,让人可以继续输入。
无障碍
方向键移动高亮时,焦点留在字段里。<textarea> 保持 textbox 角色,这是 ARIA 允许它使用的唯一角色,并用 aria-controls 指向列表,按过方向键后再用 aria-activedescendant。<input> 是带 aria-expanded 的组合框。数量和加载状态通过 ui-trigger-menu-status 播报,它是一个礼貌的状态区域,绝不通过字段播报,所以一定要渲染一个:视觉上隐藏(如示例所示),或放在列表顶部(如加载条目所示)。通过 Field 或 aria-label 给字段一个可见的名称。
键盘
| 按键 | 作用 |
|---|---|
| ArrowDown, ArrowUp | 列表打开时移动高亮;光标留在字段里 |
| Enter | 选择高亮的条目。在命令的参数中,只剩可选参数时完成 |
| Tab | 选择高亮的条目,或接受一个参数并移到下一个 |
| Escape | 关闭列表并关闭这次匹配,之后继续输入不会重新打开它 |
| Control+Space | 重新打开已关闭的匹配,光标留在其中;shortcut 可以换键 |
| Backspace | 越过某个参数的起点时,返回上一个参数 |
| Command+Z, Control+Z | 撤销插入并恢复查询 |
经过测试的行为
下面每一行都是一个自动化测试。
- Typing a trigger opens the list with every item.
- A field controlled through onChange keeps the typed trigger and opens the list. 仅在 React 运行。
- 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.
- 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.
- 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.
- 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.
- Items load for the query.
- A newer query aborts the older load, and only its results land.
- Undo after choosing brings the query back, never a dead undo.
- The SDK's Textarea works as the field, and undo still works.
- An <input> field works the same.
运行于 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.
运行于 React、Vue 和 web components。