Hover Card
悬停或通过键盘聚焦链接时预览它指向的内容,同时保留链接正常的跳转。
hover card 为在链接上停留的人显示链接指向内容的预览,比如某个人的个人资料。链接仍然是普通的链接。
import {
HoverCard,
HoverCardContent,
HoverCardTrigger,
} from "@ui-sdk/solid/hover-card"
function Example() {
return (
<HoverCard>
<HoverCardTrigger href="https://example.com/people/hollis">
@hollis
</HoverCardTrigger>
<HoverCardContent>
<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>
</HoverCardContent>
</HoverCard>
)
}
export { Example }安装
npm install @ui-sdk/solid @ui-sdk/core组合
用下面的组合构建 HoverCard:
HoverCard
├── HoverCardTrigger
└── HoverCardContent
└── HoverCardArrow触发器是一个链接(一个 <a>,所以要给它 href),按压它会跟随链接。内容是预览,箭头是可选的。
卡片只为在链接上停留的人补一份预览:里面的所有内容都应该能从链接指向的页面到达,因为触摸和屏幕阅读器用户可能永远不会打开它。要给按钮加一句提示,请使用 Tooltip。要放按压后打开的内容,请使用 Popover。
用法
导入部件并把它们组合起来:
import {
HoverCard,
HoverCardContent,
HoverCardTrigger,
} from "@ui-sdk/solid/hover-card"
function Example() {
return (
<HoverCard>
<HoverCardTrigger href="/people/hollis">@hollis</HoverCardTrigger>
<HoverCardContent>
<p>Hollis Grant</p>
<p>Design engineer on the payments team.</p>
</HoverCardContent>
</HoverCard>
)
}
export { Example }定位
side 选择卡片打开的方向,默认是 bottom;align 让它与链接的 start、center 或 end 对齐。空间不够时,卡片会翻到另一侧,并沿链接平移以留在屏幕内。
HoverCardArrow 跟随卡片实际落点的一侧,翻转之后也是如此,并得到相同的 data-side。它指向链接的中间,并用 arrowPadding 与边角保持距离;data-arrow-clamped 告诉你它什么时候无法指向中间。
import {
HoverCard,
HoverCardArrow,
HoverCardContent,
HoverCardTrigger,
} from "@ui-sdk/solid/hover-card"
import {
Select,
SelectContent,
SelectItem,
SelectItemIndicator,
SelectLabel,
SelectTrigger,
SelectValue,
} from "@ui-sdk/solid/select"
import { createSignal, For } from "solid-js"
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" },
]
type Side = "top" | "right" | "bottom" | "left"
type Align = "start" | "center" | "end"
function Example() {
const [side, setSide] = createSignal<Side>("bottom")
const [align, setAlign] = createSignal<Align>("center")
return (
<div data-slot="stack">
<div data-slot="controls">
<Select
items={sides}
value={side()}
onValueChange={(next) => next && setSide(next as Side)}
>
<SelectLabel>Side</SelectLabel>
<SelectTrigger>
<SelectValue />
<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 9 6 6 6-6" />
</svg>
</SelectTrigger>
<SelectContent>
<For each={sides}>
{(option) => (
<SelectItem value={option.value}>
{option.label}
<SelectItemIndicator>
<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>
</SelectItemIndicator>
</SelectItem>
)}
</For>
</SelectContent>
</Select>
<Select
items={aligns}
value={align()}
onValueChange={(next) => next && setAlign(next as Align)}
>
<SelectLabel>Align</SelectLabel>
<SelectTrigger>
<SelectValue />
<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 9 6 6 6-6" />
</svg>
</SelectTrigger>
<SelectContent>
<For each={aligns}>
{(option) => (
<SelectItem value={option.value}>
{option.label}
<SelectItemIndicator>
<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>
</SelectItemIndicator>
</SelectItem>
)}
</For>
</SelectContent>
</Select>
</div>
<HoverCard>
<HoverCardTrigger href="https://example.com/people/ines">
@ines
</HoverCardTrigger>
<HoverCardContent side={side()} align={align()} sideOffset={10}>
<HoverCardArrow />
<p>Inès Moreau</p>
<p>Product designer. Leads the checkout redesign.</p>
</HoverCardContent>
</HoverCard>
</div>
)
}
export { Example }sideOffset 是与链接之间的间距,默认 4 像素。alignOffset 沿它平移卡片,collisionPadding 是离窗口边缘保留的空间。anchor 让卡片贴着链接以外的东西定位:元素、CSS 选择器、像 { x, y } 这样的点,或任何带 getBoundingClientRect() 的对象。
<HoverCardContent
side="right"
align="start"
sideOffset={8}
collisionPadding={16}
anchor={row()}
/>延迟
delay 是指针在链接上停驻、或键盘焦点停留在链接上多久之后,卡片才打开:默认 600 毫秒。closeDelay 是指针离开链接和卡片之后,它还会保持打开多久:默认 300 毫秒。指针可以越过链接和卡片之间的间隙而不会关闭它。
disabled 会阻止卡片打开,只留下一个普通的链接。
<HoverCard delay={300} closeDelay={150} disabled={!previews()}>受控
传入 open={open()},并在 onOpenChange 中更新 signal。每次变更都带有原因,比如 trigger-hover、trigger-focus、focus-out、escape-key 或 outside-press。调用 details.cancel() 可以阻止它。
const [open, setOpen] = createSignal(false)
<HoverCard open={open()} onOpenChange={setOpen}>多个链接共用一张卡片
信息流或列表可以共用一张卡片,而不是为每个链接各渲染一张。把链接和卡片连接到同一个 createHoverCardController<Payload>()。每个链接传入一个 payload,比如它对应的人;内容从自己的状态里读取它。只有打开卡片的那个链接会得到 data-open。controller.open({ payload }) 从代码打开卡片。
const profile = createHoverCardController<Person>()
<For each={people}>
{(person) => (
<HoverCardTrigger controller={profile} payload={person} href={person.url}>
{person.name}
</HoverCardTrigger>
)}
</For>
<HoverCard controller={profile}>
<HoverCardContent<Person>>{(state) => <p>{state.payload?.bio}</p>}</HoverCardContent>
</HoverCard>卡片里也可以有自己的链接。从打开着卡片的链接按 Tab 会进入卡片,按 Tab 越过它的末尾则会移动到链接之后的页面内容。焦点离开卡片会关闭它。
容器
卡片就地渲染并显示在顶层,所以不会被任何祖先元素裁剪或遮挡。container 把卡片渲染到别处,适用于 iframe、影子根(shadow root)或特定的层叠上下文。见共享的浮层指南。
<HoverCardContent container={shadowRoot} />动画
内容打开时带有 data-starting-style,关闭时带有 data-ending-style。从这些状态做过渡,卡片会保持挂载,直到退场结束。onOpenChangeComplete 在过渡之后运行,keepMounted 让关闭的卡片留在页面里,保持隐藏,供从状态驱动退场的动画库使用。
[data-slot="hover-card-content"] {
transition:
opacity 150ms,
scale 150ms;
&:is([data-starting-style], [data-ending-style]) {
opacity: 0;
scale: 0.96;
}
}自定义渲染
每个部件都接受 render,它是一个接收要展开的 props 和部件状态的函数;它的 children 也可以是同一个状态的函数。
<HoverCardTrigger
href="/people/hollis"
render={(props) => (
<a {...props}>
<span aria-hidden="true">HG</span>
Hollis Grant
</a>
)}
/>样式
每个部件都有一个 data-slot,比如 hover-card-content,并通过数据属性下列出的属性展示自己的状态。用触发器上的 data-open 标记正在显示卡片的链接,用 data-side 为内容和箭头按最终落点设置样式。把 transform-origin: var(--transform-origin) 放在内容上,让它从链接开始缩放。
箭头伸出卡片之外时,让它周围的溢出保持可见。如果 body 需要滚动,把滚动放在内层元素上。
HoverCardContent
| 变量 | 内容 |
|---|---|
--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. |
数据属性
HoverCardTrigger
[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. |
HoverCardContent
[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. |
HoverCardArrow
[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 参考
属性和回调与下面相同,都作为 Solid props。
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.
onOpenChange?((open: boolean, details: ChangeDetails<HoverCardOpenChangeReason>) => void)- Runs when the card wants to open or close.
details.reasonsays why, anddetails.cancel()stops it. onOpenChangeComplete?((open: boolean) => void)- Runs once the card has finished opening or closing, after any animation.
onPayloadChange?((payload: unknown, details: ChangeDetails<HoverCardPayloadChangeReason>) => void)- 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
onOpenChange, 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
卡片之外的触发器还接受 controller。
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
从卡片最终所在的一侧指向链接。渲染一个 div。
状态
每个部件的渲染函数、基于状态的类名和槽位会收到什么。
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.
原因
details.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.
控制器
用 createHoverCardController<Payload>() 创建一个,并作为 controller 传给卡片以及它之外的所有触发器。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<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.
事件
回调先收到新状态,然后收到详情。
| 属性 | 所属 | 收到 |
|---|---|---|
onOpenChange | HoverCard | (open, details):新状态,以及原因 |
onOpenChangeComplete | HoverCard | (open),在动画之后 |
onPayloadChange | HoverCard | (payload, details):内容的新 payload,以及原因 |
无障碍
触发器始终是一个普通的链接,卡片是它旁边的预览,而不是对话框。下面每一行都是一个自动化测试。
键盘
| 按键 | 作用 |
|---|---|
| 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。