Skip to content

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

TypeScript

fix(HoverCard): Escape and focus work in the card's own document, such as an iframe (#9592)

Cindy Zhangb01b7ee1c359
diff --git a/.changeset/hovercard-second-document.md b/.changeset/hovercard-second-document.md
new file mode 100644
index 0000000000..c8be5013b5
--- /dev/null
+++ b/.changeset/hovercard-second-document.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[fix] A `HoverCard` rendered into another document, such as an iframe or a Picture-in-Picture window, now closes when Escape is pressed there, and Escape from inside the card returns focus to its trigger. Moving focus from the trigger into such a card also keeps it open. Before, the card read only the page's document, so Escape in the other document never closed it. The card now also ranks on the shared dismissal stack by its trigger's place, so a card whose trigger sits inside a focus-trap container takes Escape before that container, as the topmost layer.
+
+@cixzhang @duytbp
diff --git a/apps/storybook/stories/HoverCardSecondDocumentA11y.stories.tsx b/apps/storybook/stories/HoverCardSecondDocumentA11y.stories.tsx
new file mode 100644
index 0000000000..818b1bcffc
--- /dev/null
+++ b/apps/storybook/stories/HoverCardSecondDocumentA11y.stories.tsx
@@ -0,0 +1,117 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file HoverCardSecondDocumentA11y.stories.tsx
+ * @input HoverCard portalled into a same-origin iframe and into a Document
+ * Picture-in-Picture window
+ * @output A fixture for the Chromium check that Escape and focus work in the
+ * card's own document; excluded from the visual matrix
+ * @position Browser fixture for component:HoverCard FR6 in a second document
+ */
+
+import {useCallback, useState, type SyntheticEvent} from 'react';
+import {createPortal} from 'react-dom';
+import type {Meta, StoryObj} from '@storybook/react';
+import {Button} from '@astryxdesign/core/Button';
+import {HoverCard} from '@astryxdesign/core/HoverCard';
+
+const meta: Meta = {
+ title: 'a11y/HoverCard in a second document',
+ tags: ['no-visual'],
+};
+
+export default meta;
+
+const FRAME_DOCUMENT = '<!doctype html><html><head></head><body></body></html>';
+
+/** Copy the page's style sheets into the frame, as an app does. */
+function adoptPageStyles(target: Document) {
+ for (const sheet of Array.from(document.styleSheets)) {
+ if (
+ sheet.href != null &&
+ new URL(sheet.href).origin !== window.location.origin
+ ) {
+ continue;
+ }
+ const style = target.createElement('style');
+ style.textContent = Array.from(sheet.cssRules, rule => rule.cssText).join(
+ '\n',
+ );
+ target.head.append(style);
+ }
+}
+
+function Card() {
+ return (
+ <HoverCard
+ label="Profile"
+ content={<Button label="Message" />}
+ delay={0}
+ hideDelay={0}>
+ <Button label="Rowan" />
+ </HoverCard>
+ );
+}
+
+interface DocumentPictureInPicture {
+ requestWindow(options?: {width?: number; height?: number}): Promise<Window>;
+}
+
+/** The card again, portalled into a Document Picture-in-Picture window. */
+function PictureInPictureCard() {
+ const [body, setBody] = useState<HTMLElement | null>(null);
+ const pictureInPicture = (
+ window as Window & {documentPictureInPicture?: DocumentPictureInPicture}
+ ).documentPictureInPicture;
+ const popOut = useCallback(async () => {
+ if (pictureInPicture == null) {
+ return;
+ }
+ // Opening the window needs the user gesture of this click.
+ const pipWindow = await pictureInPicture.requestWindow({
+ width: 420,
+ height: 260,
+ });
+ adoptPageStyles(pipWindow.document);
+ pipWindow.addEventListener('pagehide', () => setBody(null));
+ setBody(pipWindow.document.body);
+ }, [pictureInPicture]);
+ return (
+ <>
+ <Button
+ label="Pop out"
+ isDisabled={pictureInPicture == null}
+ onClick={popOut}
+ />
+ {body != null && createPortal(<Card />, body)}
+ </>
+ );
+}
+
+export const SecondDocument: StoryObj = {
+ render: function SecondDocumentStory() {
+ const [body, setBody] = useState<HTMLElement | null>(null);
+ const handleLoad = useCallback(
+ (event: SyntheticEvent<HTMLIFrameElement>) => {
+ const frameDocument = event.currentTarget.contentDocument;
+ if (frameDocument != null) {
+ adoptPageStyles(frameDocument);
+ setBody(frameDocument.body);
+ }
+ },
+ [],
+ );
+ return (
+ <>
+ <iframe
+ title="Second document"
+ srcDoc={FRAME_DOCUMENT}
+ onLoad={handleLoad}
+ style={{width: 420, height: 260, border: '1px solid'}}
+ />
+ {body != null && createPortal(<Card />, body)}
+ <PictureInPictureCard />
+ </>
+ );
+ },
+};
diff --git a/docs/families/overlay-dismissal.md b/docs/families/overlay-dismissal.md
index acc9c375f3..43189d9b24 100644
--- a/docs/families/overlay-dismissal.md
+++ b/docs/families/overlay-dismissal.md
@@ -283,15 +283,15 @@ this record's current membership snapshot must be updated with it.
## Adoption and exceptions
-| Components or surface | Adoption | Current deviation or limitation |
-| -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
-| Dialog, AlertDialog, Popover, MobileNav, Drawer, CommandPalette | shared owner; CommandPalette composes Dialog | none |
-| Tooltip, HoverCard | shared owner with DOM presence reporting | Neither provides nesting depth to descendant layers. Implementation gap: a Tooltip consumes Escape when it is the topmost layer, so the layer beneath it stays open for that press, and a Tooltip in another document is never closed by Escape (`component:Tooltip` FR6); FR8 gives that press to the layer beneath and closes a lone Tooltip in its own document. A Tooltip that a press pinned open through `useTooltip`'s `show()`, as a press on InfoTip does, takes Escape first (`spec:AST-003` FR4, DEC-6; `component:Tooltip` FR9, FR12); a HoverCard has no press pin. HoverCard reads its presence from the page's document, so in another document it takes no request (FR8) and returns no focus there (FR9) |
-| Focus traps with `onEscape` | shared owner through `useFocusTrap` | They provide DOM containment, not descendant depth |
-| BreadcrumbItem, ChatComposerInput, ComplexSelector, DateInput, DateRangeInput, DateTimeInput, Selector, MultiSelector, PowerSearch, BaseTypeahead, Typeahead, Tokenizer, SideNavHeading, SideNavItem, TabMenu, TopNavHeading, TopNavMenu, TopNavMegaMenu, Table, Lab TourStep, Lab ChatEmojiPicker | shared owner through `usePopover` or a composed Popover owner | Table filtering owns controlled Popover state and discards its draft on close; TourStep routes Popover close to the Tour; ChatEmojiPicker owns controlled Popover state |
-| DropdownMenu root, MoreMenu, ContextMenu, Selector, MultiSelector, TopNavHeading, TopNavMenu, TopNavMegaMenu, SideNavHeading, SideNavItem, BottomSheet, BottomSheetSwitcher, Lightbox | shared owner | Implementation gap: in another document (for BottomSheet, BottomSheetSwitcher and Lightbox, a Picture-in-Picture window), each decides focus return from the page's document and last input, so focus returns to the frame element or the page, or without the ring the last input in its document calls for (FR9) |
-| List's reorder-mode hint | shared owner, registered while reorder mode is on | none |
-| DropdownMenuSubMenu, PowerSearchEditPopover | local only | Must migrate from component-specific listeners or registries to the shared owner |
+| Components or surface | Adoption | Current deviation or limitation |
+| -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| Dialog, AlertDialog, Popover, MobileNav, Drawer, CommandPalette | shared owner; CommandPalette composes Dialog | none |
+| Tooltip, HoverCard | shared owner with DOM presence reporting | Neither provides nesting depth to descendant layers. Implementation gap: a Tooltip consumes Escape when it is the topmost layer, so the layer beneath it stays open for that press, and a Tooltip in another document is never closed by Escape (`component:Tooltip` FR6); FR8 gives that press to the layer beneath and closes a lone Tooltip in its own document. A Tooltip that a press pinned open through `useTooltip`'s `show()`, as a press on InfoTip does, takes Escape first (`spec:AST-003` FR4, DEC-6; `component:Tooltip` FR9, FR12); a HoverCard has no press pin. |
+| Focus traps with `onEscape` | shared owner through `useFocusTrap` | They provide DOM containment, not descendant depth |
+| BreadcrumbItem, ChatComposerInput, ComplexSelector, DateInput, DateRangeInput, DateTimeInput, Selector, MultiSelector, PowerSearch, BaseTypeahead, Typeahead, Tokenizer, SideNavHeading, SideNavItem, TabMenu, TopNavHeading, TopNavMenu, TopNavMegaMenu, Table, Lab TourStep, Lab ChatEmojiPicker | shared owner through `usePopover` or a composed Popover owner | Table filtering owns controlled Popover state and discards its draft on close; TourStep routes Popover close to the Tour; ChatEmojiPicker owns controlled Popover state |
+| DropdownMenu root, MoreMenu, ContextMenu, Selector, MultiSelector, TopNavHeading, TopNavMenu, TopNavMegaMenu, SideNavHeading, SideNavItem, BottomSheet, BottomSheetSwitcher, Lightbox | shared owner | Implementation gap: in another document (for BottomSheet, BottomSheetSwitcher and Lightbox, a Picture-in-Picture window), each decides focus return from the page's document and last input, so focus returns to the frame element or the page, or without the ring the last input in its document calls for (FR9) |
+| List's reorder-mode hint | shared owner, registered while reorder mode is on | none |
+| DropdownMenuSubMenu, PowerSearchEditPopover | local only | Must migrate from component-specific listeners or registries to the shared owner |
The rows marked partial or local are current adoption gaps against FR1, and the
rows naming an implementation gap are gaps against FR8 or FR9. They are not
@@ -313,7 +313,7 @@ modality, positioning, outside-dismissal, and open-state contracts.
| FR8 | `PopoverSecondDocument.a11y.chromium.spec.ts` | a Popover in an iframe and in a Picture-in-Picture window, alone and with one open in the page | A press in the second document misses its own layer or dismisses the page's |
| FR9 | `DialogSecondDocument.a11y.browser.spec.ts` | a Dialog in an iframe and in a Picture-in-Picture window, closed by Escape or a control inside it, and a Dialog in an iframe opened from the page | Focus lands outside the opener's document, or its ring does not follow the closing input |
| FR9 | `BottomSheetCloseScroll.a11y.browser.spec.ts`; `DialogCloseScroll.a11y.browser.spec.ts` | a BottomSheet and a Dialog whose trigger sits in a tall focusable region of a scrolled page, closed by a control inside, by the backdrop, and by Escape, in Chromium and WebKit | The page's scroll offset or the trigger's place on screen changes across the close |
-| FR8, FR9 | Real-browser second-document checks; implementation gap: only Dialog and Popover have them | Dialog, Popover, DropdownMenu, MoreMenu, ContextMenu, Selector, MultiSelector, TopNavHeading, TopNavMenu, TopNavMegaMenu, SideNavHeading, SideNavItem, Tooltip and HoverCard, each in a same-origin iframe and in a Picture-in-Picture window: opens and takes Escape in the document it renders in (an unpinned Tooltip only when no other member is present; a pinned Tooltip before the member beneath it), and returns focus in the opener's document | The member opens or ranks in another document, a pinned Tooltip lets Escape reach the member beneath it, or focus lands on the frame element, the page, or the body |
+| FR8, FR9 | Real-browser second-document checks; implementation gap: only Dialog, Popover and HoverCard have them | Dialog, Popover, DropdownMenu, MoreMenu, ContextMenu, Selector, MultiSelector, TopNavHeading, TopNavMenu, TopNavMegaMenu, SideNavHeading, SideNavItem, Tooltip and HoverCard, each in a same-origin iframe and in a Picture-in-Picture window: opens and takes Escape in the document it renders in (an unpinned Tooltip only when no other member is present; a pinned Tooltip before the member beneath it), and returns focus in the opener's document | The member opens or ranks in another document, a pinned Tooltip lets Escape reach the member beneath it, or focus lands on the frame element, the page, or the body |
| FR8, FR9 | Real-browser second-document checks; implementation gap: none has them | BottomSheet, BottomSheetSwitcher, and Lightbox in a Picture-in-Picture window: opens, takes Escape, and returns focus to its return target there | The surface ranks in the page, or focus lands on the page or the body |
| FR8 | Source check over Drawer and MobileNav | Drawer and MobileNav rendered from a control in a second document | A page-level surface moves into the second document |
| FR10 | `useBackdropPress.test.tsx`; `BackdropPress.a11y.chromium.spec.ts` | Dialog (`purpose="info"`), Drawer scrim, and CommandPalette, with a mouse and a finger: a press that starts and ends on the backdrop, one that starts inside and ends on it, one that starts on it and ends inside, a cancelled pointer, and a backdrop start followed by a press inside | A press that crosses the edge either way dismisses, a cancelled or earlier press carries over, or a press on the backdrop alone does not dismiss |
diff --git a/docs/specs/components/HoverCard/HoverCard.spec.md b/docs/specs/components/HoverCard/HoverCard.spec.md
index 192cb4b35b..857c99f902 100644
--- a/docs/specs/components/HoverCard/HoverCard.spec.md
+++ b/docs/specs/components/HoverCard/HoverCard.spec.md
@@ -47,7 +47,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 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). |
+| Compatibility/readiness | No public API change: `touchTrigger` keeps its released values and its default `auto`. Two 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`. |
@@ -83,10 +83,6 @@ Consumer migration instructions belong in consumer docs and release notes.
- **Hover timing does not use the shared hover recognizer.** The card runs its
own show and hide timers. `architecture:interaction-modality` INV11 has
`useHoverCard` take its hover timing from the shared hover recognizer.
-- **Escape cannot close a card in another document.** HoverCard listens for
- Escape only in the page's document, so a card rendered into an iframe or a
- Picture-in-Picture window with no layer beneath it is never closed by
- Escape. WCAG 1.4.13 requires such content to be dismissible (FR6).
- **The hold follows only the pointer.** The card stays open only while the
pointer is on the trigger or the card. A card opened by keyboard focus closes
once the pointer crosses the trigger and leaves, while the trigger keeps
@@ -127,7 +123,7 @@ Consumer migration instructions belong in consumer docs and release notes.
| 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 |
+| FR6 | Escape closes a visible card through the shared dismissal stack when it is the topmost layer in its trigger's document, so a layer underneath stays open; a card rendered into another document, such as an iframe or a Picture-in-Picture window, takes the Escape pressed there. 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. `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`: 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 |
@@ -161,8 +157,8 @@ Consumer migration instructions belong in consumer docs and release notes.
- **AR1 — Popup semantics.** FR3.
- **AR2 — Content on hover or focus.** FR4–FR6 keep the card hoverable,
- dismissible, and persistent per WCAG 1.4.13, except FR6's other-document gap
- and the pointer-only hold (Current-state impact).
+ dismissible, and persistent per WCAG 1.4.13, except the pointer-only hold
+ (Current-state impact).
## Design relationships
@@ -204,14 +200,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, 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; `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. | — |
-| 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, 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; `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, and its "in a second document" Escape, refocus, focus-into-card, late-trigger, and moving-trigger cases, and its focus-trap-container Escape case; `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, in the page and in a second document; a trigger attached after the hook mounts, and one moved into a frame and back; a trigger inside a focus-trap container; `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.tsx
index 738ce1c3af..ce6bf8d6d8 100644
--- a/packages/core/src/HoverCard/HoverCard.test.tsx
+++ b/packages/core/src/HoverCard/HoverCard.test.tsx
@@ -26,9 +26,12 @@ import {
fireEvent,
waitFor,
act,
+ cleanup,
+ within,
} from '@testing-library/react';
import {renderToString} from 'react-dom/server';
import {hydrateRoot} from 'react-dom/client';
+import {createPortal} from 'react-dom';
import {StrictMode, useState, type ComponentProps} from 'react';
import * as stylex from '@stylexjs/stylex';
import {Button} from '../Button/Button';
@@ -36,6 +39,7 @@ import {ClickableCard} from '../ClickableCard/ClickableCard';
import {Theme, defineTheme} from '../theme';
import {HoverCard} from './HoverCard';
import {useHoverCard} from './useHoverCard';
+import {useFocusTrap} from '../hooks/useFocusTrap';
import {__resetInteractionModalityForTest} from '../utils/interactionModality';
// Store original matches to restore later
@@ -1083,6 +1087,255 @@ describe('HoverCard', () => {
});
describe('Escape key behavior', () => {
+ it('takes Escape before a focus-trap container its trigger sits in', async () => {
+ const onOpenChange = vi.fn();
+ const onEscape = vi.fn();
+ function Trap() {
+ const {containerRef} = useFocusTrap<HTMLDivElement>({
+ isActive: true,
+ onEscape,
+ });
+ return (
+ <div ref={containerRef}>
+ <HoverCard
+ content={<span>Card content</span>}
+ onOpenChange={onOpenChange}
+ delay={0}
+ hideDelay={0}>
+ <button type="button">Trigger</button>
+ </HoverCard>
+ </div>
+ );
+ }
+ render(<Trap />);
+ fireEvent.mouseEnter(screen.getByRole('button', {name: 'Trigger'}));
+ await waitFor(() => expect(onOpenChange).toHaveBeenLastCalledWith(true));
+
+ fireEvent.keyDown(document.body, {key: 'Escape'});
+ await waitFor(() => expect(onOpenChange).toHaveBeenLastCalledWith(false));
+ expect(onEscape).not.toHaveBeenCalled();
+ });
+
+ describe('in a second document', () => {
+ // A same-origin iframe stands in for any second document an app renders
+ // into through a portal, Document Picture-in-Picture included. A key
+ // press reaches only the document it happened in.
+ let frame: HTMLIFrameElement;
+
+ beforeEach(() => {
+ frame = document.createElement('iframe');
+ document.body.appendChild(frame);
+ // The frame has its own element prototypes: give them the same
+ // Popover API stand-ins as this document's.
+ const frameWindow = frame.contentWindow as Window & typeof globalThis;
+ const proto = frameWindow.HTMLElement.prototype;
+ const frameMatches = proto.matches;
+ proto.showPopover = function (this: HTMLElement) {
+ popoverOpenState.set(this, true);
+ };
+ proto.hidePopover = function (this: HTMLElement) {
+ popoverOpenState.set(this, false);
+ };
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ (proto as any).matches = function (selector: string): boolean {
+ if (selector === ':popover-open') {
+ return popoverOpenState.get(this) ?? false;
+ }
+ return frameMatches.call(this, selector);
+ };
+ });
+
+ afterEach(() => {
+ // Unmount before the frame goes, or React removes nodes from a
+ // document that no longer exists.
+ cleanup();
+ frame.remove();
+ });
+
+ it('closes a card rendered into the second document on Escape there', async () => {
+ const onOpenChange = vi.fn();
+ const frameDocument = frame.contentDocument!;
+ render(
+ createPortal(
+ <HoverCard
+ content={<span>Card content</span>}
+ onOpenChange={onOpenChange}
+ delay={0}
+ hideDelay={0}>
+ <button type="button">Trigger</button>
+ </HoverCard>,
+ frameDocument.body,
+ ),
+ );
+ const trigger = within(frameDocument.body).getByRole('button', {
+ name: 'Trigger',
+ });
+
+ fireEvent.mouseEnter(trigger);
+ await waitFor(() =>
+ expect(onOpenChange).toHaveBeenLastCalledWith(true),
+ );
+
+ fireEvent.keyDown(frameDocument.body, {key: 'Escape'});
+ await waitFor(() =>
+ expect(onOpenChange).toHaveBeenLastCalledWith(false),
+ );
+ });
+
+ it('takes Escape in the second document when its trigger appears there after the hook mounts', async () => {
+ const frameDocument = frame.contentDocument!;
+ function LateTrigger() {
+ const card = useHoverCard({delay: 0, hideDelay: 0});
+ const [isShown, setIsShown] = useState(false);
+ return (
+ <>
+ <button type="button" onClick={() => setIsShown(true)}>
+ Show trigger
+ </button>
+ <output data-testid="state">
+ {card.isOpen ? 'open' : 'closed'}
+ </output>
+ {isShown
+ ? createPortal(
+ <>
+ <span ref={card.ref}>Late trigger</span>
+ {card.renderHoverCard(<span>Card</span>)}
+ </>,
+ frameDocument.body,
+ )
+ : null}
+ </>
+ );
+ }
+ render(<LateTrigger />);
+ fireEvent.click(screen.getByRole('button', {name: 'Show trigger'}));
+ const state = screen.getByTestId('state');
+ fireEvent.mouseEnter(
+ within(frameDocument.body).getByText('Late trigger'),
+ );
+ await waitFor(() => expect(state).toHaveTextContent('open'));
+
+ // A press in the page is not the card's.
+ fireEvent.keyDown(document.body, {key: 'Escape'});
+ expect(state).toHaveTextContent('open');
+
+ fireEvent.keyDown(frameDocument.body, {key: 'Escape'});
+ await waitFor(() => expect(state).toHaveTextContent('closed'));
+ });
+
+ it('takes Escape where its trigger is after the trigger moves into the frame and back', async () => {
+ const frameDocument = frame.contentDocument!;
+ function MovingTrigger() {
+ const card = useHoverCard({delay: 0, hideDelay: 0});
+ const [isInFrame, setIsInFrame] = useState(false);
+ return (
+ <>
+ <button type="button" onClick={() => setIsInFrame(x => !x)}>
+ Move trigger
+ </button>
+ <output data-testid="state">
+ {card.isOpen ? 'open' : 'closed'}
+ </output>
+ {createPortal(
+ <>
+ <span ref={card.ref}>Moving trigger</span>
+ {card.renderHoverCard(<span>Card</span>)}
+ </>,
+ isInFrame ? frameDocument.body : document.body,
+ )}
+ </>
+ );
+ }
+ render(<MovingTrigger />);
+ const state = screen.getByTestId('state');
+ const move = () =>
+ fireEvent.click(screen.getByRole('button', {name: 'Move trigger'}));
+ const openIn = async (doc: Document) => {
+ fireEvent.mouseEnter(within(doc.body).getByText('Moving trigger'));
+ await waitFor(() => expect(state).toHaveTextContent('open'));
+ };
+
+ move();
+ await openIn(frameDocument);
+ fireEvent.keyDown(document.body, {key: 'Escape'});
+ expect(state).toHaveTextContent('open');
+ fireEvent.keyDown(frameDocument.body, {key: 'Escape'});
+ await waitFor(() => expect(state).toHaveTextContent('closed'));
+
+ move();
+ await openIn(document);
+ fireEvent.keyDown(frameDocument.body, {key: 'Escape'});
+ expect(state).toHaveTextContent('open');
+ fireEvent.keyDown(document.body, {key: 'Escape'});
+ await waitFor(() => expect(state).toHaveTextContent('closed'));
+ });
+
+ it('stays open when focus moves from the trigger into the card', async () => {
+ const onOpenChange = vi.fn();
+ const frameDocument = frame.contentDocument!;
+ const button = (text: string) =>
+ Array.from(frameDocument.querySelectorAll('button')).find(
+ candidate => candidate.textContent === text,
+ );
+ render(
+ createPortal(
+ <HoverCard
+ content={<button type="button">Inside</button>}
+ onOpenChange={onOpenChange}
+ delay={0}
+ hideDelay={0}>
+ <button type="button">Trigger</button>
+ </HoverCard>,
+ frameDocument.body,
+ ),
+ );
+ const trigger = button('Trigger')!;
+ fireEvent.mouseEnter(trigger);
+ await waitFor(() =>
+ expect(onOpenChange).toHaveBeenLastCalledWith(true),
+ );
+ trigger.focus();
+ button('Inside')!.focus();
+ await act(async () => {
+ await new Promise(resolve => setTimeout(resolve, 50));
+ });
+ expect(onOpenChange).toHaveBeenLastCalledWith(true);
+ });
+
+ it('returns focus to the trigger when Escape closes the card from inside it', async () => {
+ const frameDocument = frame.contentDocument!;
+ // Testing Library's role queries cannot read the frame's popover, so
+ // find buttons by text.
+ const button = (text: string) =>
+ Array.from(frameDocument.querySelectorAll('button')).find(
+ candidate => candidate.textContent === text,
+ );
+ render(
+ createPortal(
+ <HoverCard
+ content={<button type="button">Inside</button>}
+ delay={0}
+ hideDelay={0}>
+ <button type="button">Trigger</button>
+ </HoverCard>,
+ frameDocument.body,
+ ),
+ );
+ const trigger = button('Trigger')!;
+ fireEvent.mouseEnter(trigger);
+ await waitFor(() => expect(button('Inside')).toBeDefined());
+ const inside = button('Inside')!;
+ inside.focus();
+ // Compared as booleans: printing a frame's element fails.
+ expect(frameDocument.activeElement === inside).toBe(true);
+
+ fireEvent.keyDown(inside, {key: 'Escape'});
+ await waitFor(() =>
+ expect(frameDocument.activeElement === trigger).toBe(true),
+ );
+ });
+ });
+
it('hides hover card when Escape is pressed on trigger', async () => {
const onOpenChange = vi.fn();
// Reset the mock before this test
diff --git a/packages/core/src/HoverCard/__tests__/HoverCardSecondDocument.a11y.chromium.spec.ts b/packages/core/src/HoverCard/__tests__/HoverCardSecondDocument.a11y.chromium.spec.ts
new file mode 100644
index 0000000000..1cb59886c3
--- /dev/null
+++ b/packages/core/src/HoverCard/__tests__/HoverCardSecondDocument.a11y.chromium.spec.ts
@@ -0,0 +1,106 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+// @pr-a11y scope core/HoverCard ^apps/storybook/stories/HoverCardSecondDocumentA11y
+
+/**
+ * @file HoverCardSecondDocument.a11y.chromium.spec.ts
+ * @input The built a11y/HoverCard in a second document story; real Chromium
+ * keyboard and mouse input inside a same-origin iframe and a Document
+ * Picture-in-Picture window
+ * @output Browser evidence that a card in either document closes on Escape
+ * pressed there, and that Escape from inside the card returns focus to its trigger
+ * @position Chromium proof for component:HoverCard FR6 in a second document.
+ * The jsdom cases in HoverCard.test.tsx check the same paths against
+ * stand-in popovers.
+ */
+
+import {expect, test, type Page} from '@astryxdesign/a11y-spec/playwright';
+import {holdMotionStill} from '@astryxdesign/a11y-spec/chromium';
+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 () => {
+ await storybook?.close();
+});
+
+async function openFrame(page: Page) {
+ await page.goto(
+ `${storybook.origin}/iframe.html?id=a11y-hovercard-in-a-second-document--second-document&viewMode=story`,
+ );
+ await holdMotionStill(page);
+ const frame = page.frameLocator('iframe[title="Second document"]');
+ await expect(frame.getByRole('button', {name: 'Rowan'})).toBeVisible();
+ // Keys go to the focused document: put it in the frame, where a user who
+ // works there has it.
+ const frameHandle = page.frame({url: /^about:srcdoc/});
+ if (frameHandle == null) {
+ throw new Error('the story has no srcdoc frame');
+ }
+ await frameHandle.evaluate(() => window.focus());
+ return frame;
+}
+
+test('Escape pressed in the frame closes the card there', async ({page}) => {
+ const frame = await openFrame(page);
+ await frame.getByRole('button', {name: 'Rowan'}).hover();
+ const message = frame.getByRole('button', {name: 'Message'});
+ await expect(message).toBeVisible();
+
+ await page.keyboard.press('Escape');
+ await expect(message).toBeHidden();
+});
+
+test('Escape from inside the card returns focus to its trigger', async ({
+ page,
+}) => {
+ const frame = await openFrame(page);
+ const trigger = frame.getByRole('button', {name: 'Rowan'});
+ await trigger.hover();
+ const message = frame.getByRole('button', {name: 'Message'});
+ await expect(message).toBeVisible();
+ await message.focus();
+
+ await page.keyboard.press('Escape');
+ await expect(message).toBeHidden();
+ await expect(trigger).toBeFocused();
+});
+
+test('Escape pressed in a Picture-in-Picture window closes the card there, and focus returns to its trigger', async ({
+ page,
+}) => {
+ await page.goto(
+ `${storybook.origin}/iframe.html?id=a11y-hovercard-in-a-second-document--second-document&viewMode=story`,
+ );
+ await holdMotionStill(page);
+ // Opening the window needs a user gesture; the click is one.
+ const [pictureInPicture] = await Promise.all([
+ page.context().waitForEvent('page'),
+ page.getByRole('button', {name: 'Pop out'}).click(),
+ ]);
+ const trigger = pictureInPicture.getByRole('button', {name: 'Rowan'});
+ await expect(trigger).toBeVisible();
+
+ await trigger.hover();
+ const message = pictureInPicture.getByRole('button', {name: 'Message'});
+ await expect(message).toBeVisible();
+ await pictureInPicture.keyboard.press('Escape');
+ await expect(message).toBeHidden();
+
+ // Leave the trigger first: a hover where the pointer already rests fires no
+ // mouseenter.
+ await pictureInPicture.mouse.move(0, 0);
+ await trigger.hover();
+ await expect(message).toBeVisible();
+ await message.focus();
+ await pictureInPicture.keyboard.press('Escape');
+ await expect(message).toBeHidden();
+ await expect(trigger).toBeFocused();
+});
diff --git a/packages/core/src/HoverCard/useHoverCard.tsx b/packages/core/src/HoverCard/useHoverCard.tsx
index bc611d5275..1569ee59cb 100644
--- a/packages/core/src/HoverCard/useHoverCard.tsx
+++ b/packages/core/src/HoverCard/useHoverCard.tsx
@@ -34,7 +34,7 @@ import {
} from '../Layer/useTouchTrigger';
import {layerAnimations} from '../Layer/layerAnimations.stylex';
import {registerLayerSurface} from '../Layer/layerSurfacePress';
-import {useLayerDismissal} from '../Layer/useLayerDismissal';
+import {useKeyedLayerDismissal} from '../Layer/useLayerDismissal';
import {
colorVars,
shadowVars,
@@ -61,6 +61,17 @@ const styles = stylex.create({
},
});
+/**
+ * The card lives in its trigger's document, which can be an iframe or a
+ * Picture-in-Picture window rather than this page.
+ */
+function ownerDocumentOf(el: HTMLElement | null): Document | null {
+ if (el != null) {
+ return el.ownerDocument;
+ }
+ return typeof document === 'undefined' ? null : document;
+}
+
/**
* When focus on the trigger opens the hover card
*/
@@ -300,6 +311,11 @@ export function useHoverCard(options: HoverCardOptions = {}): HoverCardReturn {
const showTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const hideTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const triggerRef = useRef<HTMLElement | null>(null);
+ // The dismissal stack listens in the document a layer registers with, so
+ // the card registers when its trigger attaches, and again when the trigger
+ // attaches in another document. The key counts those documents.
+ const triggerDocumentRef = useRef<Document | null>(null);
+ const [triggerDocumentKey, setTriggerDocumentKey] = useState(0);
const isHoveringContentRef = useRef(false);
// Track when we're dismissing via Escape to prevent re-show on refocus
const isEscapeDismissingRef = useRef(false);
@@ -457,7 +473,9 @@ export function useHoverCard(options: HoverCardOptions = {}): HoverCardReturn {
}
// Check if focus is moving to the hover card content
const relatedTarget = e.relatedTarget as HTMLElement | null;
- const popoverElement = document.getElementById(layerId);
+ const popoverElement = ownerDocumentOf(
+ triggerRef.current,
+ )?.getElementById(layerId);
if (popoverElement?.contains(relatedTarget)) {
// Focus moving into hover card, keep it open
@@ -481,59 +499,61 @@ export function useHoverCard(options: HoverCardOptions = {}): HoverCardReturn {
// other layer, but answers it by reporting instead of hiding: `isOpen` is
// the consumer's value, so only their update may change it. Same contract as
// a controlled Dialog.
- useLayerDismissal({
- // Registered for the hook's lifetime rather than gated on `layer.isOpen`:
- // that state can lag a frame behind the DOM, so a press arriving right after
- // the layer appears would find nothing registered. Because this layer
- // CONSUMES the press, a stale registration would be worse than a missed one
- // — it would silently eat Escapes meant for the dialog underneath — so
- // presence is answered from the DOM at press time instead of from state.
- isActive: true,
- isPresent: () => {
- const el =
- typeof document === 'undefined'
- ? null
- : document.getElementById(layerId);
- if (el == null) {
- return false;
- }
- try {
- return el.matches(':popover-open');
- } catch {
- // Browsers without the Popover API (and some test environments) cannot
- // answer the selector; fall back to the hook's own state.
- return isLayerOpen;
- }
- },
- onDismiss: () => {
- clearTimeouts();
- clearTapOpen();
- // Controlled: report and stop. The close — and the focus restore that
- // goes with it — happens in the controlled effect if and when the
- // consumer flips `isOpen`.
- if (isOpen !== undefined) {
- onHide?.();
- return;
- }
- // Only when the card itself held focus, which is the one case the
- // content-level handler this replaced could run in. Refocusing
- // unconditionally would drag the caret out of a field the user was
- // typing in while a hover card happened to be up; arming the re-show
- // guard unconditionally would swallow their next focus on the trigger,
- // because a focus() on the already-focused trigger fires no focusin to
- // clear it.
- const card =
- typeof document === 'undefined'
- ? null
- : document.getElementById(layerId);
- const hadFocus = card?.contains(document.activeElement) ?? false;
- hide();
- if (hadFocus) {
- isEscapeDismissingRef.current = true;
- triggerRef.current?.focus();
- }
+ useKeyedLayerDismissal(
+ {
+ // Registered from the trigger's attach for the hook's lifetime, in the
+ // trigger's document, rather than gated on `layer.isOpen`:
+ // that state can lag a frame behind the DOM, so a press arriving right after
+ // the layer appears would find nothing registered. Because this layer
+ // CONSUMES the press, a stale registration would be worse than a missed one
+ // — it would silently eat Escapes meant for the dialog underneath — so
+ // presence is answered from the DOM at press time instead of from state.
+ isActive: triggerDocumentKey > 0,
+ // The stack listens for Escape in the trigger's own document, which may be
+ // an iframe or a Picture-in-Picture window rather than this page.
+ getContainer: () => triggerRef.current,
+ isPresent: () => {
+ const el = ownerDocumentOf(triggerRef.current)?.getElementById(layerId);
+ if (el == null) {
+ return false;
+ }
+ try {
+ return el.matches(':popover-open');
+ } catch {
+ // Browsers without the Popover API (and some test environments) cannot
+ // answer the selector; fall back to the hook's own state.
+ return isLayerOpen;
+ }
+ },
+ onDismiss: () => {
+ clearTimeouts();
+ clearTapOpen();
+ // Controlled: report and stop. The close — and the focus restore that
+ // goes with it — happens in the controlled effect if and when the
+ // consumer flips `isOpen`.
+ if (isOpen !== undefined) {
+ onHide?.();
+ return;
+ }
+ // Only when the card itself held focus, which is the one case the
+ // content-level handler this replaced could run in. Refocusing
+ // unconditionally would drag the caret out of a field the user was
+ // typing in while a hover card happened to be up; arming the re-show
+ // guard unconditionally would swallow their next focus on the trigger,
+ // because a focus() on the already-focused trigger fires no focusin to
+ // clear it.
+ const doc = ownerDocumentOf(triggerRef.current);
+ const card = doc?.getElementById(layerId);
+ const hadFocus = card?.contains(doc?.activeElement ?? null) ?? false;
+ hide();
+ if (hadFocus) {
+ isEscapeDismissingRef.current = true;
+ triggerRef.current?.focus();
+ }
+ },
},
- });
+ triggerDocumentKey,
+ );
// Interaction ref that handles event listeners only
const interactionRef: RefCallback<HTMLElement> = useCallback(
@@ -575,6 +595,10 @@ export function useHoverCard(options: HoverCardOptions = {}): HoverCardReturn {
}
triggerRef.current = el;
+ if (el != null && el.ownerDocument !== triggerDocumentRef.current) {
+ triggerDocumentRef.current = el.ownerDocument;
+ setTriggerDocumentKey(key => key + 1);
+ }
},
[
focusTrigger,
@@ -625,11 +649,9 @@ export function useHoverCard(options: HoverCardOptions = {}): HoverCardReturn {
// A consumer closing the card while it holds focus would strand focus on
// <body>. Arming the re-show guard is what keeps the refocus from
// reopening the card through `handleFocusIn`, which shows on any focusin.
- const card =
- typeof document === 'undefined'
- ? null
- : document.getElementById(layerId);
- const hadFocus = card?.contains(document.activeElement) ?? false;
+ const doc = ownerDocumentOf(triggerRef.current);
+ const card = doc?.getElementById(layerId);
+ const hadFocus = card?.contains(doc?.activeElement ?? null) ?? false;
hideLayer();
if (hadFocus) {
isEscapeDismissingRef.current = true;
diff --git a/packages/core/src/Layer/useLayerDismissal.ts b/packages/core/src/Layer/useLayerDismissal.ts
index 31279fc388..9e3060f285 100644
--- a/packages/core/src/Layer/useLayerDismissal.ts
+++ b/packages/core/src/Layer/useLayerDismissal.ts
@@ -123,6 +123,19 @@ export interface UseLayerDismissalReturn {
*/
export function useLayerDismissal(
options: UseLayerDismissalOptions,
+): UseLayerDismissalReturn {
+ return useKeyedLayerDismissal(options, null);
+}
+
+/**
+ * `useLayerDismissal` that registers again whenever `registrationKey`
+ * changes. A layer whose container can move to another document passes a key
+ * that changes with the document, so the stack listens where the layer now is.
+ * Internal: not exported from the package.
+ */
+export function useKeyedLayerDismissal(
+ options: UseLayerDismissalOptions,
+ registrationKey: unknown,
): UseLayerDismissalReturn {
const {
isActive,
@@ -174,7 +187,7 @@ export function useLayerDismissal(
isPresent: () => isPresentRef.current?.() ?? true,
dismiss: () => onDismissRef.current(),
});
- }, [isRegistered, depth, escapeBehavior]);
+ }, [isRegistered, depth, escapeBehavior, registrationKey]);
const shouldDismissOnCloseRequest = useCallback(
() =>