An open source design system that's fully customizable and agent ready
TypeScript
fix(HoverCard): text written around an expression gets the focusable trigger and hover cue (#9603)
Cindy Zhangba6401064874
diff --git a/.changeset/hovercard-mixed-text.md b/.changeset/hovercard-mixed-text.mdnew file mode 100644index 0000000000..8d3d76cdd4--- /dev/null+++ b/.changeset/hovercard-mixed-text.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[fix] A `HoverCard` whose trigger is text written around an expression, such as `Edited {when}`, now wraps that text in its focusable trigger, so hover and keyboard focus open the card, the trigger carries its popup attributes or description, and it shows the same hover cue as a plain text trigger. Before, such text had no trigger at all.++@cixzhang @duytbpdiff --git a/docs/specs/components/HoverCard/HoverCard.spec.md b/docs/specs/components/HoverCard/HoverCard.spec.mdindex b74cb630f0..53b1e33e81 100644--- a/docs/specs/components/HoverCard/HoverCard.spec.md+++ b/docs/specs/components/HoverCard/HoverCard.spec.md@@ -45,7 +45,7 @@ system_specs: [spec:AST-003, spec:AST-017]| 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`. Five implementation gaps (see Current-state impact). |+| Compatibility/readiness | No public API change: `touchTrigger` keeps its released values and its default `auto`. Four 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`. |@@ -63,7 +63,10 @@ Consumer usage lives in `HoverCard.doc.mjs`.- Released default preserved: yes. `touchTrigger` keeps its released valuesand its default `auto`. A disabled control is not an action, so its reasonopens on a tap (FR5); that restoration ships on its own as a patch `[fix]`-- Compatibility class: no public prop, default, DOM, or styling change+- Compatibility class: no public prop, default, or styling change. Text+ written around an expression, such as `Edited {when}`, now renders the+ focusable trigger span with the text hover cue, as a single string does; this+ ships as a patch `[fix]`- Controlled/uncontrolled behavior: uncontrolled by default; `isOpen` forces thestate, and a controlled card reports close requests through`onOpenChange(false)` without closing itself (FR7)@@ -91,10 +94,6 @@ Consumer migration instructions belong in consumer docs and release notes.focus, and a hover-opened card the user has tabbed into closes when thepointer leaves the trigger, dropping focus to the page. WCAG 1.4.13 requirescontent shown on focus to persist until focus moves or the user dismisses it.-- **Mixed text children get no trigger.** Text children that reach React as- several strings, such as `Edited {when}`, have no element to attach to: no- focusable span or popup attributes are added, and hover and focus never open- the card (FR2).## Ownership boundary@@ -125,13 +124,13 @@ Consumer migration instructions belong in consumer docs and release notes.| ID | Invariant | Basis || ---- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------ || 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: a single string or number child is wrapped in a 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 |+| 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 || 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, a completed tap opens the card per `touchTrigger` when the finger lifts; 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 own content keeps it open; a second tap on the trigger, 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 || FR7 | `isOpen` forces the card shown or hidden, and `isOpen={true}` suppresses hover and focus hiding; a controlled card answers Escape by calling `onOpenChange(false)` without hiding, and setting `isOpen={false}` while focus is inside the card returns focus to the trigger. `isDefaultOpen` opens it on mount, still dismissible. Implementation gap: with `isOpen={false}`, focus on the trigger still opens the card, and Escape then only reports `onOpenChange(false)` (Current-state impact). `isEnabled={false}` disables the triggers. `onOpenChange` reports each show and hide. | Current source and tests |-| FR8 | Content renders only while open; server markup and the first client render match, including a default-open card. `hasHoverIndication` (`auto`: a single string or number child) adds a hover cue to the inline trigger. | Current source and tests |+| FR8 | Content renders only while open; server markup and the first client render match, including a default-open card. `hasHoverIndication` (`auto`: text children: strings and numbers, with holes such as `false` and `null` ignored) adds a hover cue to the inline trigger. | Current source and tests || FR11 | A press inside an open HoverCard surface acts only within that surface: it never activates the trigger, a clickable container around it, or the control a label names. Interactive content inside the card (a link, a button) keeps its own activation. The press still reaches page-level listeners, so a menu or Typeahead inside the surface keeps working. `architecture:layer-runtime` INV17 states this stop for every layer root. | `component:Tooltip` FR11; `architecture:layer-runtime` INV17 |### Allowed variation@@ -210,7 +209,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, 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` |+| 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` || 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` |@@ -221,12 +220,11 @@ Read from source, with no focused test yet:- FR3: restoring the trigger's own attributes on unmount.- FR7: `isOpen={true}` keeping the card open when focus leaves the trigger.-- FR8: `hasHoverIndication={true}` and `{false}`.+- FR8: `hasHoverIndication={true}`.Checked only in a browser, with no unit test:- FR1: the card's padding.-- FR8: the default `hasHoverIndication` cue on a text trigger.## Decision logdiff --git a/packages/core/src/HoverCard/HoverCard.doc.mjs b/packages/core/src/HoverCard/HoverCard.doc.mjsindex 0a1da40e16..a7c44690eb 100644--- a/packages/core/src/HoverCard/HoverCard.doc.mjs+++ b/packages/core/src/HoverCard/HoverCard.doc.mjs@@ -54,7 +54,7 @@ export const docs = {name: 'children',type: 'ReactNode',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.',+ 'The trigger. Text children, a string or number or text written around an expression such as `Edited {when}`, are wrapped in a focusable inline span; holes such as `false` and `null` are ignored. With element children, HoverCard wires the first element, so that element does not need to accept a ref.',},{name: 'content',@@ -131,7 +131,7 @@ export const docs = {name: 'hasHoverIndication',type: "'auto' | boolean",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.',+ 'Shows a dashed underline on a text trigger. auto shows it when children is text: strings and numbers, such as `Edited {when}`, with holes such as `false` and `null` ignored. It has no effect on an element trigger, which keeps its own styling.',default: "'auto'",},{@@ -267,7 +267,7 @@ export const docsZh = {name: 'children',type: 'ReactNode',description:- '触发元素。单个字符串或数字会被包裹在可聚焦的内联 span 中。分成多段到达的文本(例如 `Edited {when}`)不会得到触发器,请传入单个字符串(例如模板字符串)或用可聚焦元素包裹。传入元素时,HoverCard 连接第一个元素,因此该元素无需接受 ref。',+ '触发元素。文本子元素(字符串或数字,或围绕表达式书写的文本,例如 `Edited {when}`)会被包裹在可聚焦的内联 span 中;`false`、`null` 等空位会被忽略。传入元素时,HoverCard 连接第一个元素,因此该元素无需接受 ref。',},{name: 'content',@@ -337,7 +337,7 @@ export const docsZh = {name: 'hasHoverIndication',type: "'auto' | boolean",description:- '在文本触发元素上显示虚线下划线。auto:当 children 是单个字符串或数字时显示。对元素触发器无效,元素保留自身样式。',+ '在文本触发元素上显示虚线下划线。auto:当 children 是文本(字符串和数字,例如 `Edited {when}`,忽略 `false`、`null` 等空位)时显示。对元素触发器无效,元素保留自身样式。',default: "'auto'",},{@@ -476,7 +476,7 @@ export const docsDense = {'Component wrapper for hover card overlay; richer overlay triggered on hover/focus.',propDescriptions: {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).',+ 'Trigger. Text children (strings/numbers, incl. `Edited {when}`; holes like false/null ignored) are wrapped in a focusable inline span. 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).",@@ -493,7 +493,7 @@ export const docsDense = {onOpenChange:'Callback when visibility changes; true=shown, false=hidden.',hasHoverIndication:- 'Dashed underline on a text trigger. auto = single string/number children; no effect on element triggers.',+ 'Dashed underline on a text trigger. auto = text children (strings/numbers, holes ignored); 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.',diff --git a/packages/core/src/HoverCard/HoverCard.test.tsx b/packages/core/src/HoverCard/HoverCard.test.tsxindex ce170dd69c..f0d0cea97d 100644--- a/packages/core/src/HoverCard/HoverCard.test.tsx+++ b/packages/core/src/HoverCard/HoverCard.test.tsx@@ -859,6 +859,91 @@ describe('HoverCard', () => {});});+ describe('text written around an expression', () => {+ it('wraps several text children in one focusable trigger', async () => {+ const when = '2 hours ago';+ const onOpenChange = vi.fn();+ render(+ <HoverCard+ content={<span>Edited by Kai</span>}+ onOpenChange={onOpenChange}+ delay={0}>+ Edited {when}+ </HoverCard>,+ );+ const trigger = screen.getByText('Edited 2 hours ago');+ expect(trigger.tagName).toBe('SPAN');+ expect(trigger).toHaveAttribute('tabindex', '0');+ expect(trigger).toHaveAttribute('aria-describedby');+ fireEvent.mouseEnter(trigger);+ await waitFor(() => expect(onOpenChange).toHaveBeenLastCalledWith(true));+ });++ it('ignores holes that render nothing', () => {+ const isDraft = false;+ render(+ <HoverCard label="History" content={<span>Card</span>}>+ Edited {isDraft && 'draft'} {null}today+ </HoverCard>,+ );+ expect(screen.getByText(/Edited/)).toHaveAttribute(+ 'aria-haspopup',+ 'dialog',+ );+ });++ // The auto hover cue (FR8) is a class on the text trigger; a single+ // string's trigger is the reference.+ function cueClassOf(+ children: ComponentProps<typeof HoverCard>['children'],+ ) {+ const {unmount} = render(+ <HoverCard content={<span>Card</span>}>{children}</HoverCard>,+ );+ const className = (+ document.querySelector('span[tabindex="0"]') as HTMLElement+ ).className;+ unmount();+ return className;+ }++ it('gives several text children the same hover cue as one string', () => {+ const when = 'today';+ const single = cueClassOf('Edited today');+ // JSX passes `Edited {when}` as this array.+ expect(cueClassOf(['Edited ', when])).toBe(single);+ const {unmount} = render(+ <HoverCard content={<span>Card</span>} hasHoverIndication={false}>+ Edited today+ </HoverCard>,+ );+ expect(+ (document.querySelector('span[tabindex="0"]') as HTMLElement).className,+ ).not.toBe(single);+ unmount();+ });++ it('keeps the hover cue when holes render nothing', () => {+ const isDraft = false;+ const single = cueClassOf('Edited today');+ expect(cueClassOf(['Edited ', isDraft && 'draft', null, 'today'])).toBe(+ single,+ );+ });++ it('still attaches to the first element when one is present', () => {+ render(+ <HoverCard label="History" content={<span>Card</span>}>+ Edited <time dateTime="2026-11-02">today</time>+ </HoverCard>,+ );+ expect(screen.getByText('today')).toHaveAttribute(+ 'aria-haspopup',+ 'dialog',+ );+ });+ });+describe('a replaced trigger element', () => {function SwapsItsRoot() {const [isLink, setIsLink] = useState(false);diff --git a/packages/core/src/HoverCard/HoverCard.tsx b/packages/core/src/HoverCard/HoverCard.tsxindex 8737fd18f4..82565dc56e 100644--- a/packages/core/src/HoverCard/HoverCard.tsx+++ b/packages/core/src/HoverCard/HoverCard.tsx@@ -23,6 +23,7 @@ import {type ReactElement,type ReactNode,} from 'react';+import {isRenderable} from '../utils/isRenderable';import {observeMutations} from '../utils/sharedMutationObserver';import {useIsomorphicLayoutEffect} from '../hooks/useIsomorphicLayoutEffect';import * as stylex from '@stylexjs/stylex';@@ -201,7 +202,8 @@ export interface HoverCardProps extends Pick</*** 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+ * - `'auto'`: Show when children is text: strings and numbers, such as+ * `Edited {when}`, with holes such as `false` and `null` ignored* - `true`: Show on a text trigger* - `false`: Never show*@@ -235,7 +237,26 @@ export interface HoverCardProps extends Pick<* Check if children are text-only (no React elements)*/function isTextOnly(children: ReactNode): boolean {- return typeof children === 'string' || typeof children === 'number';+ if (typeof children === 'string' || typeof children === 'number') {+ return true;+ }+ // Text written around an expression, such as `Edited {when}`, reaches React+ // as several strings. Holes that render nothing do not change that; one+ // element does.+ if (!Array.isArray(children)) {+ return false;+ }+ let hasText = false;+ for (const child of children.flat(Infinity) as ReactNode[]) {+ if (!isRenderable(child)) {+ continue;+ }+ if (typeof child !== 'string' && typeof child !== 'number') {+ return false;+ }+ hasText = true;+ }+ return hasText;}/**