为控件命名,或在悬停和键盘焦点时补上一句简短提示。

当指针停在控件上或键盘焦点到达时,tooltip 为控件命名,或补上一句简短提示。保持纯文本,几个词就够。

import { Tooltip, TooltipContent, TooltipTrigger } from "@ui-sdk/solid/tooltip"

function Example() {
  return (
    <Tooltip defaultOpen>
      <TooltipTrigger aria-label="Add to library">
        <svg
          viewBox="0 0 24 24"
          fill="none"
          stroke="currentColor"
          stroke-width="2"
          stroke-linecap="round"
          stroke-linejoin="round"
          aria-hidden="true"
        >
          <path d="M17 3a2 2 0 0 1 2 2v15a1 1 0 0 1-1.496.868l-4.512-2.578a2 2 0 0 0-1.984 0l-4.512 2.578A1 1 0 0 1 5 20V5a2 2 0 0 1 2-2z" />
        </svg>
      </TooltipTrigger>
      <TooltipContent>Add to library</TooltipContent>
    </Tooltip>
  )
}

export { Example }
tooltip 一开始就是打开的。悬停按钮或用 Tab 到达它,让它再次显示;按 Escape 关闭它,焦点仍留在按钮上。

安装

npm install @ui-sdk/solid @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/solid/tooltip"

function Example() {
  return (
    <Tooltip>
      <TooltipTrigger>Share</TooltipTrigger>
      <TooltipContent>Anyone with the link can view</TooltipContent>
    </Tooltip>
  )
}

export { Example }

方向

side 选择 tooltip 打开的方向:默认是 top。空间不够时,它会翻到另一侧,并沿触发器平移以留在屏幕内。data-side 报告它最终落在哪里。

import { Tooltip, TooltipContent, TooltipTrigger } from "@ui-sdk/solid/tooltip"
import { For } from "solid-js"

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">
      <For each={sides}>
        {({ side, label }) => (
          <Tooltip>
            <TooltipTrigger>{label}</TooltipTrigger>
            <TooltipContent side={side}>Add to library</TooltipContent>
          </Tooltip>
        )}
      </For>
    </div>
  )
}

export { Example }
悬停 Top、Left、Right 和 Bottom。每个 tooltip 都在对应按钮的那一侧打开,空间不够时会翻到中间。

添加 TooltipArrow 来指向触发器。它跟随 tooltip 最终的落点,翻转之后也是如此。

<TooltipContent>
  <TooltipArrow />
  Add to library
</TooltipContent>

锚点

用 anchor 让 tooltip 贴着触发器以外的东西定位:元素、CSS 选择器、像 { x, y } 这样的点,或任何带 getBoundingClientRect() 的对象。这里字段里的小帮助按钮会让它的 tooltip 与整个字段对齐。

import { Field, FieldLabel } from "@ui-sdk/solid/field"
import { Input } from "@ui-sdk/solid/input"
import { Tooltip, TooltipContent, TooltipTrigger } from "@ui-sdk/solid/tooltip"
import { createSignal } from "solid-js"

