An open source design system that's fully customizable and agent ready
TypeScript
fix(HoverCard): a replaced trigger element is wired in place of the old one (#9593)
Cindy Zhangae97fa8fc037
diff --git a/.changeset/hovercard-replaced-trigger.md b/.changeset/hovercard-replaced-trigger.mdnew file mode 100644index 0000000000..023d6160a0--- /dev/null+++ b/.changeset/hovercard-replaced-trigger.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[fix] When a `HoverCard`'s trigger element is replaced after mount, by new children or by a child component that swaps its own root element, the new element now gets the card's popup attributes or description and opens the card on hover and focus. Before, it stayed unwired until the card next opened or closed or its `label` changed.++@cixzhang @duytbpdiff --git a/docs/specs/components/HoverCard/HoverCard.spec.md b/docs/specs/components/HoverCard/HoverCard.spec.mdindex 91f115cf5a..7fef60ad33 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`. Seven implementation gaps (see Current-state impact). |+| Compatibility/readiness | No public API change: `touchTrigger` keeps its released values and its default `auto`. Six 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`. |@@ -88,11 +88,6 @@ Consumer migration instructions belong in consumer docs and release notes.`auto` does not recognize, such as a `<summary>` or an SVG link, never openson focus. `architecture:interaction-modality` INV4 keeps hover from being theonly discovery path.-- **A replaced trigger loses its wiring.** The card wires its trigger element- when it opens or closes, when `label` changes, or when its listeners- re-attach. A trigger element replaced after mount gets no popup attributes,- description, or hover and focus opening until one of those happens (FR2,- FR3).- **Escape cannot close a card in another document.** HoverCard listens forEscape only in the page's document, so a card rendered into an iframe or aPicture-in-Picture window with no layer beneath it is never closed by@@ -137,7 +132,7 @@ 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. | 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 || 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). Implementation gap: under `auto` the tab order is read only when the trigger's listeners attach, on mount and on a re-render that re-attaches them, so a trigger rendered with `tabindex="-1"` does not open on focus until such a re-render follows its move into the tab order (Current-state impact). | 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 |@@ -220,14 +215,14 @@ Consumer migration instructions belong in consumer docs and release notes.## Verification map-| Contract | Verification | Representative states | Mutation or failure expectation | Audit section |-| ------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------- |-| FR1, FR2, FR8 | `HoverCard.test.tsx` render, wrapper, portal, theme font, SSR, 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; `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. | — |-| Theming anatomy map | `scripts/check-knowledge.mjs` | Consumer anatomy and current target | Missing, extra, or stale mappings fail validation. | `audit:HoverCard/theming` |+| 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` |+| 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; `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. | — |+| Theming anatomy map | `scripts/check-knowledge.mjs` | Consumer anatomy and current target | Missing, extra, or stale mappings fail validation. | `audit:HoverCard/theming` |Read from source, with no focused test yet:diff --git a/packages/core/src/HoverCard/HoverCard.test.tsx b/packages/core/src/HoverCard/HoverCard.test.tsxindex a49e365b08..0d74fd06d1 100644--- a/packages/core/src/HoverCard/HoverCard.test.tsx+++ b/packages/core/src/HoverCard/HoverCard.test.tsx@@ -29,7 +29,7 @@ import {} from '@testing-library/react';import {renderToString} from 'react-dom/server';import {hydrateRoot} from 'react-dom/client';-import {StrictMode, type ComponentProps} from 'react';+import {StrictMode, useState, type ComponentProps} from 'react';import * as stylex from '@stylexjs/stylex';import {Button} from '../Button/Button';import {ClickableCard} from '../ClickableCard/ClickableCard';@@ -747,6 +747,111 @@ describe('HoverCard', () => {});});+ describe('a replaced trigger element', () => {+ function SwapsItsRoot() {+ const [isLink, setIsLink] = useState(false);+ return isLink ? (+ <a href="#profile">Profile link</a>+ ) : (+ <button type="button" onClick={() => setIsLink(true)}>+ Profile button+ </button>+ );+ }++ it('wires the new element when the children change', async () => {+ const onOpenChange = vi.fn();+ const {rerender} = render(+ <HoverCard+ label="Profile"+ content={<span>Card</span>}+ onOpenChange={onOpenChange}+ delay={0}>+ <button type="button">First</button>+ </HoverCard>,+ );+ rerender(+ <HoverCard+ label="Profile"+ content={<span>Card</span>}+ onOpenChange={onOpenChange}+ delay={0}>+ <a href="#second">Second</a>+ </HoverCard>,+ );+ const second = screen.getByRole('link', {name: 'Second'});+ await waitFor(() =>+ expect(second).toHaveAttribute('aria-haspopup', 'dialog'),+ );+ fireEvent.mouseEnter(second);+ await waitFor(() => expect(onOpenChange).toHaveBeenLastCalledWith(true));+ });++ it('wires the new element when a child component swaps its own root', async () => {+ const onOpenChange = vi.fn();+ render(+ <HoverCard+ label="Profile"+ content={<span>Card</span>}+ onOpenChange={onOpenChange}+ delay={0}>+ <SwapsItsRoot />+ </HoverCard>,+ );+ fireEvent.click(screen.getByRole('button', {name: 'Profile button'}));+ const link = screen.getByRole('link', {name: 'Profile link'});+ await waitFor(() =>+ expect(link).toHaveAttribute('aria-haspopup', 'dialog'),+ );+ fireEvent.mouseEnter(link);+ await waitFor(() => expect(onOpenChange).toHaveBeenLastCalledWith(true));+ });++ it('releases the old element when the children are reordered', async () => {+ const first = (+ <button key="a" type="button">+ Alpha+ </button>+ );+ const second = (+ <button key="b" type="button">+ Beta+ </button>+ );+ const {rerender} = render(+ <HoverCard label="Profile" content={<span>Card</span>}>+ {[first, second]}+ </HoverCard>,+ );+ const alpha = screen.getByRole('button', {name: 'Alpha'});+ expect(alpha).toHaveAttribute('aria-haspopup', 'dialog');++ rerender(+ <HoverCard label="Profile" content={<span>Card</span>}>+ {[second, first]}+ </HoverCard>,+ );+ const beta = screen.getByRole('button', {name: 'Beta'});+ await waitFor(() =>+ expect(beta).toHaveAttribute('aria-haspopup', 'dialog'),+ );+ // The old element stays in the DOM, released.+ expect(alpha).toBeInTheDocument();+ expect(alpha).not.toHaveAttribute('aria-haspopup');+ });++ it('describes the new element of an unnamed card', async () => {+ render(+ <HoverCard content={<span>Card</span>} delay={0}>+ <SwapsItsRoot />+ </HoverCard>,+ );+ fireEvent.click(screen.getByRole('button', {name: 'Profile button'}));+ const link = screen.getByRole('link', {name: 'Profile link'});+ await waitFor(() => expect(link).toHaveAttribute('aria-describedby'));+ });+ });+describe('Escape key behavior', () => {it('hides hover card when Escape is pressed on trigger', async () => {const onOpenChange = vi.fn();diff --git a/packages/core/src/HoverCard/HoverCard.tsx b/packages/core/src/HoverCard/HoverCard.tsxindex 93a67b5af8..c99250ecfd 100644--- a/packages/core/src/HoverCard/HoverCard.tsx+++ b/packages/core/src/HoverCard/HoverCard.tsx@@ -16,7 +16,14 @@* - /packages/cli/assets/templates/blocks/components/HoverCard/ (showcase blocks)*/-import {useCallback, useRef, type ReactElement, type ReactNode} from 'react';+import {+ useCallback,+ useRef,+ useState,+ type ReactElement,+ type ReactNode,+} from 'react';+import {observeMutations} from '../utils/sharedMutationObserver';import {useIsomorphicLayoutEffect} from '../hooks/useIsomorphicLayoutEffect';import * as stylex from '@stylexjs/stylex';import {@@ -303,6 +310,28 @@ export function HoverCard({onHide: handleHide,});+ // The wrapper's first element is the trigger, and it can be replaced after+ // mount: by new children, or by a child component that swaps its own root+ // without a render here. Syncs with the DOM: on a replacement the wiring+ // below re-runs, so the old element is released before the new one is wired.+ const [triggerReplacements, setTriggerReplacements] = useState(0);+ const observedTriggerRef = useRef<Element | null>(null);+ useIsomorphicLayoutEffect(() => {+ const wrapper = wrapperRef.current;+ if (textOnly || wrapper == null) {+ return;+ }+ observedTriggerRef.current = wrapper.firstElementChild;+ return observeMutations(wrapper, {childList: true}, () => {+ const trigger = wrapper.firstElementChild;+ if (trigger === observedTriggerRef.current) {+ return;+ }+ observedTriggerRef.current = trigger;+ setTriggerReplacements(count => count + 1);+ });+ }, [textOnly]);+// For element children with display:contents, attach ref to first childuseIsomorphicLayoutEffect(() => {if (textOnly) {@@ -407,6 +436,7 @@ export function HoverCard({hoverCard.id,hoverCard.isOpen,hoverCard.describedBy,+ triggerReplacements,]);// While closed, useLayer leaves only an inert <template> marker at this JSX