Skip to content

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

TypeScript

fix(HoverCard): a labelled card puts aria-haspopup only on a trigger whose role supports it (#10733)

Cindy Zhangaa31eab11c9a
diff --git a/.changeset/hovercard-roleless-trigger-haspopup.md b/.changeset/hovercard-roleless-trigger-haspopup.md
new file mode 100644
index 0000000000..1bdaac1a4f
--- /dev/null
+++ b/.changeset/hovercard-roleless-trigger-haspopup.md
@@ -0,0 +1,6 @@
+---
+'@astryxdesign/core': patch
+---
+
+[fix] HoverCard: a labelled card no longer puts `aria-haspopup="dialog"` on a role-less trigger, such as text or a `<time>`. Such a trigger names the open card through `aria-controls` only; a button or link trigger still gets `aria-haspopup` and `aria-expanded`.
+@cixzhang
diff --git a/apps/storybook/stories/HoverCard.stories.tsx b/apps/storybook/stories/HoverCard.stories.tsx
index c4a5cf69c9..fc004c92c0 100644
--- a/apps/storybook/stories/HoverCard.stories.tsx
+++ b/apps/storybook/stories/HoverCard.stories.tsx
@@ -216,6 +216,28 @@ export const TextNodeMultiple: Story = {
),
};
+/**
+ * A labelled card on a text trigger. The trigger is a role-less span, so it
+ * names the open card through aria-controls and carries no aria-haspopup.
+ */
+export const LabelledTextTrigger: Story = {
+ render: () => (
+ <div style={{padding: 100}}>
+ <p>
+ This feature was created by{' '}
+ <HoverCard
+ content={<ProfileCard />}
+ label="Jane Doe profile"
+ placement="below"
+ isOpen>
+ Jane Doe
+ </HoverCard>{' '}
+ and shipped last week.
+ </p>
+ </div>
+ ),
+};
+
/**
* Touch has no hover, so a tap decides instead. A tap-opened card is dismissed
* by a tap outside it, and a tap on the card's own content leaves it open.
diff --git a/docs/specs/components/HoverCard/HoverCard.spec.md b/docs/specs/components/HoverCard/HoverCard.spec.md
index 184893f9eb..192cb4b35b 100644
--- a/docs/specs/components/HoverCard/HoverCard.spec.md
+++ b/docs/specs/components/HoverCard/HoverCard.spec.md
@@ -13,6 +13,8 @@ review_triggers: [public-api, behavior, theming, accessibility]
verified_by:
[
packages/core/src/HoverCard/HoverCard.test.tsx,
+ packages/core/src/HoverCard/popupTrigger.test.ts,
+ packages/core/src/HoverCard/__tests__/HoverCardTriggerRoles.a11y.browser.spec.ts,
packages/core/src/Layer/layerDismissalFamilies.test.tsx,
packages/core/src/Layer/useTouchTrigger.test.ts,
packages/core/src/Layer/touchTriggerTargets.test.tsx,
@@ -39,15 +41,15 @@ system_specs: [spec:AST-003, spec:AST-017]
## Contract at a glance
-| Area | Contract |
-| ----------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
-| Public contract | `HoverCard` with `children` (trigger), `content`, `label`, `placement` (`above`), `alignment` (`center`), `delay` (300), `hideDelay` (200), `focusTrigger`, `touchTrigger` (`auto`), `isEnabled`, `isOpen`, `isDefaultOpen`, `onOpenChange`, and `hasHoverIndication`; target `hover-card`. `useHoverCard` takes the same `touchTrigger`. |
-| Behavior | A floating card of rich, possibly interactive content anchored to a trigger. It opens on hover after `delay`, on focus, and on a tap that `touchTrigger` allows, stays open while the pointer is on the trigger or card, and closes on leave, Escape, or a tap outside. With `label` it is a named dialog the trigger advertises; without, a group that describes the trigger. With `touchTrigger="none"`, touch never opens it. |
-| End-user impact | Mouse, keyboard, and touch users can open the preview, move into it to use its actions, and dismiss it; screen-reader users hear it as a named popup dialog or as the trigger's description. Under the default `touchTrigger="auto"`, a tap on a trigger that performs an action performs only that action. |
-| Builder impact | `touchTrigger` answers whether it is safe to consume a tap to show the card (DEC-1): keep the default `auto` on a trigger that performs an action, pass `tap` where a tap only reveals the card, and pass `none` where a tap must never show it. |
-| Compatibility/readiness | No public API change: `touchTrigger` keeps its released values and its default `auto`. Three implementation gaps (see Current-state impact). |
-| Review checks | Reject an unnamed `dialog`, a card that cannot be hovered or dismissed (WCAG 1.4.13), Escape in the page that also closes a layer underneath, `aria-expanded` set on a trigger whose role does not support it, or a tap under `touchTrigger="auto"` that both performs the trigger's action and shows the card. |
-| Governing rules | WCAG 1.4.13, 2.1.1; `family:overlay-dismissal`; `spec:AST-003` FR4; `spec:AST-017` (lifecycle); `architecture:public-component-api` INV9, INV21; `architecture:layer-runtime`; `architecture:interaction-modality`; `architecture:component-theming-surface`. |
+| Area | Contract |
+| ----------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| Public contract | `HoverCard` with `children` (trigger), `content`, `label`, `placement` (`above`), `alignment` (`center`), `delay` (300), `hideDelay` (200), `focusTrigger`, `touchTrigger` (`auto`), `isEnabled`, `isOpen`, `isDefaultOpen`, `onOpenChange`, and `hasHoverIndication`; target `hover-card`. `useHoverCard` takes the same `touchTrigger`. |
+| Behavior | A floating card of rich, possibly interactive content anchored to a trigger. It opens on hover after `delay`, on focus, and on a tap that `touchTrigger` allows, stays open while the pointer is on the trigger or card, and closes on leave, Escape, or a tap outside. With `label` it is a named dialog the trigger names while open (and advertises, when the trigger's role supports it); without, a group that describes the trigger. With `touchTrigger="none"`, touch never opens it. |
+| End-user impact | Mouse, keyboard, and touch users can open the preview, move into it to use its actions, and dismiss it; screen-reader users hear it as a named dialog, announced as a popup on a button or link trigger, or as the trigger's description. Under the default `touchTrigger="auto"`, a tap on a trigger that performs an action performs only that action. |
+| Builder impact | `touchTrigger` answers whether it is safe to consume a tap to show the card (DEC-1): keep the default `auto` on a trigger that performs an action, pass `tap` where a tap only reveals the card, and pass `none` where a tap must never show it. |
+| Compatibility/readiness | No public API change: `touchTrigger` keeps its released values and its default `auto`. Three implementation gaps (see Current-state impact). |
+| Review checks | Reject an unnamed `dialog`, a card that cannot be hovered or dismissed (WCAG 1.4.13), Escape in the page that also closes a layer underneath, `aria-expanded` set on a trigger whose role does not support it, or a tap under `touchTrigger="auto"` that both performs the trigger's action and shows the card. |
+| Governing rules | WCAG 1.4.13, 2.1.1; `family:overlay-dismissal`; `spec:AST-003` FR4; `spec:AST-017` (lifecycle); `architecture:public-component-api` INV9, INV21; `architecture:layer-runtime`; `architecture:interaction-modality`; `architecture:component-theming-surface`. |
Under `none`, no touch or pen tap opens the card.
@@ -122,7 +124,7 @@ Consumer migration instructions belong in consumer docs and release notes.
| ---- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------ |
| FR1 | The open card is one surface carrying only the `hover-card` target, padded on every logical edge, with `content` inside and the theme's body font. `xstyle`, `className`, and `style` apply to the card. | Current source and tests |
| FR2 | Trigger wiring: text children, strings and numbers (one, or several written around an expression such as `Edited {when}`) with holes such as `false` and `null` ignored, are wrapped in one focusable inline span; element `children` attach to their first element inside an inline-safe wrapper, and a first element replaced after mount, by new children or by a child that swaps its own root, is wired in place of the old one. | Current source and tests |
-| FR3 | With `label`, the card is `role="dialog"` named by `label`; the trigger gets `aria-haspopup="dialog"` and, only when its role supports it, `aria-expanded`, each replacing the trigger's own value while the card is wired, plus `aria-controls` naming the card while open, merged with the trigger's own; the trigger's own values return on cleanup. Without `label`, the card is `role="group"` and the trigger's `aria-describedby` gains the card's id. | Current source and tests |
+| FR3 | With `label`, the card is `role="dialog"` named by `label`. A labelled trigger names the open card through `aria-controls`, merged with the trigger's own; it also gets `aria-haspopup="dialog"` and `aria-expanded` only when its role supports them (button, link and similar), never on a role-less element, each replacing the trigger's own value while the card is wired; the trigger's own values return on cleanup. Without `label`, the card is `role="group"` and the trigger's `aria-describedby` gains the card's id. | Current source and tests |
| FR4 | On a hover-capable pointer, entering the trigger opens the card after `delay` ms; leaving the trigger or the card closes it after `hideDelay` ms, and moving between them keeps it open. Any focus on the trigger, keyboard, pointer, or programmatic, opens it per `focusTrigger`, except the focus a tap leaves behind, the refocus after an Escape dismiss (FR6), and the refocus after a controlled close (FR7). Under `auto`, whether focus counts is judged when it arrives: focus on the trigger itself, or within a trigger that is focusable at that moment, so a roving-tabindex member opens when the arrow keys reach it. | WCAG 1.4.13; tests |
| FR5 | On touch and pen, a completed tap opens the card per `touchTrigger` on lift; a touch that becomes a scroll does not. Under `auto`, a tap opens it unless the trigger itself performs an action; an `aria-disabled` control, or a label for a disabled control, is not an action, so a disabled control's reason opens on a tap (DEC-1). Under `tap`, every tap opens it; under `none`, no tap does. A tap on the card's content keeps it open; a tap on the trigger while it is open, a tap outside, or a scroll starting outside closes it. Whether `auto` also leaves the card shut when the tap acts on a control around the trigger is open (`component:Tooltip` OQ1). | Current source and tests |
| FR6 | Escape closes a visible card through the shared dismissal stack when it is the topmost layer in the page, so a layer underneath stays open. Implementation gap: a card rendered into another document, such as an iframe or a Picture-in-Picture window, with no layer beneath it is never closed by Escape (Current-state impact). When focus was inside the card, it returns to the trigger, and that refocus does not reopen the card. | WCAG 1.4.13; tests |
@@ -137,13 +139,13 @@ Consumer migration instructions belong in consumer docs and release notes.
### Representative states
-| State | Required invariant | Allowed variation |
-| ------------------- | ---------------------------------------------- | ----------------- |
-| Unlabelled | `role="group"`; trigger described by the card. | Content. |
-| Labelled | Named `dialog`; trigger advertises the popup. | Content. |
-| Hover into card | Stays open; actions usable. | Delays. |
-| Escape from content | Closes; focus back on trigger; no reopen. | — |
-| Tap-open | Opens on lift; survives taps on its content. | — |
+| State | Required invariant | Allowed variation |
+| ------------------- | ----------------------------------------------------------------------------------------------------- | ----------------- |
+| Unlabelled | `role="group"`; trigger described by the card. | Content. |
+| Labelled | Named `dialog`; trigger names it while open, and advertises the popup only when its role supports it. | Content. |
+| Hover into card | Stays open; actions usable. | Delays. |
+| Escape from content | Closes; focus back on trigger; no reopen. | — |
+| Tap-open | Opens on lift; survives taps on its content. | — |
### Transformation and precedence order
@@ -205,7 +207,7 @@ Consumer migration instructions belong in consumer docs and release notes.
| Contract | Verification | Representative states | Mutation or failure expectation | Audit section |
| ------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------- |
| FR1, FR2, FR8 | `HoverCard.test.tsx` render, wrapper, mixed-text and its hover cue, portal, theme font, SSR, replaced-trigger, and card `xstyle`/`className`/`style` tests; `HoverCardAudit` Chromium frames of `HoverCard / Open States` for the single target, equal padding on every logical edge, and the text trigger's dashed hover cue | Text and element triggers; default open | A stray target, lost font, or hydration mismatch fails, and so do card `xstyle`, `className`, or `style` that do not reach the card, missing or unequal card padding, or a lost dashed cue on a text trigger. | `audit:HoverCard/anatomy` |
-| FR3, AR1 | `HoverCard.test.tsx` role, trigger-attribute, and attribute-restore tests; `HoverCardAudit` frames and the audit axe pass on `HoverCard / Open States` | Labelled and unlabelled; supported and unsupported roles | Wrong role, trigger attributes that are not replaced and restored as stated, or a new axe violation on an open card, fail. | `audit:HoverCard/accessibility` |
+| FR3, AR1 | `HoverCard.test.tsx` role, trigger-attribute, and attribute-restore tests; `popupTrigger.test.ts` role-support and attribute tests; `HoverCardTriggerRoles.a11y.browser.spec.ts` attribute checks and axe pass with a labelled role-less trigger open; `HoverCardAudit` frames and the audit axe pass on `HoverCard / Open States` | Labelled and unlabelled; supported and unsupported roles | Wrong role, trigger attributes that are not replaced and restored as stated, or a new axe violation on an open card, fail. | `audit:HoverCard/accessibility` |
| FR4–FR6, AR2 | `HoverCard.test.tsx` hover, delay and hide-delay timing, trigger-to-card hold, Escape, refocus, and touch tests, and its `focusTrigger="auto"` roving, `<summary>`, wrapper, left-the-tab-order, and focus-inside-a-focusable-trigger cases; `HoverCardAudit` hover-and-keyboard pass in Chromium; `useTouchTrigger.test.ts` and `touchTriggerTargets.test.tsx` disabled-control cases | Hover, focus, tap, Escape from trigger and content; `touchTrigger` `auto`, `tap`, and `none`; an action trigger; a disabled control inside a clickable row | A card that cannot be reached or dismissed, that opens before `delay` or closes before `hideDelay`, that closes while the pointer moves from the trigger into it, or that opens on a tap on a trigger that performs an action under `auto` or on any tap under `none`, fails. | `audit:HoverCard/behavior` |
| FR7 | `HoverCard.test.tsx` isEnabled, isDefaultOpen, onOpenChange, `isOpen` forcing, and controlled-close focus-return tests; `layerDismissalFamilies.test.tsx` controlled HoverCard case | Disabled, default open, held open, held closed, closed by the caller with focus inside | Wrong state reporting, a hover that hides a card held open or opens one held closed, or focus left inside a card the caller closes, fails. | `audit:HoverCard/behavior` |
| FR11 | `HoverCard.test.tsx` surface-press suite | A card inside a clickable container and inside a `<label>`; a button inside the card | A click on card content that runs the container's click handler or activates a labelled control, or a card button that stops working, fails. | — |
diff --git a/internal/eslint-plugin-astryx/no-comment-provenance.baseline.json b/internal/eslint-plugin-astryx/no-comment-provenance.baseline.json
index 0510a54723..2a64e8ae14 100644
--- a/internal/eslint-plugin-astryx/no-comment-provenance.baseline.json
+++ b/internal/eslint-plugin-astryx/no-comment-provenance.baseline.json
@@ -465,7 +465,7 @@
"spec:AST-085",
"spec:AST-086"
],
- "packages/core/src/HoverCard/HoverCard.tsx": ["#5049", "#5049"],
+ "packages/core/src/HoverCard/HoverCard.tsx": ["#5049"],
"packages/core/src/HoverCard/useHoverCard.tsx": ["FR11"],
"packages/core/src/Icon/Icon.tsx": ["ORD1", "spec quote"],
"packages/core/src/Indicator/CheckIndicator.tsx": ["#4838", "#4893"],
diff --git a/packages/core/src/HoverCard/HoverCard.test.tsx b/packages/core/src/HoverCard/HoverCard.test.tsx
index efb5be245a..738ce1c3af 100644
--- a/packages/core/src/HoverCard/HoverCard.test.tsx
+++ b/packages/core/src/HoverCard/HoverCard.test.tsx
@@ -636,7 +636,7 @@ describe('HoverCard', () => {
expect(trigger).toHaveAttribute('aria-expanded', 'false');
});
- it('omits aria-expanded on a trigger whose role does not support it', () => {
+ it('gives a role-less trigger neither aria-haspopup nor aria-expanded', () => {
render(
<HoverCard content={<span>Card content</span>} label="Timestamp details">
<time dateTime="2026-08-25" tabIndex={0}>
@@ -646,11 +646,26 @@ describe('HoverCard', () => {
);
const trigger = screen.getByText('2 hours ago');
expect(trigger.tagName).toBe('TIME');
- // Global attributes are valid on any element, so the popup relationship is
- // still advertised.
- expect(trigger).toHaveAttribute('aria-haspopup', 'dialog');
- // aria-expanded is not: <time> has no role that supports it, and emitting
- // it is a critical axe aria-allowed-attr violation.
+ // ARIA 1.2 supports neither attribute on the time role.
+ expect(trigger).not.toHaveAttribute('aria-haspopup');
+ expect(trigger).not.toHaveAttribute('aria-expanded');
+ });
+
+ it('names the open card from a role-less trigger through aria-controls only', () => {
+ render(
+ <HoverCard
+ content={<span>Card content</span>}
+ label="Profile actions"
+ isOpen>
+ <span tabIndex={0} aria-controls="own-region">
+ Trigger
+ </span>
+ </HoverCard>,
+ );
+ const trigger = screen.getByText('Trigger');
+ const card = screen.getByRole('dialog', {hidden: true});
+ expect(trigger).toHaveAttribute('aria-controls', `own-region ${card.id}`);
+ expect(trigger).not.toHaveAttribute('aria-haspopup');
expect(trigger).not.toHaveAttribute('aria-expanded');
});
@@ -787,11 +802,12 @@ describe('HoverCard', () => {
);
// Text should be rendered
expect(screen.getByText('Just text, no element')).toBeInTheDocument();
- // When labelled, the wrapper advertises a dialog popup.
+ // The wrapper is a role-less <span>, so it carries neither
+ // aria-haspopup nor aria-expanded.
const wrapper = screen.getByText('Just text, no element');
expect(wrapper.tagName).toBe('SPAN');
- expect(wrapper).toHaveAttribute('aria-haspopup', 'dialog');
- // The wrapper is a role-less <span>; aria-expanded is invalid there.
+ expect(wrapper).toHaveAttribute('tabindex', '0');
+ expect(wrapper).not.toHaveAttribute('aria-haspopup');
expect(wrapper).not.toHaveAttribute('aria-expanded');
// While closed, the layer is not in the DOM, so aria-controls is unset.
expect(wrapper).not.toHaveAttribute('aria-controls');
@@ -904,10 +920,8 @@ describe('HoverCard', () => {
Edited {isDraft && 'draft'} {null}today
</HoverCard>,
);
- expect(screen.getByText(/Edited/)).toHaveAttribute(
- 'aria-haspopup',
- 'dialog',
- );
+ // The text wrapper is the trigger: it is the tab stop.
+ expect(screen.getByText(/Edited/)).toHaveAttribute('tabindex', '0');
});
// The auto hover cue (FR8) is a class on the text trigger; a single
@@ -951,13 +965,14 @@ describe('HoverCard', () => {
it('still attaches to the first element when one is present', () => {
render(
- <HoverCard label="History" content={<span>Card</span>}>
+ <HoverCard label="History" content={<span>Card</span>} isOpen>
Edited <time dateTime="2026-11-02">today</time>
</HoverCard>,
);
+ const card = screen.getByRole('dialog', {hidden: true});
expect(screen.getByText('today')).toHaveAttribute(
- 'aria-haspopup',
- 'dialog',
+ 'aria-controls',
+ card.id,
);
});
});
diff --git a/packages/core/src/HoverCard/HoverCard.tsx b/packages/core/src/HoverCard/HoverCard.tsx
index dc125890f8..3de4d6926e 100644
--- a/packages/core/src/HoverCard/HoverCard.tsx
+++ b/packages/core/src/HoverCard/HoverCard.tsx
@@ -42,66 +42,12 @@ export type {
HoverCardTouchTrigger,
} from './useHoverCard';
import {mergeIds} from './mergeIds';
-
-// `aria-haspopup` and `aria-controls` are global, so any trigger may carry
-// them. `aria-expanded` is not. This is the ARIA 1.2 "Supported States and
-// Properties" list for it — deliberately the narrow reading: axe accepts the
-// attribute on rather more roles, since it also allows every subclass of these,
-// so a role outside this set is not necessarily a violation. Widening it is
-// safe; the set is a floor, not the spec's ceiling. The same rule is applied in
-// Chat/useTriggerMenu.tsx, which only emits the combobox attributes once the
-// element is actually a combobox.
-const EXPANDABLE_ROLES = new Set([
- 'application',
- 'button',
- 'checkbox',
- 'columnheader',
- 'combobox',
- 'gridcell',
- 'link',
- 'listbox',
- 'menuitem',
- 'menuitemcheckbox',
- 'menuitemradio',
- 'row',
- 'rowheader',
- 'switch',
- 'tab',
- 'treeitem',
-]);
-
-const BUTTON_INPUT_TYPES = new Set(['button', 'submit', 'reset', 'image']);
-
-// Deliberately partial, and unlisted elements are read as role-less: dropping
-// aria-expanded where it might have been legal costs an AT user a state they
-// can still infer, whereas emitting it where it is illegal is a critical
-// aria-allowed-attr defect.
-function supportsAriaExpanded(el: HTMLElement): boolean {
- const explicit = el.getAttribute('role')?.trim().split(/\s+/)[0];
- if (explicit) {
- return EXPANDABLE_ROLES.has(explicit);
- }
- switch (el.tagName) {
- case 'BUTTON':
- case 'SUMMARY':
- return true;
- case 'A':
- case 'AREA':
- return el.hasAttribute('href');
- case 'INPUT':
- // The button-flavoured input types map to role="button"; every other
- // type maps to a textbox-family role, which does not take it.
- return BUTTON_INPUT_TYPES.has(
- (el as HTMLInputElement).type?.toLowerCase(),
- );
- case 'SELECT':
- // combobox when it is a single-line picker, listbox otherwise; both
- // support aria-expanded.
- return true;
- default:
- return false;
- }
-}
+import {
+ ROLELESS_TRIGGER,
+ applyPopupTriggerAttributes,
+ labelledTriggerAttributes,
+ popupTriggerSupport,
+} from './popupTrigger';
const styles = stylex.create({
wrapperContents: {
@@ -367,63 +313,32 @@ export function HoverCard({
hoverCard.ref(firstChild);
if (label) {
- // When named, the hover card is a dialog. The trigger should advertise the
- // popup relationship with aria-haspopup/aria-expanded, not describe the
- // trigger with the dialog's content (aria-describedby is for plain-text
- // descriptions, not navigable regions). See #5049.
- //
- // aria-expanded only goes on a trigger whose role permits it. A role-less
- // trigger (Timestamp's <time>/<span>) gets haspopup + controls, which are
- // global, and no expanded state.
- //
- // Merge rather than overwrite: the trigger may already carry its own
- // popup semantics (e.g. a menu button wrapped in a labelled HoverCard),
- // so preserve the existing values and restore them on cleanup.
- const existingHaspopup = firstChild.getAttribute('aria-haspopup');
- const existingControls = firstChild.getAttribute('aria-controls');
- const existingExpanded = firstChild.getAttribute('aria-expanded');
- const canExpand = supportsAriaExpanded(firstChild);
-
- firstChild.setAttribute('aria-haspopup', 'dialog');
- // Only point aria-controls at the layer while it is open and in the DOM.
- // While closed, useLayer leaves only an inert <template> marker, so the
- // id would reference nothing. DateInput gates it the same way. The
- // trigger's own aria-controls (if any) is preserved either way.
- if (hoverCard.isOpen) {
- firstChild.setAttribute(
- 'aria-controls',
- mergeIds(existingControls, hoverCard.id) ?? '',
- );
- } else if (existingControls) {
- firstChild.setAttribute('aria-controls', existingControls);
- } else {
- firstChild.removeAttribute('aria-controls');
- }
- if (canExpand) {
- firstChild.setAttribute('aria-expanded', String(hoverCard.isOpen));
- } else if (existingExpanded) {
- firstChild.setAttribute('aria-expanded', existingExpanded);
- } else {
- firstChild.removeAttribute('aria-expanded');
- }
+ // When named, the hover card is a dialog. The trigger names it through
+ // aria-controls, not aria-describedby, which is for plain-text
+ // descriptions, not navigable regions. The trigger's own popup
+ // attributes (e.g. a menu button's) come back on cleanup.
+ const own = {
+ haspopup: firstChild.getAttribute('aria-haspopup'),
+ controls: firstChild.getAttribute('aria-controls'),
+ expanded: firstChild.getAttribute('aria-expanded'),
+ };
+ applyPopupTriggerAttributes(
+ firstChild,
+ labelledTriggerAttributes(popupTriggerSupport(firstChild), own, {
+ id: hoverCard.id,
+ isOpen: hoverCard.isOpen,
+ }),
+ );
return () => {
hoverCard.ref(null);
- if (existingHaspopup) {
- firstChild.setAttribute('aria-haspopup', existingHaspopup);
- } else {
- firstChild.removeAttribute('aria-haspopup');
- }
- if (existingControls) {
- firstChild.setAttribute('aria-controls', existingControls);
- } else {
- firstChild.removeAttribute('aria-controls');
- }
- if (existingExpanded) {
- firstChild.setAttribute('aria-expanded', existingExpanded);
- } else {
- firstChild.removeAttribute('aria-expanded');
- }
+ applyPopupTriggerAttributes(
+ firstChild,
+ labelledTriggerAttributes(ROLELESS_TRIGGER, own, {
+ id: null,
+ isOpen: false,
+ }),
+ );
};
}
@@ -471,10 +386,15 @@ export function HoverCard({
<span
ref={hoverCard.ref}
tabIndex={0}
- aria-haspopup={label ? 'dialog' : undefined}
- aria-controls={label && hoverCard.isOpen ? hoverCard.id : undefined}
- // No aria-expanded: this wrapper is a role-less <span>, and
- // aria-expanded is invalid on it (see EXPANDABLE_ROLES above).
+ // The wrapper is a role-less <span>: when labelled, it names the
+ // open card through aria-controls only.
+ {...(label
+ ? labelledTriggerAttributes(
+ ROLELESS_TRIGGER,
+ {},
+ {id: hoverCard.id, isOpen: hoverCard.isOpen},
+ )
+ : null)}
aria-describedby={label ? undefined : hoverCard.describedBy}
// The span is a tab stop Astryx adds: it draws the shared ring,
// which a theme restyles through the focus-outline tokens.
diff --git a/packages/core/src/HoverCard/__tests__/HoverCardTriggerRoles.a11y.browser.spec.ts b/packages/core/src/HoverCard/__tests__/HoverCardTriggerRoles.a11y.browser.spec.ts
new file mode 100644
index 0000000000..83adbed476
--- /dev/null
+++ b/packages/core/src/HoverCard/__tests__/HoverCardTriggerRoles.a11y.browser.spec.ts
@@ -0,0 +1,53 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+// @pr-a11y scope core/HoverCard
+
+/**
+ * @file HoverCardTriggerRoles.a11y.browser.spec.ts
+ * @input Built Storybook, a labelled HoverCard open on a role-less text trigger
+ * @output Proof that the trigger names the card through aria-controls only and
+ * that the open card passes axe, in Chromium and WebKit
+ * @position Browser regression for the labelled trigger's popup attributes
+ */
+
+import AxeBuilder from '@axe-core/playwright';
+import {expect, test} from '@astryxdesign/a11y-spec/playwright';
+import {
+ DEFAULT_STORYBOOK_DIR,
+ serveStorybook,
+ type StaticServer,
+} from '@astryxdesign/a11y-spec/storybook';
+
+let storybook: StaticServer;
+test.beforeAll(async () => {
+ storybook = await serveStorybook(
+ process.env.ASTRYX_STORYBOOK_DIR ?? DEFAULT_STORYBOOK_DIR,
+ );
+});
+test.afterAll(async () => storybook?.close());
+
+test('a labelled card on a role-less trigger passes axe while open', async ({
+ page,
+}) => {
+ await page.goto(
+ `${storybook.origin}/iframe.html?id=core-hovercard--labelled-text-trigger&viewMode=story`,
+ );
+ const card = page.getByRole('dialog', {name: 'Jane Doe profile'});
+ await expect(card).toBeVisible();
+ const cardId = await card.getAttribute('id');
+ const trigger = page
+ .getByRole('paragraph')
+ .getByText('Jane Doe', {exact: true});
+ await expect(trigger).toHaveAttribute('aria-controls', cardId ?? '');
+ await expect(trigger).not.toHaveAttribute('aria-haspopup');
+ await expect(trigger).not.toHaveAttribute('aria-expanded');
+ // A story is a page fragment with no landmarks or heading.
+ const results = await new AxeBuilder({page})
+ .disableRules(['landmark-one-main', 'page-has-heading-one', 'region'])
+ .analyze();
+ expect(
+ results.violations.map(
+ violation =>
+ `${violation.id}: ${violation.nodes.map(node => node.target.join(' ')).join(', ')}`,
+ ),
+ ).toEqual([]);
+});
diff --git a/packages/core/src/HoverCard/popupTrigger.test.ts b/packages/core/src/HoverCard/popupTrigger.test.ts
new file mode 100644
index 0000000000..3cfa01cb17
--- /dev/null
+++ b/packages/core/src/HoverCard/popupTrigger.test.ts
@@ -0,0 +1,94 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file popupTrigger.test.ts
+ * @input popupTriggerSupport and labelledTriggerAttributes
+ * @output Which triggers take aria-haspopup and aria-expanded, and the
+ * attributes a labelled trigger gets
+ * @position Unit tests for the HoverCard trigger popup attributes
+ */
+
+import {describe, expect, it} from 'vitest';
+import {
+ ROLELESS_TRIGGER,
+ labelledTriggerAttributes,
+ popupTriggerSupport,
+} from './popupTrigger';
+
+function element(html: string): HTMLElement {
+ const host = document.createElement('div');
+ host.innerHTML = html;
+ return host.firstElementChild as HTMLElement;
+}
+
+describe('popupTriggerSupport', () => {
+ it.each([
+ ['<button>x</button>', true, true],
+ ['<a href="#x">x</a>', true, true],
+ ['<a>x</a>', false, false],
+ ['<input type="submit">', true, true],
+ ['<input type="text">', true, false],
+ ['<input type="checkbox">', false, false],
+ ['<textarea></textarea>', true, false],
+ ['<select></select>', true, true],
+ ['<select multiple></select>', false, true],
+ ['<summary>x</summary>', false, true],
+ ['<span>x</span>', false, false],
+ ['<time>x</time>', false, false],
+ ['<span role="button">x</span>', true, true],
+ ['<span role="checkbox">x</span>', false, true],
+ ['<span role="note">x</span>', false, false],
+ ])(
+ '%s takes aria-haspopup %s and aria-expanded %s',
+ (html, haspopup, expanded) => {
+ expect(popupTriggerSupport(element(html))).toEqual({haspopup, expanded});
+ },
+ );
+});
+
+describe('labelledTriggerAttributes', () => {
+ it('advertises the dialog on a supporting role, replacing its own value', () => {
+ expect(
+ labelledTriggerAttributes(
+ {haspopup: true, expanded: true},
+ {haspopup: 'menu', controls: 'menu-id', expanded: 'true'},
+ {id: 'card', isOpen: true},
+ ),
+ ).toEqual({
+ 'aria-haspopup': 'dialog',
+ 'aria-controls': 'menu-id card',
+ 'aria-expanded': 'true',
+ });
+ });
+
+ it('gives a role-less trigger only aria-controls, and only while open', () => {
+ expect(
+ labelledTriggerAttributes(
+ ROLELESS_TRIGGER,
+ {},
+ {id: 'card', isOpen: true},
+ ),
+ ).toEqual({'aria-controls': 'card'});
+ expect(
+ labelledTriggerAttributes(
+ ROLELESS_TRIGGER,
+ {},
+ {id: 'card', isOpen: false},
+ ),
+ ).toEqual({});
+ });
+
+ it("keeps a role-less trigger's own attributes", () => {
+ expect(
+ labelledTriggerAttributes(
+ ROLELESS_TRIGGER,
+ {haspopup: 'true', controls: 'own', expanded: 'false'},
+ {id: 'card', isOpen: false},
+ ),
+ ).toEqual({
+ 'aria-haspopup': 'true',
+ 'aria-controls': 'own',
+ 'aria-expanded': 'false',
+ });
+ });
+});
diff --git a/packages/core/src/HoverCard/popupTrigger.ts b/packages/core/src/HoverCard/popupTrigger.ts
new file mode 100644
index 0000000000..f051d3975a
--- /dev/null
+++ b/packages/core/src/HoverCard/popupTrigger.ts
@@ -0,0 +1,197 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file popupTrigger.ts
+ * @input A labelled hover card's trigger element or its known role support,
+ * the trigger's own popup attributes, and the card's id and open state
+ * @output The popup attributes a labelled trigger carries, and a reader of
+ * which of them the trigger's role supports
+ * @position Shared by HoverCard and Timestamp so that a labelled card's
+ * trigger gets one set of popup attributes
+ *
+ * SYNC: When modified, update these files to stay in sync:
+ * - /packages/core/src/HoverCard/HoverCard.tsx
+ * - /packages/core/src/Timestamp/Timestamp.tsx
+ * - /packages/core/src/HoverCard/popupTrigger.test.ts
+ */
+
+import type {AriaAttributes} from 'react';
+import {mergeIds} from './mergeIds';
+
+/** The popup states a trigger's role supports. */
+export interface PopupTriggerSupport {
+ readonly haspopup: boolean;
+ readonly expanded: boolean;
+}
+
+/** A role-less trigger, such as a `span` or a `time`, supports neither. */
+export const ROLELESS_TRIGGER: PopupTriggerSupport = {
+ haspopup: false,
+ expanded: false,
+};
+
+/** The popup attributes the trigger carries without the card. */
+export interface OwnPopupAttributes {
+ readonly haspopup?: string | null;
+ readonly controls?: string | null;
+ readonly expanded?: string | null;
+}
+
+/** A labelled trigger's popup attributes; a missing key means no attribute. */
+export interface PopupTriggerAttributes {
+ 'aria-haspopup'?: AriaAttributes['aria-haspopup'];
+ 'aria-controls'?: string;
+ 'aria-expanded'?: AriaAttributes['aria-expanded'];
+}
+
+// The ARIA 1.2 "Supported States and Properties" lists for each attribute,
+// with the subclass roles that inherit it. Both are the narrow reading: a
+// role outside a set is not always unsupported, but an attribute on a role
+// that does not support it can be ignored by assistive technology, while
+// dropping one costs a user only a state they can still infer. Widening a set
+// is safe. Chat/useTriggerMenu.tsx applies the same rule to aria-expanded.
+const HASPOPUP_ROLES = new Set([
+ 'application',
+ 'button',
+ 'combobox',
+ 'gridcell',
+ 'link',
+ 'menuitem',
+ 'menuitemcheckbox',
+ 'menuitemradio',
+ 'searchbox',
+ 'slider',
+ 'tab',
+ 'textbox',
+ 'treeitem',
+]);
+
+const EXPANDABLE_ROLES = new Set([
+ 'application',
+ 'button',
+ 'checkbox',
+ 'columnheader',
+ 'combobox',
+ 'gridcell',
+ 'link',
+ 'listbox',
+ 'menuitem',
+ 'menuitemcheckbox',
+ 'menuitemradio',
+ 'row',
+ 'rowheader',
+ 'switch',
+ 'tab',
+ 'treeitem',
+]);
+
+const BUTTON_INPUT_TYPES = new Set(['button', 'submit', 'reset', 'image']);
+
+// Input types whose implicit role is textbox, searchbox or combobox.
+const TEXT_INPUT_TYPES = new Set(['text', 'search', 'email', 'tel', 'url']);
+
+/**
+ * Which popup states `el`'s role supports. An element this does not list is
+ * read as role-less.
+ */
+export function popupTriggerSupport(el: HTMLElement): PopupTriggerSupport {
+ const explicit = el.getAttribute('role')?.trim().split(/\s+/)[0];
+ if (explicit) {
+ return {
+ haspopup: HASPOPUP_ROLES.has(explicit),
+ expanded: EXPANDABLE_ROLES.has(explicit),
+ };
+ }
+ switch (el.tagName) {
+ case 'BUTTON':
+ return {haspopup: true, expanded: true};
+ case 'SUMMARY':
+ // No implicit role takes aria-haspopup, but a disclosure summary
+ // supports aria-expanded.
+ return {haspopup: false, expanded: true};
+ case 'A':
+ case 'AREA':
+ // A link only with an href; otherwise the element is generic.
+ return el.hasAttribute('href')
+ ? {haspopup: true, expanded: true}
+ : ROLELESS_TRIGGER;
+ case 'INPUT': {
+ const type = (el as HTMLInputElement).type?.toLowerCase() ?? 'text';
+ if (BUTTON_INPUT_TYPES.has(type)) {
+ return {haspopup: true, expanded: true};
+ }
+ if (TEXT_INPUT_TYPES.has(type)) {
+ return {haspopup: true, expanded: false};
+ }
+ return ROLELESS_TRIGGER;
+ }
+ case 'TEXTAREA':
+ return {haspopup: true, expanded: false};
+ case 'SELECT':
+ // A single-line select is a combobox, which takes both. A multiple or
+ // tall select is a listbox, which takes aria-expanded only.
+ return {
+ haspopup:
+ !(el as HTMLSelectElement).multiple &&
+ (el as HTMLSelectElement).size <= 1,
+ expanded: true,
+ };
+ default:
+ return ROLELESS_TRIGGER;
+ }
+}
+
+/**
+ * The popup attributes of a labelled hover card's trigger. The trigger names
+ * the open card through `aria-controls`, after its own ids. It gets
+ * `aria-haspopup="dialog"` and `aria-expanded` only when its role supports
+ * them; otherwise it keeps its own values.
+ */
+export function labelledTriggerAttributes(
+ support: PopupTriggerSupport,
+ own: OwnPopupAttributes,
+ card: {readonly id: string | null; readonly isOpen: boolean},
+): PopupTriggerAttributes {
+ const attributes: PopupTriggerAttributes = {};
+ const haspopup = support.haspopup ? 'dialog' : own.haspopup;
+ if (haspopup != null && haspopup !== '') {
+ // A value read from the trigger is the caller's own, written as is.
+ attributes['aria-haspopup'] = haspopup as AriaAttributes['aria-haspopup'];
+ }
+ // The card's id goes in only while the card is open: while closed, the
+ // layer leaves only an inert marker, so the id would name nothing.
+ const controls =
+ card.isOpen && card.id != null
+ ? mergeIds(own.controls, card.id)
+ : own.controls;
+ if (controls != null && controls !== '') {
+ attributes['aria-controls'] = controls;
+ }
+ const expanded = support.expanded ? String(card.isOpen) : own.expanded;
+ if (expanded != null && expanded !== '') {
+ attributes['aria-expanded'] = expanded as AriaAttributes['aria-expanded'];
+ }
+ return attributes;
+}
+
+/**
+ * Writes `attributes` to `el`, and removes each popup attribute that
+ * `attributes` does not carry.
+ */
+export function applyPopupTriggerAttributes(
+ el: HTMLElement,
+ attributes: PopupTriggerAttributes,
+): void {
+ for (const name of [
+ 'aria-haspopup',
+ 'aria-controls',
+ 'aria-expanded',
+ ] as const) {
+ const value = attributes[name];
+ if (value == null) {
+ el.removeAttribute(name);
+ } else {
+ el.setAttribute(name, String(value));
+ }
+ }
+}
diff --git a/packages/core/src/HoverCard/useHoverCard.tsx b/packages/core/src/HoverCard/useHoverCard.tsx
index a5e4acfe8f..bc611d5275 100644
--- a/packages/core/src/HoverCard/useHoverCard.tsx
+++ b/packages/core/src/HoverCard/useHoverCard.tsx
@@ -209,9 +209,9 @@ export interface HoverCardReturn {
/**
* Whether the hover card is currently open.
* Useful for driving `aria-expanded` on the trigger — but only when the
- * trigger's role permits it (`button`, `link`, `combobox`, …). On a role-less
- * trigger `aria-expanded` is invalid; use `aria-haspopup`/`aria-controls`
- * alone there.
+ * trigger's role permits it (`button`, `link`, `combobox`, …). A role-less
+ * trigger supports neither `aria-expanded` nor `aria-haspopup`; name the
+ * open card through `aria-controls` alone there.
*/
isOpen: boolean;
diff --git a/packages/core/src/Timestamp/Timestamp.tsx b/packages/core/src/Timestamp/Timestamp.tsx
index 97aea75582..968bcb33d2 100644
--- a/packages/core/src/Timestamp/Timestamp.tsx
+++ b/packages/core/src/Timestamp/Timestamp.tsx
@@ -35,7 +35,10 @@ import {useLocale} from '../i18n/useLocale';
import {useCalendarSystem} from '../i18n/useCalendarSystem';
import type {BaseProps} from '../BaseProps';
import {themeProps} from '../utils/themeProps';
-import {mergeIds} from '../HoverCard/mergeIds';
+import {
+ ROLELESS_TRIGGER,
+ labelledTriggerAttributes,
+} from '../HoverCard/popupTrigger';
import {formatInstant, formatZoneName} from './formatInstant';
import {formatRelativeTime} from './formatRelativeTime';
import {formatTooltipLines, resolveTimezoneID} from './tooltipEntries';
@@ -493,11 +496,15 @@ export function Timestamp({
// A bare <time> cannot take focus. Add the tab stop only while a card
// is attached, so keyboard users can open it. A caller's tabIndex wins.
{...(showTooltip && rest.tabIndex == null ? {tabIndex: 0} : {})}
- // The time names the open card; a caller's own ids stay first. The time
- // role supports neither aria-haspopup nor aria-expanded.
- {...(showTooltip && openCardId != null
- ? {'aria-controls': mergeIds(rest['aria-controls'], openCardId)}
- : {})}>
+ // The time names the open card after a caller's own ids. The time role
+ // supports neither aria-haspopup nor aria-expanded.
+ {...(showTooltip
+ ? labelledTriggerAttributes(
+ ROLELESS_TRIGGER,
+ {controls: rest['aria-controls']},
+ {id: openCardId, isOpen: openCardId != null},
+ )
+ : null)}>
{displayText}
</time>
);