Skip to content

An open source design system that's fully customizable and agent ready

TypeScript

[Component Audit] HoverCard: open cards are now audited, and the styling props are documented (#9536)

Cindy Zhangf89fa3aa58ad
diff --git a/.changeset/hover-card-audit-docs.md b/.changeset/hover-card-audit-docs.md
new file mode 100644
index 0000000000..f93ac664a5
--- /dev/null
+++ b/.changeset/hover-card-audit-docs.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[docs] HoverCard: document the `xstyle`, `className`, `style`, and `isOpen` props in every doc language, say that a text trigger is wrapped for you and an element trigger needs no ref, and say that `hasHoverIndication` applies to text triggers only.
+
+@cixzhang
diff --git a/.github/a11y-audit-axe.json b/.github/a11y-audit-axe.json
index 04a5bee85c..5b718e69eb 100644
--- a/.github/a11y-audit-axe.json
+++ b/.github/a11y-audit-axe.json
@@ -30,5 +30,9 @@
"DropdownMenuDivider": {"readySelector": "[role=\"menu\"]"},
"DropdownMenuGroup": {"readySelector": "[role=\"menu\"]"},
"DropdownMenuItem": {"readySelector": "[role=\"menu\"]"},
- "DropdownMenuSubMenu": {"evidence": "dropdown-menu-submenu-audit-evidence"}
+ "DropdownMenuSubMenu": {"evidence": "dropdown-menu-submenu-audit-evidence"},
+ "HoverCard": {
+ "stories": ["core-hovercard--open-states"],
+ "readySelector": "[role=\"dialog\"]"
+ }
}
diff --git a/apps/storybook/stories/HoverCard.stories.tsx b/apps/storybook/stories/HoverCard.stories.tsx
index 4dac4d156b..c4a5cf69c9 100644
--- a/apps/storybook/stories/HoverCard.stories.tsx
+++ b/apps/storybook/stories/HoverCard.stories.tsx
@@ -4,6 +4,7 @@ import type {Meta, StoryObj} from '@storybook/react';
import {HoverCard, useHoverCard} from '@astryxdesign/core/HoverCard';
import {Button} from '@astryxdesign/core/Button';
import {VStack, HStack} from '@astryxdesign/core/Layout';
+import {Text} from '@astryxdesign/core/Text';
const meta: Meta<typeof HoverCard> = {
title: 'Core/HoverCard',
@@ -235,3 +236,57 @@ export const TouchTriggers: Story = {
</div>
),
};
+
+function AuditProfile({name, role}: {name: string; role: string}) {
+ return (
+ <VStack gap={1}>
+ <Text type="label">{name}</Text>
+ <Text type="supporting">{role}</Text>
+ </VStack>
+ );
+}
+
+/**
+ * Both popup roles, shown open. An unlabelled card on a text trigger is a
+ * group that describes its trigger. A labelled card with actions is a named
+ * dialog that its button advertises.
+ */
+export const OpenStates: Story = {
+ render: () => (
+ <VStack gap={0}>
+ <div style={{paddingBlock: '24px 152px', paddingInline: 16}}>
+ <Text as="p">
+ Maintained by{' '}
+ <HoverCard
+ isOpen
+ placement="below"
+ alignment="start"
+ content={<AuditProfile name="Jane Doe" role="Software engineer" />}>
+ Jane Doe
+ </HoverCard>
+ .
+ </Text>
+ </div>
+ <div style={{paddingBlock: '0 200px', paddingInline: 16}}>
+ <HoverCard
+ isOpen
+ label="Jane Doe profile"
+ placement="below"
+ alignment="start"
+ content={
+ <VStack gap={3}>
+ <AuditProfile name="Jane Doe" role="Software engineer" />
+ <HStack gap={2}>
+ <Button label="Follow" variant="primary">
+ Follow
+ </Button>
+ <Button label="Message">Message</Button>
+ </HStack>
+ </VStack>
+ }>
+ <Button label="Jane Doe">Jane Doe</Button>
+ </HoverCard>
+ </div>
+ </VStack>
+ ),
+};
diff --git a/packages/core/src/HoverCard/HoverCard.doc.mjs b/packages/core/src/HoverCard/HoverCard.doc.mjs
index 8240f0faff..53dbf2a127 100644
--- a/packages/core/src/HoverCard/HoverCard.doc.mjs
+++ b/packages/core/src/HoverCard/HoverCard.doc.mjs
@@ -53,7 +53,8 @@ export const docs = {
{
name: 'children',
type: 'ReactNode',
- description: 'Trigger element that must accept a ref.',
+ description:
+ 'The trigger. A single string or number is wrapped in a focusable inline span. Text that reaches HoverCard in several pieces, such as `Edited {when}`, gets no trigger, so pass one string, such as a template literal, or wrap it in a focusable element. With element children, HoverCard wires the first element, so that element does not need to accept a ref.',
},
{
name: 'content',
@@ -128,7 +129,8 @@ export const docs = {
{
name: 'hasHoverIndication',
type: "'auto' | boolean",
- description: 'Shows a dashed underline on the trigger element.',
+ description:
+ 'Shows a dashed underline on a text trigger. auto shows it when children is a single string or number. It has no effect on an element trigger, which keeps its own styling.',
default: "'auto'",
},
{
@@ -140,7 +142,25 @@ export const docs = {
{
name: 'isOpen',
type: 'boolean',
- description: 'Controlled open state for the hover card.',
+ description:
+ 'Controlled open state. true holds the card open. false holds it closed against hover, but focus on the trigger still opens it. A controlled card answers Escape by calling onOpenChange(false) without closing; it closes when you set isOpen to false, and focus inside the card then returns to the trigger.',
+ },
+ {
+ name: 'xstyle',
+ type: 'StyleXStyles',
+ description:
+ 'StyleX styles for the card surface, the element that carries the hover-card theme target.',
+ },
+ {
+ name: 'className',
+ type: 'string',
+ description:
+ 'Class name added to the card surface, beside the hover-card target class.',
+ },
+ {
+ name: 'style',
+ type: 'CSSProperties',
+ description: 'Inline styles for the card surface.',
},
],
},
@@ -245,7 +265,8 @@ export const docsZh = {
{
name: 'children',
type: 'ReactNode',
- description: '必须接受 ref 的触发元素。',
+ description:
+ '触发元素。单个字符串或数字会被包裹在可聚焦的内联 span 中。分成多段到达的文本(例如 `Edited {when}`)不会得到触发器,请传入单个字符串(例如模板字符串)或用可聚焦元素包裹。传入元素时,HoverCard 连接第一个元素,因此该元素无需接受 ref。',
},
{
name: 'content',
@@ -313,7 +334,8 @@ export const docsZh = {
{
name: 'hasHoverIndication',
type: "'auto' | boolean",
- description: '在触发元素上显示虚线下划线。',
+ description:
+ '在文本触发元素上显示虚线下划线。auto:当 children 是单个字符串或数字时显示。对元素触发器无效,元素保留自身样式。',
default: "'auto'",
},
{
@@ -321,6 +343,28 @@ export const docsZh = {
type: 'boolean',
description: '是否在挂载时显示悬浮卡片。仍然可以关闭。',
},
+ {
+ name: 'isOpen',
+ type: 'boolean',
+ description:
+ '受控的打开状态。true 保持卡片打开。false 使悬停无法打开卡片,但触发元素获得焦点时仍会打开。受控卡片响应 Escape 时调用 onOpenChange(false) 而不关闭;将 isOpen 设为 false 时关闭,此时卡片内的焦点返回触发元素。',
+ },
+ {
+ name: 'xstyle',
+ type: 'StyleXStyles',
+ description:
+ '卡片表面(带有 hover-card 主题目标的元素)的 StyleX 样式。',
+ },
+ {
+ name: 'className',
+ type: 'string',
+ description: '添加到卡片表面的类名,与 hover-card 目标类名并列。',
+ },
+ {
+ name: 'style',
+ type: 'CSSProperties',
+ description: '卡片表面的内联样式。',
+ },
],
},
],
@@ -429,7 +473,8 @@ export const docsDense = {
description:
'Component wrapper for hover card overlay; richer overlay triggered on hover/focus.',
propDescriptions: {
- children: 'Trigger element; must accept ref.',
+ children:
+ 'Trigger. A single string/number is wrapped in a focusable inline span; text in several pieces (`Edited {when}`) gets no trigger; pass one string or a focusable element. With elements, the first element is wired (no ref needed).',
content: 'Hover card content.',
placement:
"Position relative to anchor element. Logical: start/end follow the popover's inherited direction (RTL mirrors).",
@@ -445,8 +490,14 @@ export const docsDense = {
'Accessible name for the popup. With label: named role="dialog"; without: role="group".',
onOpenChange:
'Callback when visibility changes; true=shown, false=hidden.',
- hasHoverIndication: 'Dashed underline on trigger element.',
+ hasHoverIndication:
+ 'Dashed underline on a text trigger. auto = single string/number children; no effect on element triggers.',
isDefaultOpen: 'Show hover card on mount. Still dismissible.',
+ isOpen:
+ 'Controlled open state. true holds open; false holds closed against hover, but trigger focus still opens it. Escape calls onOpenChange(false) without closing; setting false returns focus inside the card to the trigger.',
+ xstyle: 'StyleX styles for the card surface (hover-card target).',
+ className: 'Class added to the card surface.',
+ style: 'Inline styles for the card surface.',
},
},
],
diff --git a/packages/core/src/HoverCard/HoverCard.test.tsx b/packages/core/src/HoverCard/HoverCard.test.tsx
index 745d10fbfb..a49e365b08 100644
--- a/packages/core/src/HoverCard/HoverCard.test.tsx
+++ b/packages/core/src/HoverCard/HoverCard.test.tsx
@@ -16,6 +16,7 @@ import {
vi,
beforeAll,
beforeEach,
+ afterEach,
afterAll,
} from 'vitest';
import {
@@ -28,7 +29,8 @@ import {
} from '@testing-library/react';
import {renderToString} from 'react-dom/server';
import {hydrateRoot} from 'react-dom/client';
-import {StrictMode} from 'react';
+import {StrictMode, type ComponentProps} from 'react';
+import * as stylex from '@stylexjs/stylex';
import {Button} from '../Button/Button';
import {ClickableCard} from '../ClickableCard/ClickableCard';
import {Theme, defineTheme} from '../theme';
@@ -1433,3 +1435,178 @@ describe('HoverCard surface press', () => {
expect(screen.getByRole('checkbox')).not.toBeChecked();
});
});
+
+describe('HoverCard timing, hold, and controlled state', () => {
+ beforeEach(() => {
+ vi.useFakeTimers();
+ });
+
+ afterEach(() => {
+ vi.useRealTimers();
+ });
+
+ function advance(ms: number) {
+ act(() => {
+ vi.advanceTimersByTime(ms);
+ });
+ }
+
+ function renderCard(props: Partial<ComponentProps<typeof HoverCard>> = {}) {
+ const onOpenChange = vi.fn();
+ const result = render(
+ <HoverCard
+ content={<button type="button">Card action</button>}
+ onOpenChange={onOpenChange}
+ {...props}>
+ <button type="button">Trigger</button>
+ </HoverCard>,
+ );
+ return {
+ ...result,
+ onOpenChange,
+ trigger: screen.getByRole('button', {name: 'Trigger'}),
+ };
+ }
+
+ function cardSurface(): HTMLElement {
+ const action = screen.getByText('Card action');
+ return action.parentElement as HTMLElement;
+ }
+
+ it('opens only once the hover delay has passed', () => {
+ const {trigger, onOpenChange} = renderCard({delay: 300});
+ fireEvent.mouseEnter(trigger);
+ advance(299);
+ expect(onOpenChange).not.toHaveBeenCalled();
+ advance(1);
+ expect(onOpenChange).toHaveBeenCalledWith(true);
+ });
+
+ it('closes only once the hide delay has passed after the pointer leaves', () => {
+ const {trigger, onOpenChange} = renderCard({delay: 0, hideDelay: 200});
+ fireEvent.mouseEnter(trigger);
+ advance(0);
+ expect(onOpenChange).toHaveBeenLastCalledWith(true);
+ fireEvent.mouseLeave(trigger);
+ advance(199);
+ expect(onOpenChange).not.toHaveBeenCalledWith(false);
+ advance(1);
+ expect(onOpenChange).toHaveBeenLastCalledWith(false);
+ });
+
+ it('stays open while the pointer moves from the trigger into the card, and closes when it leaves the card', () => {
+ const {trigger, onOpenChange} = renderCard({delay: 0, hideDelay: 200});
+ fireEvent.mouseEnter(trigger);
+ advance(0);
+ fireEvent.mouseLeave(trigger);
+ fireEvent.mouseEnter(cardSurface());
+ advance(500);
+ expect(onOpenChange).not.toHaveBeenCalledWith(false);
+ expect(screen.getByText('Card action')).toBeInTheDocument();
+
+ fireEvent.mouseLeave(cardSurface());
+ advance(200);
+ expect(onOpenChange).toHaveBeenLastCalledWith(false);
+ });
+
+ it('keeps a card held open by isOpen={true} open when the pointer leaves', () => {
+ const {trigger, onOpenChange} = renderCard({
+ isOpen: true,
+ delay: 0,
+ hideDelay: 0,
+ });
+ expect(screen.getByText('Card action')).toBeInTheDocument();
+ fireEvent.mouseEnter(trigger);
+ fireEvent.mouseLeave(trigger);
+ advance(500);
+ expect(onOpenChange).not.toHaveBeenCalledWith(false);
+ expect(screen.getByText('Card action')).toBeInTheDocument();
+ });
+
+ it('keeps a card held closed by isOpen={false} closed on hover', () => {
+ const {trigger, onOpenChange} = renderCard({isOpen: false, delay: 0});
+ fireEvent.mouseEnter(trigger);
+ advance(500);
+ expect(onOpenChange).not.toHaveBeenCalled();
+ expect(screen.queryByText('Card action')).not.toBeInTheDocument();
+ });
+
+ it('returns focus to the trigger, without reopening, when the caller closes a card that holds focus', () => {
+ const {trigger, onOpenChange, rerender} = renderCard({isOpen: true});
+ const action = screen.getByText('Card action');
+ act(() => {
+ action.focus();
+ });
+ expect(action).toHaveFocus();
+ onOpenChange.mockClear();
+
+ rerender(
+ <HoverCard
+ content={<button type="button">Card action</button>}
+ onOpenChange={onOpenChange}
+ isOpen={false}>
+ <button type="button">Trigger</button>
+ </HoverCard>,
+ );
+ advance(500);
+ expect(trigger).toHaveFocus();
+ expect(onOpenChange).not.toHaveBeenCalledWith(true);
+ });
+
+ it('applies xstyle to the themed card surface', () => {
+ const overrides = stylex.create({card: {minWidth: 240}});
+ renderCard({isOpen: true, xstyle: overrides.card});
+ const card = screen.getByText('Card action').closest('[popover]');
+ expect(card).toHaveClass('astryx-hover-card');
+ const callerClasses = stylex.props(overrides.card).className?.split(' ');
+ expect(callerClasses?.length).toBeGreaterThan(0);
+ expect(card).toHaveClass(...(callerClasses ?? []));
+ });
+
+ it('applies className and style to the themed card surface', () => {
+ renderCard({
+ isOpen: true,
+ className: 'caller-card',
+ style: {maxInlineSize: 320},
+ });
+ const card = screen.getByText('Card action').closest('[popover]');
+ expect(card).toHaveClass('astryx-hover-card');
+ expect(card).toHaveClass('caller-card');
+ expect(card?.getAttribute('style')).toContain('max-inline-size: 320px');
+ });
+
+ it("restores the trigger's own popup attributes when the label is removed", () => {
+ const {rerender} = render(
+ <HoverCard content={<span>Card content</span>} label="Profile" isOpen>
+ <button
+ type="button"
+ aria-haspopup="menu"
+ aria-expanded="false"
+ aria-controls="own-menu">
+ Trigger
+ </button>
+ </HoverCard>,
+ );
+ const trigger = screen.getByRole('button', {name: 'Trigger'});
+ const cardId = screen.getByText('Card content').closest('[popover]')?.id;
+ expect(trigger).toHaveAttribute('aria-haspopup', 'dialog');
+ expect(trigger).toHaveAttribute('aria-expanded', 'true');
+ expect(trigger).toHaveAttribute('aria-controls', `own-menu ${cardId}`);
+
+ rerender(
+ <HoverCard content={<span>Card content</span>} isOpen>
+ <button
+ type="button"
+ aria-haspopup="menu"
+ aria-expanded="false"
+ aria-controls="own-menu">
+ Trigger
+ </button>
+ </HoverCard>,
+ );
+ expect(trigger).toHaveAttribute('aria-haspopup', 'menu');
+ expect(trigger).toHaveAttribute('aria-expanded', 'false');
+ expect(trigger).toHaveAttribute('aria-controls', 'own-menu');
+ expect(trigger).toHaveAttribute('aria-describedby');
+ });
+});
diff --git a/packages/core/src/HoverCard/HoverCard.tsx b/packages/core/src/HoverCard/HoverCard.tsx
index 4316875cdf..93a67b5af8 100644
--- a/packages/core/src/HoverCard/HoverCard.tsx
+++ b/packages/core/src/HoverCard/HoverCard.tsx
@@ -10,6 +10,7 @@
*
* SYNC: When modified, update these files to stay in sync:
* - /packages/core/src/HoverCard/HoverCard.test.tsx
+ * - /packages/core/src/HoverCard/HoverCard.doc.mjs
* - /packages/core/src/HoverCard/index.ts
* - /apps/storybook/stories/HoverCard.stories.tsx
* - /packages/cli/assets/templates/blocks/components/HoverCard/ (showcase blocks)
@@ -190,9 +191,10 @@ export interface HoverCardProps extends Pick<
onOpenChange?: (isOpen: boolean) => void;
/**
- * Whether to show hover indication (dashed underline) on the trigger.
- * - `'auto'`: Show for text-only children
- * - `true`: Always show
+ * Whether to show hover indication (dashed underline) on a text trigger.
+ * An element trigger keeps its own styling, so this has no effect on it.
+ * - `'auto'`: Show when children is a single string or number
+ * - `true`: Show on a text trigger
* - `false`: Never show
*
* @default 'auto'
@@ -200,9 +202,10 @@ export interface HoverCardProps extends Pick<
hasHoverIndication?: 'auto' | boolean;
/**
- * Controlled open state. When provided, overrides hover/focus triggers:
+ * Controlled open state. When provided, overrides the hover trigger:
* - `true`: force-show the hover card (hover/focus hide is suppressed)
- * - `false`: force-hide the hover card
+ * - `false`: hide the hover card and keep hover from opening it; focus on
+ * the trigger still opens it
* - `undefined`: uncontrolled — hover/focus triggers manage visibility
*
* A controlled hover card still takes Escape when it is the top-most layer,
diff --git a/packages/core/src/HoverCard/__tests__/HoverCardAudit.a11y.chromium.spec.ts b/packages/core/src/HoverCard/__tests__/HoverCardAudit.a11y.chromium.spec.ts
new file mode 100644
index 0000000000..c5a00ecfd5
--- /dev/null
+++ b/packages/core/src/HoverCard/__tests__/HoverCardAudit.a11y.chromium.spec.ts
@@ -0,0 +1,582 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+// @pr-a11y audit HoverCard
+
+/**
+ * @file HoverCardAudit.a11y.chromium.spec.ts
+ * @input Exact-head HoverCard open states across themes, modes, direction, and viewport, plus a real hover and keyboard pass
+ * @output Screenshots and fail-closed sensor receipts for the HoverCard whole-component audit
+ * @position Component-owned Night Watch browser evidence; CI runs it only for a HoverCard audit pull request
+ */
+
+import {createHash} from 'node:crypto';
+import {execFileSync} from 'node:child_process';
+import * as fs from 'node:fs';
+import * as path from 'node:path';
+import {expect, test, type Page} from '@playwright/test';
+import {holdMotionStill} from '@astryxdesign/a11y-spec/chromium';
+import {
+ DEFAULT_STORYBOOK_DIR,
+ serveStorybook,
+ type StaticServer,
+} from '@astryxdesign/a11y-spec/storybook';
+
+const OUTPUT = path.resolve('hover-card-audit-evidence');
+const OPEN_STORY_ID = 'core-hovercard--open-states';
+const INTERACTIVE_STORY_ID = 'core-hovercard--interactive-content';
+const WIDE = {width: 1024, height: 900};
+const NARROW = {width: 320, height: 900};
+
+type Mode = 'light' | 'dark';
+type Direction = 'ltr' | 'rtl';
+type Theme = 'neutral' | 'butter';
+
+type AuditCase = {
+ key: string;
+ mode: Mode;
+ direction: Direction;
+ theme: Theme;
+ viewport: {width: number; height: number};
+};
+
+type AuditReceipt = {
+ passed: boolean;
+ expected: Record<string, unknown>;
+ failures: string[];
+};
+
+const cases: AuditCase[] = [];
+function addPair(
+ key: string,
+ options: Partial<Omit<AuditCase, 'key' | 'mode'>> = {},
+) {
+ for (const mode of ['light', 'dark'] as const) {
+ cases.push({
+ key: `${key}-${mode}`,
+ mode,
+ direction: options.direction ?? 'ltr',
+ theme: options.theme ?? 'neutral',
+ viewport: options.viewport ?? WIDE,
+ });
+ }
+}
+
+addPair('open-default');
+addPair('open-custom-theme', {theme: 'butter'});
+addPair('open-rtl', {direction: 'rtl'});
+addPair('open-narrow', {viewport: NARROW});
+
+test.describe.configure({mode: 'serial', retries: 0});
+let server: StaticServer;
+let checkoutSha: string;
+let storybookSha: string;
+
+function storyUrl(
+ storyId: string,
+ mode: Mode,
+ theme: Theme,
+ direction: Direction,
+) {
+ return `${server.origin}/iframe.html?id=${storyId}&viewMode=story&globals=colorMode:${mode};astryxTheme:${theme};direction:${direction}`;
+}
+
+async function settle(page: Page) {
+ await holdMotionStill(page);
+ await page.evaluate(async () => document.fonts.ready);
+ await page.evaluate(
+ async () =>
+ new Promise<void>(resolve =>
+ requestAnimationFrame(() => requestAnimationFrame(() => resolve())),
+ ),
+ );
+ await page.waitForTimeout(40);
+}
+
+async function observeEnvironment(page: Page) {
+ return page.evaluate(() => {
+ const directions = Array.from(
+ document.querySelectorAll<HTMLElement>('.astryx-hover-card'),
+ ).map(card => getComputedStyle(card).direction);
+ return {
+ theme: document
+ .querySelector('[data-astryx-theme]')
+ ?.getAttribute('data-astryx-theme'),
+ mode: document.documentElement.getAttribute('data-theme'),
+ direction:
+ directions.length > 0 && new Set(directions).size === 1
+ ? directions[0]
+ : directions.join(',') || null,
+ viewport: {width: innerWidth, height: innerHeight},
+ dpr: devicePixelRatio,
+ reducedMotion: matchMedia('(prefers-reduced-motion: reduce)').matches,
+ documentOverflow: document.documentElement.scrollWidth > innerWidth + 1,
+ fonts: document.fonts.status,
+ runningAnimations: document
+ .getAnimations()
+ .filter(animation => animation.playState === 'running').length,
+ storybookError:
+ document.querySelector('.sb-show-errordisplay') != null ||
+ document.body.classList.contains('sb-show-errordisplay'),
+ };
+ });
+}
+
+async function observeCards(page: Page) {
+ return page.evaluate(() => {
+ const round = (value: number) => Math.round(value * 10) / 10;
+ function box(element: Element | null) {
+ if (element == null) {
+ return null;
+ }
+ const rect = element.getBoundingClientRect();
+ return {
+ left: round(rect.left),
+ right: round(rect.right),
+ top: round(rect.top),
+ bottom: round(rect.bottom),
+ width: round(rect.width),
+ height: round(rect.height),
+ };
+ }
+ function isOpen(element: Element) {
+ try {
+ return element.matches(':popover-open');
+ } catch {
+ return false;
+ }
+ }
+ const cards = Array.from(
+ document.querySelectorAll<HTMLElement>('.astryx-hover-card'),
+ ).map(card => {
+ const body = card.firstElementChild as HTMLElement | null;
+ const bodyStyle = body ? getComputedStyle(body) : null;
+ return {
+ id: card.id,
+ role: card.getAttribute('role'),
+ ariaLabel: card.getAttribute('aria-label'),
+ open: isOpen(card),
+ targetClasses: Array.from(card.classList).filter(name =>
+ name.startsWith('astryx-'),
+ ),
+ box: box(card),
+ background: getComputedStyle(card).backgroundColor,
+ padding: bodyStyle
+ ? [
+ bodyStyle.paddingBlockStart,
+ bodyStyle.paddingInlineEnd,
+ bodyStyle.paddingBlockEnd,
+ bodyStyle.paddingInlineStart,
+ ]
+ : null,
+ text: card.textContent?.trim() ?? '',
+ };
+ });
+ const textTrigger = Array.from(
+ document.querySelectorAll<HTMLElement>('span[tabindex="0"]'),
+ ).find(span => span.textContent === 'Jane Doe');
+ const textStyle = textTrigger ? getComputedStyle(textTrigger) : null;
+ const buttonTrigger = Array.from(
+ document.querySelectorAll<HTMLElement>('button'),
+ ).find(
+ button =>
+ button.textContent?.trim() === 'Jane Doe' &&
+ button.closest('.astryx-hover-card') == null,
+ );
+ return {
+ cards,
+ textTrigger: textTrigger
+ ? {
+ box: box(textTrigger),
+ describedBy: textTrigger.getAttribute('aria-describedby'),
+ hasPopup: textTrigger.getAttribute('aria-haspopup'),
+ expanded: textTrigger.getAttribute('aria-expanded'),
+ decorationLine: textStyle?.textDecorationLine ?? null,
+ decorationStyle: textStyle?.textDecorationStyle ?? null,
+ }
+ : null,
+ buttonTrigger: buttonTrigger
+ ? {
+ box: box(buttonTrigger),
+ hasPopup: buttonTrigger.getAttribute('aria-haspopup'),
+ expanded: buttonTrigger.getAttribute('aria-expanded'),
+ controls: buttonTrigger.getAttribute('aria-controls'),
+ describedBy: buttonTrigger.getAttribute('aria-describedby'),
+ }
+ : null,
+ };
+ });
+}
+
+function imageInfo(png: Buffer, file: string) {
+ return {
+ file,
+ sha256: createHash('sha256').update(png).digest('hex'),
+ width: png.readUInt32BE(16),
+ height: png.readUInt32BE(20),
+ };
+}
+
+function writeReceipt(key: string, png: Buffer, receipt: object) {
+ fs.writeFileSync(path.join(OUTPUT, `${key}.png`), png);
+ fs.writeFileSync(
+ path.join(OUTPUT, `${key}.sensors.json`),
+ `${JSON.stringify(receipt, null, 2)}\n`,
+ );
+}
+
+test.beforeAll(async () => {
+ fs.rmSync(OUTPUT, {recursive: true, force: true});
+ fs.mkdirSync(OUTPUT, {recursive: true});
+ checkoutSha = execFileSync('git', ['rev-parse', 'HEAD'], {
+ encoding: 'utf8',
+ }).trim();
+ const expected = process.env.ASTRYX_HEAD_SHA;
+ if (expected && expected !== checkoutSha) {
+ throw new Error(
+ `checkout ${checkoutSha} does not match expected head ${expected}`,
+ );
+ }
+ server = await serveStorybook(
+ process.env.ASTRYX_STORYBOOK_DIR ?? DEFAULT_STORYBOOK_DIR,
+ );
+ const response = await fetch(`${server.origin}/astryx-build-sha.txt`);
+ if (!response.ok) {
+ throw new Error(`Storybook build has no SHA stamp (${response.status})`);
+ }
+ storybookSha = (await response.text()).trim();
+ if (storybookSha !== checkoutSha) {
+ throw new Error(
+ `Storybook ${storybookSha} does not match checkout ${checkoutSha}`,
+ );
+ }
+});
+
+test.afterAll(async () => {
+ await server?.close();
+});
+
+for (const item of cases) {
+ test(item.key, async ({browser}) => {
+ const context = await browser.newContext({
+ viewport: item.viewport,
+ deviceScaleFactor: 1,
+ colorScheme: item.mode,
+ reducedMotion: 'reduce',
+ });
+ const page = await context.newPage();
+ const pageErrors: string[] = [];
+ page.on('pageerror', error => pageErrors.push(String(error)));
+ await page.goto(
+ storyUrl(OPEN_STORY_ID, item.mode, item.theme, item.direction),
+ {waitUntil: 'load'},
+ );
+ await page.locator('#storybook-root').waitFor();
+ await expect(page.locator('.astryx-hover-card')).toHaveCount(2);
+ await page.locator('[role="dialog"]').waitFor();
+
+ await settle(page);
+ const first = await observeCards(page);
+ await page.waitForTimeout(100);
+ await settle(page);
+ const environment = await observeEnvironment(page);
+ const observed = await observeCards(page);
+ const geometryStable =
+ JSON.stringify(first.cards.map(card => card.box)) ===
+ JSON.stringify(observed.cards.map(card => card.box));
+
+ const failures: string[] = [];
+ const check = (condition: boolean, message: string) => {
+ if (!condition) {
+ failures.push(message);
+ }
+ };
+ const near = (actual: number, expected: number) =>
+ Math.abs(actual - expected) <= 2;
+
+ check(storybookSha === checkoutSha, 'storybook build mismatch');
+ check(pageErrors.length === 0, `page errors: ${pageErrors.join(' | ')}`);
+ check(!environment.storybookError, 'storybook error display');
+ check(environment.theme === item.theme, `theme ${environment.theme}`);
+ check(environment.mode === item.mode, `mode ${environment.mode}`);
+ check(
+ environment.direction === item.direction,
+ `direction ${environment.direction}`,
+ );
+ check(
+ environment.viewport.width === item.viewport.width &&
+ environment.viewport.height === item.viewport.height,
+ 'viewport mismatch',
+ );
+ check(environment.dpr === 1, `dpr ${environment.dpr}`);
+ check(environment.reducedMotion, 'reduced motion not applied');
+ check(environment.fonts === 'loaded', `fonts ${environment.fonts}`);
+ check(environment.runningAnimations === 0, 'animations still running');
+ check(geometryStable, 'geometry changed between samples');
+ check(!environment.documentOverflow, 'document scrolls horizontally');
+
+ const group = observed.cards.find(card => card.role === 'group');
+ const dialog = observed.cards.find(card => card.role === 'dialog');
+ const text = observed.textTrigger;
+ const button = observed.buttonTrigger;
+ check(group != null, 'no group card');
+ check(dialog != null, 'no dialog card');
+ check(text != null, 'no text trigger');
+ check(button != null, 'no button trigger');
+
+ for (const card of observed.cards) {
+ const id = card.role ?? 'unknown';
+ // one open surface carrying only the hover-card target, padded on
+ // every logical edge.
+ check(card.open, `${id}: card is not open in the top layer`);
+ check(
+ JSON.stringify(card.targetClasses) ===
+ JSON.stringify(['astryx-hover-card']),
+ `${id}: targets ${card.targetClasses.join(' ')}`,
+ );
+ const padding = card.padding ?? [];
+ check(
+ padding.length === 4 &&
+ padding.every(value => Number.parseFloat(value) > 0) &&
+ new Set(padding).size === 1,
+ `${id}: padding ${padding.join(' ')}`,
+ );
+ check(
+ card.background !== 'rgba(0, 0, 0, 0)',
+ `${id}: card paints no surface`,
+ );
+ if (card.box != null) {
+ check(
+ card.box.left >= -0.5 &&
+ card.box.right <= environment.viewport.width + 0.5,
+ `${id}: card leaves the viewport inline`,
+ );
+ }
+ }
+
+ if (group != null && text != null && group.box && text.box) {
+ // without a label the card is a group that describes its trigger.
+ check(group.ariaLabel == null, 'group: has an aria-label');
+ check(text.describedBy === group.id, 'text trigger: not described');
+ check(text.hasPopup == null, 'text trigger: advertises a popup');
+ check(text.expanded == null, 'text trigger: aria-expanded on a span');
+ // the default hover cue on a text trigger.
+ check(
+ text.decorationLine === 'underline' &&
+ text.decorationStyle === 'dashed',
+ `text trigger: decoration ${text.decorationLine} ${text.decorationStyle}`,
+ );
+ check(group.box.top >= text.box.bottom - 0.5, 'group: not below');
+ }
+
+ if (dialog != null && button != null && dialog.box && button.box) {
+ // with a label the card is a named dialog its button advertises.
+ check(dialog.ariaLabel === 'Jane Doe profile', 'dialog: wrong name');
+ check(button.hasPopup === 'dialog', 'button: aria-haspopup');
+ check(button.expanded === 'true', 'button: aria-expanded');
+ check(
+ (button.controls ?? '').split(' ').includes(dialog.id),
+ 'button: aria-controls does not name the dialog',
+ );
+ check(button.describedBy == null, 'button: described by the dialog');
+ check(dialog.box.top >= button.box.bottom - 0.5, 'dialog: not below');
+ if (item.viewport === WIDE) {
+ // alignment="start" follows the inherited direction.
+ check(
+ item.direction === 'rtl'
+ ? near(dialog.box.right, button.box.right)
+ : near(dialog.box.left, button.box.left),
+ 'dialog: not aligned to the trigger inline start',
+ );
+ }
+ }
+
+ const png = await page.screenshot({animations: 'disabled', fullPage: true});
+ check(png.length > 1000, 'screenshot is empty');
+ writeReceipt(item.key, png, {
+ schemaVersion: 1,
+ expected: {
+ build: checkoutSha,
+ storyId: OPEN_STORY_ID,
+ mode: item.mode,
+ direction: item.direction,
+ theme: item.theme,
+ viewport: item.viewport,
+ semantics:
+ 'unlabelled card is a group that describes its text trigger; labelled card is a dialog named "Jane Doe profile" that its button advertises with aria-haspopup, aria-expanded, and aria-controls',
+ surface:
+ 'each open card carries only astryx-hover-card, paints a surface, has equal non-zero padding on every logical edge, sits below its trigger, and stays inside the viewport',
+ alignment:
+ 'at 1024px the labelled card starts at its trigger inline start, mirrored in RTL',
+ },
+ observed: {
+ build: storybookSha,
+ ...environment,
+ ...observed,
+ geometryStable,
+ pageErrors,
+ },
+ image: imageInfo(png, `${item.key}.png`),
+ failures,
+ passed: failures.length === 0,
+ });
+ await context.close();
+ });
+}
+
+test('hover-and-keyboard', async ({browser}) => {
+ const key = 'hover-and-keyboard';
+ const context = await browser.newContext({
+ viewport: WIDE,
+ deviceScaleFactor: 1,
+ colorScheme: 'light',
+ reducedMotion: 'reduce',
+ });
+ const page = await context.newPage();
+ const pageErrors: string[] = [];
+ page.on('pageerror', error => pageErrors.push(String(error)));
+ await page.goto(storyUrl(INTERACTIVE_STORY_ID, 'light', 'neutral', 'ltr'), {
+ waitUntil: 'load',
+ });
+ await page.locator('#storybook-root').waitFor();
+ await settle(page);
+
+ const failures: string[] = [];
+ const check = (condition: boolean, message: string) => {
+ if (!condition) {
+ failures.push(message);
+ }
+ };
+ const steps: Record<string, unknown> = {};
+ const trigger = page.getByRole('button', {
+ name: 'Hover for interactive content',
+ });
+ const card = page.locator('.astryx-hover-card');
+ const cardOpen = async () =>
+ card.evaluateAll(nodes =>
+ nodes.some(node => {
+ try {
+ return node.matches(':popover-open');
+ } catch {
+ return false;
+ }
+ }),
+ );
+
+ // hovering the trigger opens the card after the delay.
+ await page.mouse.move(5, 5);
+ await trigger.hover();
+ await expect.poll(cardOpen, {timeout: 3000}).toBe(true);
+ steps.hoverOpens = await cardOpen();
+ steps.describedBy = await trigger.getAttribute('aria-describedby');
+ steps.cardId = await card.first().getAttribute('id');
+ steps.cardRole = await card.first().getAttribute('role');
+ check(steps.hoverOpens === true, 'hover did not open the card');
+ check(steps.cardRole === 'group', `card role ${String(steps.cardRole)}`);
+ check(
+ steps.describedBy === steps.cardId,
+ 'trigger is not described by the card',
+ );
+ await settle(page);
+ const png = await page.screenshot({animations: 'disabled', fullPage: true});
+
+ // moving from the trigger into the card keeps it open.
+ await page.getByRole('button', {name: 'Follow'}).hover();
+ await page.waitForTimeout(600);
+ steps.openWhileOnCard = await cardOpen();
+ check(steps.openWhileOnCard === true, 'card closed while pointer on it');
+
+ // leaving the card closes it after the hide delay.
+ await page.mouse.move(5, 5);
+ await expect.poll(cardOpen, {timeout: 3000}).toBe(false);
+ steps.closesAfterLeave = !(await cardOpen());
+ check(steps.closesAfterLeave === true, 'card stayed open after leave');
+
+ // keyboard focus opens it, Tab reaches its actions, and
+ // Escape closes it and returns focus to the trigger without reopening.
+ await trigger.focus();
+ await expect.poll(cardOpen, {timeout: 3000}).toBe(true);
+ steps.focusOpens = true;
+ await page.keyboard.press('Tab');
+ steps.tabReachesAction = await page.evaluate(
+ () => document.activeElement?.textContent?.trim() ?? null,
+ );
+ check(
+ steps.tabReachesAction === 'Follow',
+ `Tab moved focus to ${String(steps.tabReachesAction)}`,
+ );
+ await page.keyboard.press('Escape');
+ await expect.poll(cardOpen, {timeout: 3000}).toBe(false);
+ await page.waitForTimeout(600);
+ steps.escapeClosed = !(await cardOpen());
+ steps.focusAfterEscape = await page.evaluate(
+ () => document.activeElement?.textContent?.trim() ?? null,
+ );
+ check(steps.escapeClosed === true, 'Escape did not keep the card closed');
+ check(
+ steps.focusAfterEscape === 'Hover for interactive content',
+ `focus after Escape on ${String(steps.focusAfterEscape)}`,
+ );
+
+ check(storybookSha === checkoutSha, 'storybook build mismatch');
+ check(pageErrors.length === 0, `page errors: ${pageErrors.join(' | ')}`);
+ check(png.length > 1000, 'screenshot is empty');
+ writeReceipt(key, png, {
+ schemaVersion: 1,
+ expected: {
+ build: checkoutSha,
+ storyId: INTERACTIVE_STORY_ID,
+ mode: 'light',
+ direction: 'ltr',
+ theme: 'neutral',
+ viewport: WIDE,
+ behavior:
+ 'hover opens a group card that describes its trigger; it stays open while the pointer is on the card and closes after the pointer leaves; focus opens it, Tab reaches its first action, and Escape closes it and returns focus to the trigger without reopening',
+ image: 'the hover-opened card',
+ },
+ observed: {
+ build: storybookSha,
+ ...(await observeEnvironment(page)),
+ steps,
+ pageErrors,
+ },
+ image: imageInfo(png, `${key}.png`),
+ failures,
+ passed: failures.length === 0,
+ });
+ await context.close();
+});
+
+test('manifest is complete', async () => {
+ const keys = [...cases.map(item => item.key), 'hover-and-keyboard'];
+ const receiptFiles = fs
+ .readdirSync(OUTPUT)
+ .filter(file => file.endsWith('.sensors.json'));
+ const receipts = receiptFiles.map(
+ (file): AuditReceipt =>
+ JSON.parse(
+ fs.readFileSync(path.join(OUTPUT, file), 'utf8'),
+ ) as AuditReceipt,
+ );
+ fs.writeFileSync(
+ path.join(OUTPUT, 'manifest.json'),
+ `${JSON.stringify(
+ {
+ schemaVersion: 1,
+ component: 'core/HoverCard',
+ build: checkoutSha,
+ frames: keys.map(key => ({
+ key,
+ image: `${key}.png`,
+ receipt: `${key}.sensors.json`,
+ })),
+ },
+ null,
+ 2,
+ )}\n`,
+ );
+ expect(receiptFiles).toHaveLength(keys.length);
+ expect(
+ receipts
+ .filter(receipt => !receipt.passed)
+ .map(receipt => ({frame: receipt.expected, failures: receipt.failures})),
+ ).toEqual([]);
+});
diff --git a/packages/core/src/HoverCard/useHoverCard.tsx b/packages/core/src/HoverCard/useHoverCard.tsx
index 6a04f201fe..bce45cf4d2 100644
--- a/packages/core/src/HoverCard/useHoverCard.tsx
+++ b/packages/core/src/HoverCard/useHoverCard.tsx
@@ -133,9 +133,10 @@ export interface HoverCardOptions {
label?: string;
/**
- * Controlled open state. When provided, overrides hover/focus triggers:
+ * Controlled open state. When provided, overrides the hover trigger:
* - `true`: force-show the hover card (hover/focus hide is suppressed)
- * - `false`: force-hide the hover card
+ * - `false`: hide the hover card and keep hover from opening it; focus on
+ * the trigger still opens it
* - `undefined`: uncontrolled — hover/focus triggers manage visibility
*
* A controlled hover card still takes Escape when it is the top-most layer,