function Example() {
  const [field, setField] = createSignal<HTMLDivElement | null>(null)

  return (
    <Field>
      <FieldLabel>Webhook URL</FieldLabel>
      <div data-slot="row" ref={setField}>
        <Input placeholder="https://" />
        <Tooltip>
          <TooltipTrigger aria-label="About webhooks">
            <svg
              viewBox="0 0 24 24"
              fill="none"
              stroke="currentColor"
              stroke-width="2"
              stroke-linecap="round"
              stroke-linejoin="round"
              aria-hidden="true"
            >
              <circle cx="12" cy="12" r="10" />
              <path d="M12 16v-4" />
              <path d="M12 8h.01" />
            </svg>
          </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 在 Webhook URL 字段下方打开,并与它的 start 对齐,而不是与按钮对齐。

键盘快捷键

tooltip 上的 shortcut,比如 "mod+s",提示触发器的动作绑定在什么按键上;其中 mod 在 Apple 平台上是 Command,在其他平台上是 Control。TooltipShortcut 显示当前平台的按键,⌘S 或 Ctrl+S,对屏幕阅读器隐藏,触发器则会得到 aria-keyshortcuts,让屏幕阅读器改为听到它。TooltipShortcut 可以用自己的 shortcut 显示其他按键。

tooltip 不会绑定这些按键。像示例那样,用 registerShortcut 自己注册快捷键,或使用会绑定按键的组件的 shortcut,比如 Dialog 的触发器。

控制台
import { registerShortcut } from "@ui-sdk/core/shortcuts"
import {
  Tooltip,
  TooltipContent,
  TooltipShortcut,
  TooltipTrigger,
} from "@ui-sdk/solid/tooltip"
import { onSettled } from "solid-js"
import { useLog } from "./log"

function Example() {
  const log = useLog()

  onSettled(() => {
    const offSave = registerShortcut("mod+s", () => log("Saved"))
    const offShare = registerShortcut("mod+shift+e", () => log("Shared"))
    return () => {
      offSave()
      offShare()
    }
  })

  return (
    <div data-slot="row">
      <Tooltip shortcut="mod+s">
        <TooltipTrigger aria-label="Save" onClick={() => log("Saved")}>
          <svg
            viewBox="0 0 24 24"
            fill="none"
            stroke="currentColor"
            stroke-width="2"
            stroke-linecap="round"
            stroke-linejoin="round"
            aria-hidden="true"
          >
            <path d="M15.2 3a2 2 0 0 1 1.4.6l3.8 3.8a2 2 0 0 1 .6 1.4V19a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2z" />
            <path d="M17 21v-7a1 1 0 0 0-1-1H8a1 1 0 0 0-1 1v7" />
            <path d="M7 3v4a1 1 0 0 0 1 1h7" />
          </svg>
        </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 }
悬停 Save 或 Share 查看它的快捷键,然后按压按钮或按键。控制台会记录 Saved 或 Shared。

禁用的按钮

原生禁用的按钮无法接收焦点,而且有些浏览器不会给它发送指针事件,所以它的 tooltip 永远不会显示。当 tooltip 用来解释某个操作为什么不可用时,改用 aria-disabled="true",并由你自己忽略按钮的按压。按钮会留在 Tab 顺序中,屏幕阅读器会把它播报为变暗,tooltip 则说明缺了什么。按钮恢复可用后,tooltip 上的 disabled 会关掉这条说明。

控制台
import { Field, FieldLabel } from "@ui-sdk/solid/field"
import { Input } from "@ui-sdk/solid/input"
import { Tooltip, TooltipContent, TooltipTrigger } from "@ui-sdk/solid/tooltip"
import { createSignal } from "solid-js"
import { useLog } from "./log"

function Example() {
  const log = useLog()
  const [title, setTitle] = createSignal("")
  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() ? "true" : undefined}
          onClick={() => {
            if (!blocked()) {
              log(`Published “${title().trim()}”`)
            }
          }}
        >
          Publish
        </TooltipTrigger>
        <TooltipContent side="right">Add a title to publish</TooltipContent>
      </Tooltip>
    </div>
  )
}

export { Example }
悬停或聚焦 Publish,了解缺了什么。输入标题后,Publish 恢复可用,它的 tooltip 也会消失。

触摸

触摸屏没有悬停。轻点普通 tooltip 的触发器只会按压它,tooltip 仍然关闭,所以不要把重要内容藏在 tooltip 里。

如果某个信息按钮的唯一职责就是显示这条提示,就加上 toggleable:用手指、鼠标或键盘按压触发器可以打开和关闭 tooltip,按压打开时它的文本会被播报。外部按压或 Escape 也能关闭它。

import { Tooltip, TooltipContent, TooltipTrigger } from "@ui-sdk/solid/tooltip"

function Example() {
  return (
    <div data-slot="row">
      <span data-slot="label">Storage</span>
      <Tooltip toggleable>
        <TooltipTrigger aria-label="About storage" data-size="sm">
          <svg
            viewBox="0 0 24 24"
            fill="none"
            stroke="currentColor"
            stroke-width="2"
            stroke-linecap="round"
            stroke-linejoin="round"
            aria-hidden="true"
          >
            <circle cx="12" cy="12" r="10" />
            <path d="M12 16v-4" />
            <path d="M12 8h.01" />
          </svg>
        </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。

import { Tooltip, TooltipContent, TooltipTrigger } from "@ui-sdk/solid/tooltip"
import { createSignal } from "solid-js"

const command = "npm install @ui-sdk/solid"

function Example() {
  const [copied, setCopied] = createSignal(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() ? (
            <svg
              viewBox="0 0 24 24"
              fill="none"
              stroke="currentColor"
              stroke-width="2"
              stroke-linecap="round"
              stroke-linejoin="round"
              aria-hidden="true"
            >
              <path d="M20 6 9 17l-5-5" />
            </svg>
          ) : (
            <svg
              viewBox="0 0 24 24"
              fill="none"
              stroke="currentColor"
              stroke-width="2"
              stroke-linecap="round"
              stroke-linejoin="round"
              aria-hidden="true"
            >
              <rect width="14" height="14" x="8" y="8" rx="2" ry="2" />
              <path d="M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2" />
            </svg>
          )}
        </TooltipTrigger>
        <TooltipContent>{copied() ? "Copied" : "Copy"}</TooltipContent>
      </Tooltip>
    </div>
  )
}

export { Example }
悬停复制按钮并按压它。tooltip 保持打开,并变成 Copied。

被截断的文本

如果只想在文本被截断时才显示 tooltip,就在文本放得下时,于 onOpenChange 中取消这次打开。在回调里比较 scrollWidth 和 clientWidth。tooltip 会重复这个名称,所以 type="label" 可以避免屏幕阅读器听到两遍。

import { Tooltip, TooltipContent, TooltipTrigger } from "@ui-sdk/solid/tooltip"
import { For } from "solid-js"

const files = [
  "Quarterly report, final revised version for the board.pdf",
  "Notes.txt",
  "Design review recording, October 2nd.mp4",
  "Budget.xlsx",
]

function FileRow(props: { name: string }) {
  let text: HTMLSpanElement | undefined

  return (
    <li>
      <Tooltip
        type="label"
        onOpenChange={(open, details) => {
          const span = text
          if (open && span && span.scrollWidth <= span.clientWidth) {
            details.cancel()
          }
        }}
      >
        <TooltipTrigger>
          <svg
            viewBox="0 0 24 24"
            fill="none"
            stroke="currentColor"
            stroke-width="2"
            stroke-linecap="round"
            stroke-linejoin="round"
            aria-hidden="true"
          >
            <path d="M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z" />
            <path d="M14 2v5a1 1 0 0 0 1 1h5" />
          </svg>
          <span ref={text}>{props.name}</span>
        </TooltipTrigger>
        <TooltipContent>{props.name}</TooltipContent>
      </Tooltip>
    </li>
  )
}

function Example() {
  return (
    <ul>
      <For each={files}>{(file) => <FileRow name={file} />}</For>
    </ul>
  )
}

export { Example }
悬停或聚焦每个文件。只有被截断的名称才会打开 tooltip。

受控

传入 open,并在 onOpenChange 中更新它。每次变更都带有原因,比如 trigger-hover、trigger-focus、trigger-press、escape-key 或 outside-press。调用 details.cancel() 可以阻止它。要从任何地方打开 tooltip,比如分步引导中的某一步,请使用控制器。

控制台
import { Checkbox, CheckboxIndicator } from "@ui-sdk/solid/checkbox"
import { Tooltip, TooltipContent, TooltipTrigger } from "@ui-sdk/solid/tooltip"
import { createSignal } from "solid-js"
import { useLog } from "./log"

function Example() {
  const log = useLog()
  const [open, setOpen] = createSignal(false)
  let controls: HTMLDivElement | undefined

  return (
    <div data-slot="stack">
      <div data-slot="controls" ref={controls}>
        <label data-slot="label">
          <Checkbox
            checked={open()}
            onCheckedChange={(next) => setOpen(next === true)}
          >
            <CheckboxIndicator>
              <svg
                viewBox="0 0 24 24"
                fill="none"
                stroke="currentColor"
                stroke-width="2"
                stroke-linecap="round"
                stroke-linejoin="round"
                aria-hidden="true"
              >
                <path d="M20 6 9 17l-5-5" />
              </svg>
            </CheckboxIndicator>
          </Checkbox>
          Open
        </label>
      </div>
      <Tooltip
        open={open()}
        onOpenChange={(next, details) => {
          const target = details.event?.target
          const inControls =
            target instanceof Node && controls?.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 }
勾选 Open,或悬停 Export。控制台会记录每次变更及其原因。

共享

工具栏、图表或长列表可以共用一个 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,它就会滑过去而不是跳过去。打开时的第一次放置永远不做动画,所以它不会从某个角落飞进来。

import {
  createTooltipController,
  Tooltip,
  TooltipContent,
  TooltipTrigger,
} from "@ui-sdk/solid/tooltip"
import { For } from "solid-js"

const icon = (markup: string) => () => (
  <svg
    viewBox="0 0 24 24"
    fill="none"
    stroke="currentColor"
    stroke-width="2"
    stroke-linecap="round"
    stroke-linejoin="round"
    aria-hidden="true"
    innerHTML={markup}
  />
)
const Bold = icon(
  '<path d="M6 12h9a4 4 0 0 1 0 8H7a1 1 0 0 1-1-1V5a1 1 0 0 1 1-1h7a4 4 0 0 1 0 8" />'
)
const Italic = icon(
  '<line x1="19" x2="10" y1="4" y2="4" /><line x1="14" x2="5" y1="20" y2="20" /><line x1="15" x2="9" y1="4" y2="20" />'
)
const Underline = icon(
  '<path d="M6 4v6a6 6 0 0 0 12 0V4" /><line x1="4" x2="20" y1="20" y2="20" />'
)

const formats = [
  { icon: Bold, label: "Bold" },
  { icon: Italic, label: "Italic" },
  { icon: Underline, label: "Underline" },
]

function Example() {
  const tooltip = createTooltipController<string>()

  return (
    <div data-slot="row" role="group" aria-label="Formatting">
      <For each={formats}>
        {(format) => (
          <TooltipTrigger
            controller={tooltip}
            payload={format.label}
            aria-label={format.label}
          >
            <format.icon />
          </TooltipTrigger>
        )}
      </For>
      <Tooltip controller={tooltip}>
        <TooltipContent<string>>{(state) => state.payload}</TooltipContent>
      </Tooltip>
    </div>
  )
}

export { Example }
沿 Bold、Italic 和 Underline 移动。一个 tooltip 跟着指针,显示每个按钮的标签。

动画

内容在打开时带有 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 完成打开或关闭后运行,位于任何动画之后,并带上新的打开状态。

控制台
import { Tooltip, TooltipContent, TooltipTrigger } from "@ui-sdk/solid/tooltip"
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">
        <svg
          viewBox="0 0 24 24"
          fill="none"
          stroke="currentColor"
          stroke-width="2"
          stroke-linecap="round"
          stroke-linejoin="round"
          aria-hidden="true"
        >
          <rect width="20" height="5" x="2" y="3" rx="1" />
          <path d="M4 8v11a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8" />
          <path d="M10 12h4" />
        </svg>
      </TooltipTrigger>
      <TooltipContent>Archive</TooltipContent>
    </Tooltip>
  )
}

export { Example }
悬停 Archive,然后移开。tooltip 从按钮长出来并淡出,控制台会记录 Opening、Open、Closing 和 Closed。

延迟与分组

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 合并和基于状态的渲染见部件与组合。

import { Tooltip, TooltipContent, TooltipTrigger } from "@ui-sdk/solid/tooltip"

function Example() {
  return (
    <Tooltip>
      <TooltipTrigger
        data-variant="link"
        render={(props) => (
          <a {...props} href="https://example.com/changelog" />
        )}
      >
        Changelog
      </TooltipTrigger>
      <TooltipContent>See what's new in 2.0</TooltipContent>
    </Tooltip>
  )
}

export { Example }
悬停 Changelog。触发器渲染为链接,它的 tooltip 说明链接指向哪里。

一个按钮可以同时是 tooltip 的触发器和另一个组件的触发器。把 tooltip 的触发器渲染为 PopoverTrigger,按钮就会打开 popover,并由 tooltip 命名:

<Popover>
  <Tooltip>
    <TooltipTrigger render={(props) => <PopoverTrigger {...props} />}>
      <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-widthWidth of the anchor, usually the trigger. Use it to match widths.
--anchor-heightHeight of the anchor.
--available-widthSpace beside the popup, up to the viewport edge. Not inherited either.
--available-heightSpace 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-originThe point on the anchor the popup opens from. Use it to scale from the right place.
--arrow-offsetWhere 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-closedPresent while the tooltip is closed, including while it animates out.
data-openPresent while the tooltip is open.
data-starting-stylePresent for the first frame. Style the state you animate from.
data-ending-stylePresent while the tooltip animates out. Style the state you animate to.
data-sidetoprightbottomleftWhere the tooltip ended up, after flipping away from edges. Set on the arrow too.
data-alignstartcenterendHow the tooltip lines up with its trigger.

TooltipArrow

[data-slot="tooltip-arrow"]

属性含义
data-closedPresent while the tooltip is closed, including while it animates out.
data-openPresent while the tooltip is open.
data-sidetoprightbottomleftWhere the tooltip ended up, after flipping away from edges. Set on the arrow too.
data-alignstartcenterendHow the tooltip lines up with its trigger.
data-arrow-clampedPresent on the arrow when it stops short of the middle of the trigger, held back by arrowPadding.

API 参考

属性和回调与下面相同,都作为 Solid 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.reason says why, and details.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's open({ 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 false to 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. A TooltipShortcut shows it, and the trigger gets aria-keyshortcuts. It doesn't bind the keys: the trigger's own shortcut, or registerShortcut, 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. start and end follow 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 with getBoundingClientRect(). It's read on every check, so it can move. A controller's open({ 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: ⌘S on Apple platforms and Ctrl+S elsewhere. 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 api call.

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 api call.

控制器

用 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 signal aborts, or with reason "unmount" when the component leaves the page.
close(options?)(options?: (PopupChangeOptions<TooltipOpenChangeReason> & { returnValue?: string | undefined; }) | undefined) => boolean
Closes it. returnValue is passed to the promise open() 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.

事件

回调先收到新状态,然后收到详情。

属性所属收到
onOpenChangeTooltip(open, details):新状态,以及原因
onOpenChangeCompleteTooltip(open),在动画之后
onPayloadChangeTooltip(payload, details):内容的新 payload,以及原因

无障碍

触发器由 tooltip 命名或描述,遵循 WAI-ARIA tooltip 模式。它在悬停和键盘焦点时打开,并在指针移入它时保持打开。

键盘

按键作用
Tab焦点落在触发器上会立即打开 tooltip;焦点离开它会关闭 tooltip
Escape关闭 tooltip,并把焦点留在触发器上,不会关闭它周围的对话框或菜单
Enter, Space按压触发器并关闭 tooltip;在 toggleable 触发器上,打开和关闭它

经过测试的行为

下面每一行都是一个自动化测试。

Pointer
  • 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
  • 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.
Several tooltips
  • Only one tooltip is open at a time.
  • Once the pointer has been away a while, the delay applies again.
Positioning
  • 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.
A tooltip on a popover trigger
  • Hovering shows the tooltip, and pressing opens the popover instead.
  • Escape closes the tooltip and leaves the popover open.
Disabled buttons
  • Browsers send hover events to a disabled button.
  • An aria-disabled trigger shows its tooltip on hover and focus and ignores presses.
Animation
  • The tooltip animates in from its starting style.
  • The tooltip stays in the page while it animates out.
Hidden while closed
  • A class that sets display on the content doesn't show it while closed.
Options and dismissal
  • 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。

其他行为:

Enhancements
  • 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.
Shortcuts
  • A trigger connected through a controller shows its tooltip's shortcut in a Shortcut part.
Toggleable
  • 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。