Hover Card
悬停或通过键盘聚焦链接时预览它指向的内容,同时保留链接正常的跳转。
hover card 为在链接上停留的人显示链接指向内容的预览,比如某个人的个人资料。链接仍然是普通的链接。
import "@ui-sdk/web/hover-card"
function mount(root: HTMLElement) {
root.innerHTML = `
<ui-hover-card>
<ui-hover-card-trigger><a href="https://example.com/people/hollis">@hollis</a></ui-hover-card-trigger>
<ui-hover-card-content hidden>
<div data-slot="row">
<span data-slot="initials" aria-hidden="true">HG</span>
<div data-slot="stack">
<p>Hollis Grant</p>
<p>Design engineer on the payments team. Writes about forms and motion.</p>
<p data-slot="hint">Joined March 2021</p>
</div>
</div>
</ui-hover-card-content>
</ui-hover-card>
`
}
export { mount }安装
npm install @ui-sdk/web @ui-sdk/core导入组件以注册它的元素。这个导入在服务端是安全的。
import "@ui-sdk/web/hover-card"组合
用下面的组合构建 ui-hover-card:
ui-hover-card
├── ui-hover-card-trigger
│ └── a
└── ui-hover-card-content
└── ui-hover-card-arrow触发器包住你自己的链接(一个 <a>,所以要给它 href),按压它会跟随链接。内容是预览,箭头是可选的。
卡片只为在链接上停留的人补一份预览:里面的所有内容都应该能从链接指向的页面到达,因为触摸和屏幕阅读器用户可能永远不会打开它。要给按钮加一句提示,请使用 Tooltip。要放按压后打开的内容,请使用 Popover。
用法
导入部件并把它们组合起来:
<script type="module">
import "@ui-sdk/web/hover-card"
</script>
<ui-hover-card>
<ui-hover-card-trigger
><a href="/people/hollis">@hollis</a></ui-hover-card-trigger
>
<ui-hover-card-content hidden>
<p>Hollis Grant</p>
<p>Design engineer on the payments team.</p>
</ui-hover-card-content>
</ui-hover-card>定位
side 选择卡片打开的方向,默认是 bottom;align 让它与链接的 start、center 或 end 对齐。空间不够时,卡片会翻到另一侧,并沿链接平移以留在屏幕内。
ui-hover-card-arrow 跟随卡片实际落点的一侧,翻转之后也是如此,并得到相同的 data-side。它指向链接的中间,并用 arrow-padding 与边角保持距离;data-arrow-clamped 告诉你它什么时候无法指向中间。
import "@ui-sdk/web/hover-card"
import "@ui-sdk/web/select"
import { Check, ChevronDown, createElement } from "lucide"
const sides = [
{ value: "top", label: "Top" },
{ value: "right", label: "Right" },
{ value: "bottom", label: "Bottom" },
{ value: "left", label: "Left" },
]
const aligns = [
{ value: "start", label: "Start" },
{ value: "center", label: "Center" },
{ value: "end", label: "End" },
]
const select = (
name: string,
label: string,
options: { value: string; label: string }[],
value: string
) => `
<ui-select data-control="${name}" default-value="${value}">
<ui-select-label>${label}</ui-select-label>
<ui-select-trigger>
<button>
<ui-select-value></ui-select-value>
${createElement(ChevronDown, { "aria-hidden": "true" }).outerHTML}
</button>
</ui-select-trigger>
<ui-select-content hidden>
${options
.map(
(option) => `
<ui-select-item value="${option.value}">
${option.label}
<ui-select-item-indicator>${createElement(Check, { "aria-hidden": "true" }).outerHTML}</ui-select-item-indicator>
</ui-select-item>
`
)
.join("")}
</ui-select-content>
</ui-select>
`
function mount(root: HTMLElement) {
root.innerHTML = `
<div data-slot="stack">
<div data-slot="controls">
${select("side", "Side", sides, "bottom")}
${select("align", "Align", aligns, "center")}
</div>
<ui-hover-card>
<ui-hover-card-trigger><a href="https://example.com/people/ines">@ines</a></ui-hover-card-trigger>
<ui-hover-card-content hidden side="bottom" align="center" side-offset="10">
<ui-hover-card-arrow></ui-hover-card-arrow>
<p>Inès Moreau</p>
<p>Product designer. Leads the checkout redesign.</p>
</ui-hover-card-content>
</ui-hover-card>
</div>
`
const content = root.querySelector("ui-hover-card-content")!
for (const control of root.querySelectorAll("ui-select")) {
control.addEventListener("valuechange", (event) => {
if (event.detail.value) {
content.setAttribute(
control.dataset.control!,
String(event.detail.value)
)
}
})
}
}
export { mount }side-offset 是与链接之间的间距,默认 4 像素。align-offset 沿它平移卡片,collision-padding 是离窗口边缘保留的空间。anchor 让卡片贴着链接以外的东西定位,用 CSS 选择器指定。
<ui-hover-card-content
side="right"
align="start"
side-offset="8"
collision-padding="16"
anchor="#row"
hidden
></ui-hover-card-content>延迟
delay 是指针在链接上停驻、或键盘焦点停留在链接上多久之后,卡片才打开:默认 600 毫秒。close-delay 是指针离开链接和卡片之后,它还会保持打开多久:默认 300 毫秒。指针可以越过链接和卡片之间的间隙而不会关闭它。
disabled 会阻止卡片打开,只留下一个普通的链接。
<ui-hover-card delay="300" close-delay="150" disabled></ui-hover-card>受控
设置元素的 open property,并监听 openchange;open 属性设置它一开始的状态。每次变更都在 event.detail.reason 中带有原因,比如 trigger-hover、trigger-focus、focus-out、escape-key 或 outside-press。调用 event.preventDefault() 可以阻止它。
<ui-hover-card></ui-hover-card>
<script type="module">
const card = document.querySelector("ui-hover-card")
card.addEventListener("openchange", (event) => (open = event.detail.value))
card.open = true
</script>多个链接共用一张卡片
信息流或列表可以共用一张卡片,而不是为每个链接各渲染一张。给卡片一个 id,让每个触发器用 for 指向它。每个触发器接受一个 payload property,比如它对应的人;它在触发器连接时读取,所以要在触发器进入页面之前设置好。卡片的 payloadchange 事件在 event.detail.value 中带上它;在那里根据它渲染内容。只有打开卡片的那个链接会得到 data-open。卡片的 api.open({ payload }) 从代码打开它。
<ui-hover-card id="profile">
<ui-hover-card-content hidden><p></p></ui-hover-card-content>
</ui-hover-card>
<script type="module">
const card = document.querySelector("#profile")
for (const person of people) {
const trigger = Object.assign(
document.createElement("ui-hover-card-trigger"),
{ payload: person }
)
trigger.setAttribute("for", "profile")
trigger.innerHTML = `<a href="${person.url}">${person.name}</a>`
feed.append(trigger)
}
card.addEventListener("payloadchange", (event) => {
card.querySelector("p").textContent = event.detail.value?.bio
})
</script>卡片里也可以有自己的链接。从打开着卡片的链接按 Tab 会进入卡片,按 Tab 越过它的末尾则会移动到链接之后的页面内容。焦点离开卡片会关闭它。
容器
卡片就地渲染并显示在顶层,所以不会被任何祖先元素裁剪或遮挡。container 把卡片渲染到别处,用 CSS 选择器指定,适用于 iframe、影子根(shadow root)或特定的层叠上下文。见共享的浮层指南。
<ui-hover-card-content container="#card-host" hidden></ui-hover-card-content>动画
内容打开时带有 data-starting-style,关闭时带有 data-ending-style。从这些状态做过渡,卡片会保持挂载,直到退场结束。openchangecomplete 在过渡之后触发,keep-mounted 让关闭的卡片留在页面里,保持隐藏,供从状态驱动退场的动画库使用。
[data-slot="hover-card-content"] {
transition:
opacity 150ms,
scale 150ms;
&:is([data-starting-style], [data-ending-style]) {
opacity: 0;
scale: 0.96;
}
}自定义渲染
元素没有渲染函数。触发器包住你自己的链接,所以链接里可以放任何东西,比如头像和名字。卡片从某个链接打开期间,该链接会得到 data-open。
<ui-hover-card-trigger>
<a href="/people/hollis">
<span aria-hidden="true">HG</span>
Hollis Grant
</a>
</ui-hover-card-trigger>样式
每个元素都有一个 data-slot,比如 hover-card-content,并通过数据属性下列出的属性展示自己的状态。用触发器链接上的 data-open 标记正在显示卡片的链接,用 data-side 为内容和箭头按最终落点设置样式。把 transform-origin: var(--transform-origin) 放在内容上,让它从链接开始缩放。
箭头伸出卡片之外时,让它周围的溢出保持可见。如果 body 需要滚动,把滚动放在内层元素上。
<ui-hover-card-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-hover-card-trigger>
[data-slot="hover-card-trigger"]
| 属性 | 含义 |
|---|---|
data-closed | Present while the card is closed, including while it animates out. |
data-open | Present while the card is open. On a trigger, while it's open from that trigger. |
<ui-hover-card-content>
[data-slot="hover-card-content"]
| 属性 | 含义 |
|---|---|
data-closed | Present while the card is closed, including while it animates out. |
data-open | Present while the card is open. On a trigger, while it's open from that trigger. |
data-starting-style | Present for the first frame. Style the state you animate from. |
data-ending-style | Present while the card animates out. Style the state you animate to. |
data-side | toprightbottomleftWhere the card ended up, after flipping away from edges. Set on the arrow too. |
data-align | startcenterendHow the card lines up with its trigger. |
<ui-hover-card-arrow>
[data-slot="hover-card-arrow"]
| 属性 | 含义 |
|---|---|
data-closed | Present while the card is closed, including while it animates out. |
data-open | Present while the card is open. On a trigger, while it's open from that trigger. |
data-side | toprightbottomleftWhere the card ended up, after flipping away from edges. Set on the arrow too. |
data-align | startcenterendHow the card 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 参考
属性是 kebab 写法的 attribute,比如 close-delay 和 side-offset:"false" 表示 false,数字仍然是数字。anchor 和 container 接受 CSS 选择器,controller 是一个 property。回调是 DOM 事件。
HoverCard
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 card is open. Pass it to control the card.
defaultOpen?boolean- Whether the card starts open, when uncontrolled.
openchange event- Runs when the card wants to open or close.
details.reasonsays why, anddetails.cancel()stops it. openchangecomplete event- Runs once the card has finished opening or closing, after any animation.
payloadchange event- Runs when the payload the content shows changes: a trigger with another payload opens the card, or takes the open card over, which fires no
openchange, and so does a controller'sopen({ payload })on the open card.details.cancel()keeps the previous payload. delay?number- Milliseconds the pointer rests on the trigger, or keyboard focus stays on it, before the card opens.
closeDelay?number- Milliseconds before the card closes once the pointer leaves the trigger and the card.
disabled?boolean- Stops the card from opening. The trigger keeps working as a link.
controller?PopupController<any, HoverCardOpenChangeReason, {}, string, HoverCardPayloadChangeReason>- Opens, closes and inspects the card from anywhere, and connects triggers outside it. Create one with
createHoverCardController(). debug?boolean- Logs every state change with its reason to the console, in development builds.
HoverCardTrigger
卡片之外的触发器用 for="card-id" 指向卡片,并把 payload 作为 property 传入,或用字符串作为 payload 属性。property 优先。
payload?unknown- Data for the content to render when this trigger opens the card, like the profile it links to.
controller?PopupController<any, HoverCardOpenChangeReason, {}, string, HoverCardPayloadChangeReason>- Connects a trigger outside the card, like every author link in a feed, to the card with this controller.
HoverCardContent
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 card opens on.
align?Align- How the popup lines up with the anchor along that side.
startandendfollow the reading direction. How the card 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 card, 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.
keepMounted?boolean- Whether the card stays in the page, hidden, while closed. Its content keeps its state between opens.
HoverCardArrow
从卡片最终所在的一侧指向链接。<ui-hover-card-arrow> 定位在内容的边缘上。
状态
同样的状态会作为数据属性显示在每个元素上。
HoverCardTrigger:
openboolean- Whether the card is open from this trigger.
HoverCardContent:
openboolean- Whether the card is open. False while it animates out.
payloadPayload | undefined- The payload of the last open, from the trigger that opened it or a controller, typed as the controller's
Payload.
HoverCardArrow:
openboolean- Whether the card is open. False as soon as it starts closing, while it still animates out.
原因
event.detail.reason 说明卡片为什么打开或关闭。
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 变更时,它说明是什么打开了卡片或接管了它。
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.
控制器
用 @ui-sdk/web/hover-card 的 createHoverCardController<Payload>() 创建一个,并把它赋给根元素的 controller property。根元素的 api property 有相同的方法,它的 open property 读取并设置卡片是否打开。Payload 是触发器和 open() 传入数据的类型。
每个写入方法都接受一个可选的 { reason, event },传给 openchange。
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<HoverCardOpenChangeReason> | undefined) => boolean- Opens or closes it. Returns false when the change was canceled or it was already open or closed.
open(options?)(options?: (PopupChangeOptions<HoverCardPayloadChangeReason> & { 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<HoverCardOpenChangeReason> & { 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<HoverCardOpenChangeReason> | 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.
事件
事件在自己的元素上触发,不冒泡,新状态在 event.detail.value 中,reason 和 event 在它旁边。在 openchange 上调用 preventDefault() 可以取消这次变更。
| 成员 | 所属 | 说明 |
|---|---|---|
open property, 属性 | ui-hover-card | 卡片是否打开。属性设置它的起始值,并且是实时的 |
api property | ui-hover-card | 控制器 |
controller property | ui-hover-card | 一个 createHoverCardController() 创建的控制器,用来从代码驱动它 |
openchange 事件 | ui-hover-card | detail: { value: open, reason, event } |
openchangecomplete 事件 | ui-hover-card | detail: { value: open },在动画之后 |
payloadchange 事件 | ui-hover-card | detail: { value: payload, reason, event },在内容的 payload 变更时 |
payload property | ui-hover-card-trigger | 给内容的数据,在触发器连接时读取 |
for 属性 | ui-hover-card-trigger | 触发器从外部打开的卡片的 id |
无障碍
触发器始终是一个普通的链接,卡片是它旁边的预览,而不是对话框。下面每一行都是一个自动化测试。
键盘
| 按键 | 作用 |
|---|---|
| Tab | 在链接上,delay 之后打开卡片;卡片已打开时,移动到卡片内 |
| Enter | 跟随链接 |
| Escape | 关闭卡片,并把焦点留在链接上 |
键盘焦点打开卡片前等待的 delay 与指针相同,所以在满是链接的页面里按 Tab 移动时,不会在每一站都闪出一张卡片。焦点离开卡片会关闭它。
触摸屏没有悬停,所以轻点链接会跟随链接,而不会打开卡片。卡片里的任何内容都应该出现在链接指向的页面上。
经过测试的行为
- Resting the pointer on the link opens the card.
- The card waits for its delay before opening.
- Moving the pointer away closes the card after its close delay.
- Moving the pointer into the card keeps it open.
- Opening on hover leaves focus where it was.
- Clicking the link follows it.
- Keyboard focus on the link opens the card after the delay.
- Keyboard focus on a link the pointer opened keeps the card open when the pointer leaves.
- Escape closes the card and leaves focus on the link.
- Enter follows the link.
- The card opens below the link.
- The card opens on the requested side.
- The card animates in from its starting style.
- The card stays in the page while it animates out.
- A click that focuses the link doesn't open the card from focus.
- Leaving the link before the delay keeps keyboard focus from opening it later.
- A tap follows the link without opening the card.
- Changes report why the card opened and closed.
运行于 React、Vue 和 web components。
其他行为:
- Tab from the link moves into the open card.
- Shift+Tab from the card returns to the link.
- Tab out of the card moves on past the link and closes it.
- Escape inside the card closes it and returns focus to the link.
- The card stays open while focus is in it, even when the pointer leaves.
运行于 React、Vue 和 web components。
在每个经过测试的框架里,屏幕阅读器听到的内容相同,由虚拟屏幕阅读器记录:
- Announcements while tabbing into the card and out.
运行于 React、Vue 和 web components。