Tooltip
为控件命名,或在悬停和键盘焦点时补上一句简短提示。
当指针停在控件上或键盘焦点到达时,tooltip 为控件命名,或补上一句简短提示。保持纯文本,几个词就够。
"use client"
import { Tooltip, TooltipContent, TooltipTrigger } from "@ui-sdk/react/tooltip"
import { BookmarkIcon } from "lucide-react"
function Example() {
return (
<Tooltip defaultOpen>
<TooltipTrigger aria-label="Add to library">
<BookmarkIcon aria-hidden="true" />
</TooltipTrigger>
<TooltipContent>Add to library</TooltipContent>
</Tooltip>
)
}
export { Example }安装
npm install @ui-sdk/react @ui-sdk/core组合
用下面的组合构建 Tooltip:
Tooltip
├── TooltipTrigger
└── TooltipContent
├── TooltipArrow
└── TooltipShortcut把触发器和它的提示包进一个 tooltip。箭头和快捷键是可选的。
内容带有 tooltip 角色,并且从一开始就在页面里,只是隐藏着,所以在焦点到达之前,它就能为触发器命名或描述触发器。它会为没有自己名称的触发器命名,比如只有图标的按钮,并描述其他触发器,也就是带文本、aria-label 或 title 的那些。type="label" 或 type="description" 会覆盖这一判断。判断发生在浏览器里,所以在那之前,服务端渲染的 HTML 会描述只有图标的触发器。传入 type="label",让它从最初的 HTML 开始就被命名。只放纯文本:tooltip 无法获得焦点,所以里面的链接或按钮也无法到达。需要交互时,请使用 Popover 或 Hover Card。
用法
导入部件并把它们组合起来:
import { Tooltip, TooltipContent, TooltipTrigger } from "@ui-sdk/react/tooltip"
function Example() {
return (
<Tooltip>
<TooltipTrigger>Share</TooltipTrigger>
<TooltipContent>Anyone with the link can view</TooltipContent>
</Tooltip>
)
}
export { Example }方向
side 选择 tooltip 打开的方向:默认是 top。空间不够时,它会翻到另一侧,并沿触发器平移以留在屏幕内。data-side 报告它最终落在哪里。
"use client"
import { Tooltip, TooltipContent, TooltipTrigger } from "@ui-sdk/react/tooltip"
const sides = [
{ side: "top", label: "Top" },
{ side: "left", label: "Left" },
{ side: "right", label: "Right" },
{ side: "bottom", label: "Bottom" },
] as const
function Example() {
return (
<div data-slot="grid">
{sides.map(({ side, label }) => (
<Tooltip key={side}>
<TooltipTrigger>{label}</TooltipTrigger>
<TooltipContent side={side}>Add to library</TooltipContent>
</Tooltip>
))}
</div>
)
}
export { Example }添加 TooltipArrow 来指向触发器。它跟随 tooltip 最终的落点,翻转之后也是如此。
<TooltipContent>
<TooltipArrow />
Add to library
</TooltipContent>锚点
用 anchor 让 tooltip 贴着触发器以外的东西定位:元素、CSS 选择器、像 { x, y } 这样的点,或任何带 getBoundingClientRect() 的对象。这里字段里的小帮助按钮会让它的 tooltip 与整个字段对齐。
"use client"
import { Field, FieldLabel } from "@ui-sdk/react/field"
import { Input } from "@ui-sdk/react/input"
import { Tooltip, TooltipContent, TooltipTrigger } from "@ui-sdk/react/tooltip"
import { InfoIcon } from "lucide-react"
import * as React from "react"
function Example() {
const [field, setField] = React.useState<HTMLDivElement | null>(null)
return (
<Field>
<FieldLabel>Webhook URL</FieldLabel>
<div data-slot="row" ref={setField}>
<Input placeholder="https://" />
<Tooltip>
<TooltipTrigger aria-label="About webhooks">
<InfoIcon aria-hidden="true" />
</TooltipTrigger>
<TooltipContent anchor={field} side="bottom" align="start">
We send a POST request here for every new order.
</TooltipContent>
</Tooltip>
</div>
</Field>
)
}
export { Example }键盘快捷键
tooltip 上的 shortcut,比如 "mod+s",提示触发器的动作绑定在什么按键上;其中 mod 在 Apple 平台上是 Command,在其他平台上是 Control。TooltipShortcut 显示当前平台的按键,⌘S 或 Ctrl+S,对屏幕阅读器隐藏,触发器则会得到 aria-keyshortcuts,让屏幕阅读器改为听到它。TooltipShortcut 可以用自己的 shortcut 显示其他按键。
tooltip 不会绑定这些按键。像示例那样,用 registerShortcut 自己注册快捷键,或使用会绑定按键的组件的 shortcut,比如 Dialog 的触发器。
"use client"
import { registerShortcut } from "@ui-sdk/core/shortcuts"
import {
Tooltip,
TooltipContent,
TooltipShortcut,
TooltipTrigger,
} from "@ui-sdk/react/tooltip"
import { SaveIcon } from "lucide-react"
import * as React from "react"
import { useLog } from "./log"
function Example() {
const log = useLog()
React.useEffect(() => {
const offSave = registerShortcut("mod+s", () => log("Saved"))
const offShare = registerShortcut("mod+shift+e", () => log("Shared"))
return () => {
offSave()
offShare()
}
}, [log])
return (
<div data-slot="row">
<Tooltip shortcut="mod+s">
<TooltipTrigger aria-label="Save" onClick={() => log("Saved")}>
<SaveIcon aria-hidden="true" />
</TooltipTrigger>
<TooltipContent>
Save
<TooltipShortcut />
</TooltipContent>
</Tooltip>
<Tooltip shortcut="mod+shift+e">
<TooltipTrigger onClick={() => log("Shared")}>Share</TooltipTrigger>
<TooltipContent>
Share with your team
<TooltipShortcut />
</TooltipContent>
</Tooltip>
</div>
)
}
export { Example }禁用的按钮
原生禁用的按钮无法接收焦点,而且有些浏览器不会给它发送指针事件,所以它的 tooltip 永远不会显示。当 tooltip 用来解释某个操作为什么不可用时,改用 aria-disabled="true",并由你自己忽略按钮的按压。按钮会留在 Tab 顺序中,屏幕阅读器会把它播报为变暗,tooltip 则说明缺了什么。按钮恢复可用后,tooltip 上的 disabled 会关掉这条说明。
"use client"
import { Field, FieldLabel } from "@ui-sdk/react/field"
import { Input } from "@ui-sdk/react/input"
import { Tooltip, TooltipContent, TooltipTrigger } from "@ui-sdk/react/tooltip"
import * as React from "react"
import { useLog } from "./log"
function Example() {
const log = useLog()
const [title, setTitle] = React.useState("")
const blocked = !title.trim()
return (
<div data-slot="stack">
<Field>
<FieldLabel>Post title</FieldLabel>
<Input value={title} onValueChange={(value) => setTitle(value)} />
</Field>
<Tooltip disabled={!blocked}>
<TooltipTrigger
data-variant="solid"
aria-disabled={blocked || undefined}
onClick={() => {
if (!blocked) {
log(`Published “${title.trim()}”`)
}
}}
>
Publish
</TooltipTrigger>
<TooltipContent side="right">Add a title to publish</TooltipContent>
</Tooltip>
</div>
)
}
export { Example }触摸
触摸屏没有悬停。轻点普通 tooltip 的触发器只会按压它,tooltip 仍然关闭,所以不要把重要内容藏在 tooltip 里。
如果某个信息按钮的唯一职责就是显示这条提示,就加上 toggleable:用手指、鼠标或键盘按压触发器可以打开和关闭 tooltip,按压打开时它的文本会被播报。外部按压或 Escape 也能关闭它。
"use client"
import { Tooltip, TooltipContent, TooltipTrigger } from "@ui-sdk/react/tooltip"
import { InfoIcon } from "lucide-react"
function Example() {
return (
<div data-slot="row">
<span data-slot="label">Storage</span>
<Tooltip toggleable>
<TooltipTrigger aria-label="About storage" data-size="sm">
<InfoIcon aria-hidden="true" />
</TooltipTrigger>
<TooltipContent>Files in the trash still use storage.</TooltipContent>
</Tooltip>
<span data-slot="hint">12.4 of 15 GB used</span>
</div>
)
}
export { Example }按压时保持打开
按压触发器会关闭 tooltip,这样它不会遮住按压带来的变化,而且在指针离开之前会保持关闭。closeOnPress={false} 会让它保持打开,比如复制按钮的 tooltip 会变成 Copied。
"use client"
import { Tooltip, TooltipContent, TooltipTrigger } from "@ui-sdk/react/tooltip"
import { CheckIcon, CopyIcon } from "lucide-react"
import * as React from "react"
const command = "npm install @ui-sdk/react"
function Example() {
const [copied, setCopied] = React.useState(false)
return (
<div data-slot="row">
<code>{command}</code>
<Tooltip
closeOnPress={false}
onOpenChangeComplete={(open) => !open && setCopied(false)}
>
<TooltipTrigger
aria-label={copied ? "Copied" : "Copy"}
onClick={() => {
navigator.clipboard?.writeText(command).catch(() => {})
setCopied(true)
}}
>
{copied ? (
<CheckIcon aria-hidden="true" />
) : (
<CopyIcon aria-hidden="true" />
)}
</TooltipTrigger>
<TooltipContent>{copied ? "Copied" : "Copy"}</TooltipContent>
</Tooltip>
</div>
)
}
export { Example }被截断的文本
如果只想在文本被截断时才显示 tooltip,就在文本放得下时,于 onOpenChange 中取消这次打开。在回调里比较 scrollWidth 和 clientWidth。tooltip 会重复这个名称,所以 type="label" 可以避免屏幕阅读器听到两遍。
"use client"
import { Tooltip, TooltipContent, TooltipTrigger } from "@ui-sdk/react/tooltip"
import { FileIcon } from "lucide-react"
import * as React from "react"
const files = [
"Quarterly report, final revised version for the board.pdf",
"Notes.txt",
"Design review recording, October 2nd.mp4",
"Budget.xlsx",
]
function FileRow({ name }: { name: string }) {
const text = React.useRef<HTMLSpanElement>(null)
return (
<li>
<Tooltip
type="label"
onOpenChange={(open, details) => {
const span = text.current
if (open && span && span.scrollWidth <= span.clientWidth) {
details.cancel()
}
}}
>
<TooltipTrigger>
<FileIcon aria-hidden="true" />
<span ref={text}>{name}</span>
</TooltipTrigger>
<TooltipContent>{name}</TooltipContent>
</Tooltip>
</li>
)
}
function Example() {
return (
<ul>
{files.map((file) => (
<FileRow key={file} name={file} />
))}
</ul>
)
}
export { Example }受控
传入 open,并在 onOpenChange 中更新它。每次变更都带有原因,比如 trigger-hover、trigger-focus、trigger-press、escape-key 或 outside-press。调用 details.cancel() 可以阻止它。要从任何地方打开 tooltip,比如分步引导中的某一步,请使用控制器。
"use client"
import { Checkbox, CheckboxIndicator } from "@ui-sdk/react/checkbox"
import { Tooltip, TooltipContent, TooltipTrigger } from "@ui-sdk/react/tooltip"
import { CheckIcon } from "lucide-react"
import * as React from "react"
import { useLog } from "./log"
function Example() {
const log = useLog()
const [open, setOpen] = React.useState(false)
const controls = React.useRef<HTMLDivElement>(null)
return (
<div data-slot="stack">
<div data-slot="controls" ref={controls}>
<label data-slot="label">
<Checkbox
checked={open}
onCheckedChange={(next) => setOpen(next === true)}
>
<CheckboxIndicator>
<CheckIcon aria-hidden="true" />
</CheckboxIndicator>
</Checkbox>
Open
</label>
</div>
<Tooltip
open={open}
onOpenChange={(next, details) => {
const target = details.event?.target
const inControls =
target instanceof Node && controls.current?.contains(target)
if (inControls && details.reason !== "escape-key") {
return details.cancel()
}
setOpen(next)
log(`${next ? "Opened" : "Closed"} (${details.reason})`)
}}
>
<TooltipTrigger>Export</TooltipTrigger>
<TooltipContent>Download as CSV</TooltipContent>
</Tooltip>
</div>
)
}
export { Example }共享
工具栏、图表或长列表可以共用一个 tooltip,而不是为每一项各渲染一个。把触发器和 tooltip 连接到同一个 createTooltipController<Payload>(),触发器就可以放在页面上的任何位置。每个触发器传入一个 payload,这里是它的标签;内容从自己的状态里读取它,因为每个部件的 children 都可以是状态的函数。TooltipContent<string> 为 payload 指定类型。内容在首次打开之前就会渲染,所以要处理 undefined 的 payload。
只有打开 tooltip 的那个触发器会被它描述,所以给每个触发器一个自己的名称,比如 aria-label。控制器的 open() 也接受 payload 和 anchor;在已打开的 tooltip 上,open({ payload }) 会替换 payload,就像另一个触发器接管了它。onPayloadChange 报告每次变更。
当另一个触发器接管打开的 tooltip 时,tooltip 会移到它那里。把 left 和 top 加入内容的 transition,它就会滑过去而不是跳过去。打开时的第一次放置永远不做动画,所以它不会从某个角落飞进来。
"use client"
import {
createTooltipController,
Tooltip,
TooltipContent,
TooltipTrigger,
} from "@ui-sdk/react/tooltip"
import { BoldIcon, ItalicIcon, UnderlineIcon } from "lucide-react"
import * as React from "react"
const formats = [
{ icon: BoldIcon, label: "Bold" },
{ icon: ItalicIcon, label: "Italic" },
{ icon: UnderlineIcon, label: "Underline" },
]
function Example() {
const [tooltip] = React.useState(() => createTooltipController<string>())
return (
<div data-slot="row" role="group" aria-label="Formatting">
{formats.map((format) => (
<TooltipTrigger
key={format.label}
controller={tooltip}
payload={format.label}
aria-label={format.label}
>
<format.icon aria-hidden="true" />
</TooltipTrigger>
))}
<Tooltip controller={tooltip}>
<TooltipContent<string>>{(state) => state.payload}</TooltipContent>
</Tooltip>
</div>
)
}
export { Example }动画
内容在打开时带有 data-starting-style,关闭时带有 data-ending-style。从这些状态做过渡,tooltip 会保持挂载,直到退场结束。把 transform-origin: var(--transform-origin) 放在内容上,让它从触发器长出来。立即打开的 tooltip,比如分组里的下一个,会得到 data-instant,所以在那里跳过过渡。
[data-slot="tooltip-content"] {
transform-origin: var(--transform-origin);
transition:
opacity 150ms ease-out,
scale 150ms ease-out;
&:is([data-starting-style], [data-ending-style]) {
opacity: 0;
scale: 0.9;
}
&[data-instant] {
transition: none;
}
}对于要求减少动态效果的人,在 prefers-reduced-motion 查询里去掉缩放,保留淡入淡出。onOpenChangeComplete 在 tooltip 完成打开或关闭后运行,位于任何动画之后,并带上新的打开状态。
"use client"
import { Tooltip, TooltipContent, TooltipTrigger } from "@ui-sdk/react/tooltip"
import { ArchiveIcon } from "lucide-react"
import { useLog } from "./log"
function Example() {
const log = useLog()
return (
<Tooltip
onOpenChange={(open) => log(open ? "Opening" : "Closing")}
onOpenChangeComplete={(open) => log(open ? "Open" : "Closed")}
>
<TooltipTrigger aria-label="Archive">
<ArchiveIcon aria-hidden="true" />
</TooltipTrigger>
<TooltipContent>Archive</TooltipContent>
</Tooltip>
)
}
export { Example }延迟与分组
delay 是指针在触发器上停驻多久之后 tooltip 打开,默认 600 毫秒。closeDelay 是指针离开触发器和 tooltip 之后它还会停留多久,默认 0。键盘焦点会立即打开它。
tooltip 不需要 provider 就能分组。一旦有一个打开,或者刚刚打开过,悬停下一个就会立即打开它,而且同一时间只有一个打开,所以沿工具栏移动读起来就像一个 tooltip 跟着指针走。立即打开的 tooltip 会得到 data-instant,因此可以跳过动画。
disabled 会阻止 tooltip 打开,同时触发器继续正常工作。
<Tooltip delay={300} closeDelay={150} disabled={!showHints}>偏移
sideOffset 是与触发器之间的间距,默认 4 像素。alignOffset 沿它平移,align 让它与触发器的 start、center 或 end 对齐,collisionPadding 是离窗口边缘保留的空间。
<TooltipContent
align="start"
sideOffset={8}
alignOffset={4}
collisionPadding={16}
/>容器
tooltip 就地渲染并显示在顶层,所以不会被任何祖先元素裁剪或遮挡。container 把 tooltip 渲染到别处,适用于 iframe、影子根(shadow root)或特定的层叠上下文。见共享的浮层指南。
<TooltipContent container={shadowRoot} />自定义渲染
每个部件都接受 render。传入一个元素,它的 props 会与部件的 props 合并;或者传入一个函数,接收 props 和部件的状态。props 合并和基于状态的渲染见部件与组合。
"use client"
import { Tooltip, TooltipContent, TooltipTrigger } from "@ui-sdk/react/tooltip"
function Example() {
return (
<Tooltip>
<TooltipTrigger
data-variant="link"
render={<a href="https://example.com/changelog" />}
>
Changelog
</TooltipTrigger>
<TooltipContent>See what's new in 2.0</TooltipContent>
</Tooltip>
)
}
export { Example }一个按钮可以同时是 tooltip 的触发器和另一个组件的触发器。把 tooltip 的触发器渲染为 PopoverTrigger,按钮就会打开 popover,并由 tooltip 命名:
<Popover>
<Tooltip>
<TooltipTrigger render={<PopoverTrigger />}>
<BellIcon aria-hidden="true" />
</TooltipTrigger>
<TooltipContent>Notifications</TooltipContent>
</Tooltip>
<PopoverContent>...</PopoverContent>
</Popover>样式
用 data-side 和 data-align 为内容和箭头按最终落点设置样式,用 data-instant 跳过立即打开的 tooltip 的动画。触发器没有自己的状态属性,因为它常常也是另一个组件的触发器,比如菜单的触发器。把 transform-origin: var(--transform-origin) 放在内容上,让它从触发器开始缩放。
每个部件都有一个 data-slot,比如 tooltip-content,它的状态属性列在数据属性下。
TooltipContent
| 变量 | 内容 |
|---|---|
--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. |
数据属性
TooltipTrigger 和 TooltipShortcut 没有状态属性。
TooltipContent
[data-slot="tooltip-content"]
| 属性 | 含义 |
|---|---|
data-closed | Present while the tooltip is closed, including while it animates out. |
data-open | Present while the tooltip is open. |
data-starting-style | Present for the first frame. Style the state you animate from. |
data-ending-style | Present while the tooltip animates out. Style the state you animate to. |
data-side | toprightbottomleftWhere the tooltip ended up, after flipping away from edges. Set on the arrow too. |
data-align | startcenterendHow the tooltip lines up with its trigger. |
TooltipArrow
[data-slot="tooltip-arrow"]
| 属性 | 含义 |
|---|---|
data-closed | Present while the tooltip is closed, including while it animates out. |
data-open | Present while the tooltip is open. |
data-side | toprightbottomleftWhere the tooltip ended up, after flipping away from edges. Set on the arrow too. |
data-align | startcenterendHow the tooltip lines up with its trigger. |
data-arrow-clamped | Present on the arrow when it stops short of the middle of the trigger, held back by arrowPadding. |
API 参考
属性和回调与下面相同,都作为 React props。
Tooltip
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.
open?boolean- Whether the tooltip is open. Pass it to control the tooltip.
defaultOpen?boolean- Whether the tooltip starts open, when uncontrolled.
onOpenChange?((open: boolean, details: ChangeDetails<TooltipOpenChangeReason>) => void)- Runs when the tooltip wants to open or close.
details.reasonsays why, anddetails.cancel()stops it. onOpenChangeComplete?((open: boolean) => void)- Runs once the tooltip has finished opening or closing, after any animation.
onPayloadChange?((payload: unknown, details: ChangeDetails<TooltipPayloadChangeReason>) => void)- Runs when the payload the content shows changes: a trigger with another payload opens the tooltip, or takes the open tooltip over, which fires no
onOpenChange, and so does a controller'sopen({ payload })on the open tooltip.details.cancel()keeps the previous payload. delay?number- Milliseconds the pointer rests on the trigger before the tooltip opens. While another tooltip is open, or was a moment ago, the next one opens at once, without a provider.
closeDelay?number- Milliseconds before the tooltip closes once the pointer leaves the trigger and the tooltip.
disabled?boolean- Stops the tooltip from opening. The trigger keeps working.
toggleable?boolean- Whether pressing the trigger opens and closes the tooltip, so touch screens can show it too. For info buttons whose only job is the tip. The text is announced when a press opens it.
closeOnPress?boolean- Whether pressing the trigger closes the tooltip. Set it to
falseto keep it open, like for a copy button whose tooltip turns into "Copied". type?"description" | "label"- Whether the tooltip names its trigger (
"label") or adds a description to it ("description"). By default it names a trigger that has no name of its own, like an icon button, and describes any other. shortcut?string- The keyboard shortcut of what the trigger does, like
"mod+s", as a hint. ATooltipShortcutshows it, and the trigger getsaria-keyshortcuts. It doesn't bind the keys: the trigger's ownshortcut, orregisterShortcut, does. controller?PopupController<any, TooltipOpenChangeReason, {}, string, TooltipPayloadChangeReason>- Opens, closes and inspects the tooltip from anywhere, and connects triggers outside it. Create one with
createTooltipController(). debug?boolean- Logs every state change with its reason to the console, in development builds.
TooltipTrigger
tooltip 之外的触发器还接受 controller。
payload?unknown- Data for the content to render when this trigger opens the tooltip, like the row it belongs to.
controller?PopupController<any, TooltipOpenChangeReason, {}, string, TooltipPayloadChangeReason>- Connects a trigger outside the tooltip, like one per table row, to the tooltip with this controller.
TooltipContent
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 tooltip opens on.
align?Align- How the popup lines up with the anchor along that side.
startandendfollow the reading direction. How the tooltip lines up with the trigger along that side. sideOffset?number- Gap between the anchor and the popup, in pixels. Gap between the trigger and the tooltip, in pixels.
alignOffset?number- Shift along the anchor, in pixels. Shift along the trigger, 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.
TooltipArrow
从 tooltip 最终所在的一侧指向触发器。渲染一个 div。
TooltipShortcut
shortcut?string- The keys to show. By default, the tooltip's
shortcut.
状态
每个部件的渲染函数、基于状态的类名和槽位会收到什么。
TooltipTrigger:
openboolean- Whether the tooltip is open from this trigger.
TooltipContent:
openboolean- Whether the tooltip is open. False while it animates out.
instantboolean- Whether it opened at once, because another tooltip was open a moment ago. Animations can skip.
payloadPayload | undefined- The payload of the last open, from the trigger that opened it or a controller, typed as the controller's
Payload.
TooltipArrow:
openboolean- Whether the tooltip is open. False as soon as it starts closing, while it still animates out.
TooltipShortcut:
textstring- The shortcut formatted for this platform:
⌘Son Apple platforms andCtrl+Selsewhere. Empty without one.
原因
details.reason 说明 tooltip 为什么打开或关闭。
trigger-hoverPointerEvent- The pointer rested on a trigger, or left it, with hover opening.
trigger-focusFocusEvent- Keyboard focus reached a trigger that opens on focus, like a tooltip's.
trigger-pressMouseEvent | KeyboardEvent | TouchEvent- Click, tap, Enter or Space on the part that opens, closes or toggles. Arrow keys that open a menu or submenu count too. A tap on a combobox's input that opens a sheet reports its
touchend. focus-outKeyboardEvent | FocusEvent- Focus left the layer, or Tab moved it out.
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.
window-blurFocusEvent- The window lost focus.
backEvent- Going back: the Android back button or gesture, or Backspace in an empty command input, which returns to the previous page.
anchor-hiddennone- The element the popup sits beside stopped rendering, like a trigger a breakpoint hides.
imperativenone- A controller or
apicall.
payload 变更时,它说明是什么打开了 tooltip 或接管了它。
trigger-hoverPointerEvent- The pointer rested on a trigger, or left it, with hover opening.
trigger-focusFocusEvent- Keyboard focus reached a trigger that opens on focus, like a tooltip's.
trigger-pressMouseEvent | KeyboardEvent | TouchEvent- Click, tap, Enter or Space on the part that opens, closes or toggles. Arrow keys that open a menu or submenu count too. A tap on a combobox's input that opens a sheet reports its
touchend. imperativenone- A controller or
apicall.
控制器
用 createTooltipController<Payload>() 创建一个,并作为 controller 传给 tooltip 以及它之外的所有触发器。Payload 是触发器和 open() 传入数据的类型。
每个写入方法都接受一个可选的 { reason, event },传给 onOpenChange。
isOpen()() => boolean- Whether it's open. False as soon as it starts closing, while it still animates out.
setOpen(open, options?)(open: boolean, options?: PopupChangeOptions<TooltipOpenChangeReason> | undefined) => boolean- Opens or closes it. Returns false when the change was canceled or it was already open or closed.
open(options?)(options?: (PopupChangeOptions<TooltipPayloadChangeReason> & { payload?: Payload | undefined; anchor?: Anchor | undefined; signal?: AbortSignal | undefined; }) | undefined) => Promise<...>- Opens it, and resolves once it closes, with why, how and any return value. Resolves exactly once and never rejects: on the next close from any source, when
signalaborts, or with reason"unmount"when the component leaves the page. close(options?)(options?: (PopupChangeOptions<TooltipOpenChangeReason> & { returnValue?: string | undefined; }) | undefined) => boolean- Closes it.
returnValueis passed to the promiseopen()returned. Returns false when the close was canceled or it was already closed. toggle(options?)(options?: PopupChangeOptions<TooltipOpenChangeReason> | undefined) => boolean- Opens it when it's closed, and closes it when it's open. Returns false when the change was canceled.
getPayload()() => Payload | undefined- The payload of the last open, from a controller or the trigger that opened it.
focus()() => void- Moves focus to the trigger that opened it last, or the first trigger.
事件
回调先收到新状态,然后收到详情。
| 属性 | 所属 | 收到 |
|---|---|---|
onOpenChange | Tooltip | (open, details):新状态,以及原因 |
onOpenChangeComplete | Tooltip | (open),在动画之后 |
onPayloadChange | Tooltip | (payload, details):内容的新 payload,以及原因 |
无障碍
触发器由 tooltip 命名或描述,遵循 WAI-ARIA tooltip 模式。它在悬停和键盘焦点时打开,并在指针移入它时保持打开。
键盘
| 按键 | 作用 |
|---|---|
| Tab | 焦点落在触发器上会立即打开 tooltip;焦点离开它会关闭 tooltip |
| Escape | 关闭 tooltip,并把焦点留在触发器上,不会关闭它周围的对话框或菜单 |
| Enter, Space | 按压触发器并关闭 tooltip;在 toggleable 触发器上,打开和关闭它 |
经过测试的行为
下面每一行都是一个自动化测试。
- Resting the pointer on the trigger opens the tooltip.
- The tooltip waits for its delay before opening.
- Leaving the trigger before the delay keeps the tooltip closed.
- Moving the pointer away closes the tooltip.
- The pointer can move onto the tooltip without closing it.
- Opening on hover leaves focus where it was.
- Pressing the trigger closes the tooltip and runs the button.
- After a press, the tooltip stays closed until the pointer comes back.
- Keyboard focus on the trigger opens the tooltip.
- Focus leaving the trigger closes the tooltip.
- Escape closes the tooltip and leaves focus on the trigger.
- Escape closes a tooltip opened by hover.
- Tab through the toolbar shows each tooltip in turn.
- A click that focuses the trigger doesn't open the tooltip from focus.
- Only one tooltip is open at a time.
- Once the pointer has been away a while, the delay applies again.
- The tooltip opens above the trigger.
- The tooltip flips below the trigger when there is no room above.
- The tooltip opens on the requested side.
- The arrow points at the middle of the trigger.
- Hovering shows the tooltip, and pressing opens the popover instead.
- Escape closes the tooltip and leaves the popover open.
- Browsers send hover events to a disabled button.
- An aria-disabled trigger shows its tooltip on hover and focus and ignores presses.
- The tooltip animates in from its starting style.
- The tooltip stays in the page while it animates out.
- A class that sets display on the content doesn't show it while closed.
- Escape closes only a tooltip that keyboard focus opened inside a popover.
- The pointer can leave the trigger sideways on its way to the tooltip.
- With closeOnPress false, pressing the trigger keeps the tooltip open.
- Disabled tooltips never open.
- A tap on a plain tooltip's trigger only presses it.
运行于 React、Vue 和 web components。
其他行为:
- Focus returning to the trigger after its popover closes doesn't reopen the tooltip.
- Tooltips open at once after another one, without a provider.
- Focus coming back with the window doesn't reopen the tooltip.
- A controller opens the tooltip without moving focus.
- A trigger that's a disabled button warns in development.
- A trigger connected through a controller shows its tooltip's shortcut in a Shortcut part.
- Pressing a toggleable trigger opens and closes the tooltip.
- Pressing outside closes a toggleable tooltip.
- Enter toggles the tooltip from the keyboard and keeps focus on the trigger.
- A press announces the tooltip's text to screen readers.
- A tap opens a toggleable tooltip on a touch screen.
运行于 React、Vue 和 web components。
在每个经过测试的框架里,屏幕阅读器听到的内容相同,由虚拟屏幕阅读器记录:
- Announcements while tabbing through triggers with tooltips.
运行于 React、Vue 和 web components。