An open source design system that's fully customizable and agent ready
TypeScript
fix(Popover): focus, Tab and Escape work in a second document (#7356)
Christopher Chedeau4b05772a26aa
diff --git a/.changeset/popover-second-document.md b/.changeset/popover-second-document.mdnew file mode 100644index 0000000000..a28dc85681--- /dev/null+++ b/.changeset/popover-second-document.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[fix] A `Popover` rendered into a second document through a portal, such as a same-origin iframe or a Document Picture-in-Picture window, now focuses its first control on open, keeps Tab inside, closes on Escape, and returns focus to its trigger, as it does in the page. Its trigger there stays the popover's invoker `source`.++@vjeuxdiff --git a/apps/storybook/stories/PopoverSecondDocumentA11y.stories.tsx b/apps/storybook/stories/PopoverSecondDocumentA11y.stories.tsxnew file mode 100644index 0000000000..71b6416453--- /dev/null+++ b/apps/storybook/stories/PopoverSecondDocumentA11y.stories.tsx@@ -0,0 +1,176 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file PopoverSecondDocumentA11y.stories.tsx+ * @input Uses Popover, Button, VStack and HStack from core, and React portals+ * @output The fixture the second-document Popover spec drives in a real+ * browser: the same two popovers in the page, in a same-origin iframe, and in+ * a Document Picture-in-Picture window.+ * @position The reproduction path for+ * `packages/core/src/Popover/__tests__/PopoverSecondDocument.a11y.chromium.spec.ts`+ * (`docs/specs/AST-009/spec.md` FR30: a browser claim is checked against a+ * checked-in story, not a page a test builds and throws away).+ *+ * An app can render part of its UI into a second document through a React+ * portal: a same-origin iframe, or a Document Picture-in-Picture window that+ * floats above the page. A Popover there opens, traps Tab, closes on Escape and+ * hands focus back exactly as it does in the page itself.+ *+ * SYNC: The spec navigates to this story id and finds the frame, the Pop out+ * button and the popover controls by name. Nothing at compile time catches a+ * rename — the Chromium spec does, when it finds no story or no control.+ */++import {useCallback, useState, type SyntheticEvent} from 'react';+import {createPortal} from 'react-dom';+import * as stylex from '@stylexjs/stylex';+import type {Meta, StoryObj} from '@storybook/react';+import {Button} from '@astryxdesign/core/Button';+import {HStack, VStack} from '@astryxdesign/core/Layout';+import {Popover} from '@astryxdesign/core/Popover';++const meta: Meta = {+ title: 'a11y/Popover in a second document',+ // This fixture exists to be DRIVEN by the regression spec, not photographed:+ // what is under test is focus and key handling inside the iframe and the+ // window it opens, which no frame of the page shows.+ tags: ['no-visual'],+ parameters: {+ docs: {+ description: {+ component:+ 'The same two popovers in the page, in a same-origin iframe, and in a Picture-in-Picture window (Pop out). In every document, opening focuses First, Tab stays inside, Escape closes either popover, and closing hands focus back to its trigger.',+ },+ },+ },+};++export default meta;++const styles = stylex.create({+ frame: {+ width: 420,+ height: 300,+ borderWidth: 1,+ borderStyle: 'solid',+ borderColor: 'currentColor',+ },+ // Clear of either open popover, so a press on it is a press outside.+ outside: {+ marginBlockStart: 96,+ },+});++const FRAME_DOCUMENT = '<!doctype html><html><head></head><body></body></html>';++interface DocumentPictureInPicture {+ requestWindow(options?: {width?: number; height?: number}): Promise<Window>;+}++/** Copy the page's style sheets into a second document, as an app does. */+function adoptPageStyles(target: Document) {+ for (const sheet of Array.from(document.styleSheets)) {+ try {+ const style = target.createElement('style');+ style.textContent = Array.from(sheet.cssRules, rule => rule.cssText).join(+ '\n',+ );+ target.head.append(style);+ } catch {+ // A cross-origin sheet cannot be read; the page's own sheets can.+ }+ }+}++/** The default popover, and one that closes only on request. */+function Popovers() {+ const controls = (+ <HStack gap={2}>+ <Button label="First" />+ <Button label="Last" />+ </HStack>+ );+ return (+ <VStack gap={4} align="start">+ <Popover label="Settings" content={controls}>+ <Button label="Settings" />+ </Popover>+ <Popover+ label="Pinned settings"+ hasLightDismiss={false}+ content={controls}>+ <Button label="Pinned settings" />+ </Popover>+ <p {...stylex.props(styles.outside)}>Outside</p>+ </VStack>+ );+}++/** The popovers again, portalled into a same-origin iframe. */+function FramedPopovers() {+ 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}+ {...stylex.props(styles.frame)}+ />+ {body != null && createPortal(<Popovers />, body)}+ </>+ );+}++/** The popovers again, portalled into a Document Picture-in-Picture window. */+function PictureInPicturePopovers() {+ 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: 300,+ });+ 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(<Popovers />, body)}+ </>+ );+}++/**+ * Two popovers in each of three documents: the page, a same-origin iframe, and+ * a Picture-in-Picture window that Pop out opens.+ */+export const SecondDocuments: StoryObj = {+ name: 'in the page, an iframe and a Picture-in-Picture window',+ render: () => (+ <VStack gap={6} align="start">+ <Popovers />+ <FramedPopovers />+ <PictureInPicturePopovers />+ </VStack>+ ),+};diff --git a/docs/families/overlay-dismissal.md b/docs/families/overlay-dismissal.mdindex d451c22bfa..07a0af1878 100644--- a/docs/families/overlay-dismissal.md+++ b/docs/families/overlay-dismissal.md@@ -20,6 +20,8 @@ verified_by:packages/core/src/BottomSheet/BottomSheetSwitcher.test.tsx,packages/core/src/ContextMenu/ContextMenu.test.tsx,packages/core/src/CommandPalette/CommandPalette.test.tsx,+ packages/core/src/Popover/Popover.test.tsx,+ packages/core/src/Popover/__tests__/PopoverSecondDocument.a11y.chromium.spec.ts,]members:[@@ -124,8 +126,9 @@ this record's current membership snapshot must be updated with it.- `useLayerDismissal` registers an active surface and adapts abrowser-initiated close request to the shared topmost check.-- `layerStack` owns presence filtering, ordering, and the single- document-level Escape listener.+- `layerStack` owns presence filtering, ordering, and the document-level+ Escape listener: one in each document that holds a registered member (FR8,+ proposed; pending owner review).- `LayerDepthProvider` carries logical nesting through the React tree for membersthat provide it to their descendants. Members without that provider do notguarantee nested ordering after descendant content leaves DOM containment.@@ -171,6 +174,19 @@ this record's current membership snapshot must be updated with it.- **FR7 — Registration does not define open-state ownership.** The stack invokesthe selected member's dismissal callback. Whether that request immediatelycloses the surface is owned by the member's component contract and caller.+- **FR8 — Each document ranks its own members.** A member belongs to the+ document of the element it registers with: Dialog (and CommandPalette through+ it), Lightbox, MobileNav, BottomSheet, BottomSheetSwitcher and Drawer register+ their dialog, ContextMenu its menu, and a focus trap its container. An Escape+ press or platform close request is ranked only among the registered present+ members of the document it arrives in, and FR2 and FR3 apply within that+ document, so a host and the members nested in it that register an element keep+ one order wherever they render. A member of another document is never a+ candidate. Tooltip and HoverCard register no element and read their presence+ from the page's document: they belong to the page, and in another document+ they take no request, so their host handles the first one. The stack listens+ once in each document that holds a member and stops when its last member+ leaves. Proposed; pending owner review (DEC-2).## Allowed component variation@@ -193,19 +209,22 @@ this record's current membership snapshot must be updated with it.| Dialog inside Dialog | Inner dialog handles the first request | Dialog supplies native modality and focus behavior || Popover inside Dialog | Popover handles the first Escape | Popover supplies anchoring, portal placement, and focus policy || Registered descendant inside CommandPalette | Descendant handles the first Escape | CommandPalette inherits Dialog's shared stack participation |-| Tooltip or HoverCard inside Dialog | Present hover surface handles the first Escape | Hover families decide when they are present and how controlled state responds |+| Tooltip or HoverCard inside Dialog, in page | Present hover surface handles the first Escape | Hover families decide when they are present and how controlled state responds || Lightbox or MobileNav above a required Dialog | Top member handles the request | Required Dialog uses `block` only when it is topmost || Required Dialog alone | Request is consumed without closing | Dialog purpose selects `block` behavior || Self-owned input popup | Popup participates while present | Input owns selection, focus, open state, positioning, and outside dismissal || Two unrelated registered surfaces | Later active-cycle registration is topmost | Neither surface is treated as nested || Platform close request sent to a lower Dialog | Lower Dialog stays open | The platform targets a host; the shared check decides whether it may close |+| Popover in an iframe, Dialog in the page | Request goes to its own document's top member | The app renders into the second document through a portal |+| Popover inside Dialog in an iframe | Popover handles the iframe's first request | Both register their own elements, so they rank in the iframe's order |+| Tooltip or HoverCard inside Dialog, in iframe | The Dialog handles the first Escape there | Hover members register no element and read presence from the page (FR8) |## Adoption and exceptions| Components or surface | Adoption | Current deviation or limitation || -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- || Dialog, AlertDialog, Popover, DropdownMenu root, ContextMenu, MoreMenu, Lightbox, MobileNav, Drawer, CommandPalette | shared owner; CommandPalette composes Dialog | none |-| Tooltip, HoverCard | shared owner with DOM presence reporting | Neither provides nesting depth to descendant layers |+| Tooltip, HoverCard | shared owner with DOM presence reporting | Neither provides nesting depth to descendant layers; both read presence from the page's document, so in another document they take no request (FR8) || 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 || BottomSheet, BottomSheetSwitcher | shared owner | none |@@ -223,6 +242,8 @@ modality, positioning, outside-dismissal, and open-state contracts.| FR2, FR3, FR4, FR6 | `layerDismissalInvariants.test.tsx` | nested same-DOM Dialogs, Lightbox over Dialog, Dialog in BottomSheet, platform cancel, IME | One request closes two surfaces, closes a host before its child, or dismisses during composition || FR1, FR2, FR3, FR7 | `layerDismissalFamilies.test.tsx` | Dialog, Lightbox, MobileNav, BottomSheet, Tooltip, HoverCard; controlled and blocking states | A family bypasses the stack, a lower member handles a request, or controlled ownership is ignored || FR1 | `useFocusTrap.test.tsx` | active, nested, and deactivated traps with `onEscape` | A dismissible trap stays off the shared stack or nested traps respond together |+| FR8 | `useLayerDismissal.test.tsx`; `Popover.test.tsx` | members in the page and a same-origin iframe; a Popover alone and inside a Dialog, in an iframe | A press in one document dismisses a member of another, or a host closes over its nested layer |+| 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 |## Decision links@@ -242,6 +263,18 @@ are the audited current snapshot, not a closed set.A layer with no dismissal behavior does not participate. A visual-only outlinerendered through Layer is the canonical nonparticipating example.+### DEC-2 — Each document ranks its own members++**Decider:** pending owner review++A key press and a platform close request reach only the document they happen+in, and each document keeps its own browser top layer. The stack therefore+orders the members of each document separately and listens once per document.+One request still affects exactly one surface: the topmost one in the document+where the person acted.++Rejected: one order across documents, where a press in one window dismisses a surface in another.+## Open questionsNone. Focus, modality, positioning, outside dismissal, and open-state APIs arediff --git a/packages/core/src/Dialog/Dialog.tsx b/packages/core/src/Dialog/Dialog.tsxindex 5f25c0e95c..a15506a3ea 100644--- a/packages/core/src/Dialog/Dialog.tsx+++ b/packages/core/src/Dialog/Dialog.tsx@@ -623,6 +623,9 @@ export function Dialog({onDismiss: () => {onOpenChange(false);},+ // The dialog's document is this layer's: rendered into an iframe or a+ // Picture-in-Picture window, it ranks with the layers opened inside it.+ getContainer: () => dialogRef.current,});// Dev-time guardrail: an open modal should always have an accessible name.diff --git a/packages/core/src/Layer/layerStack.ts b/packages/core/src/Layer/layerStack.tsindex b85e470748..d84e945500 100644--- a/packages/core/src/Layer/layerStack.ts+++ b/packages/core/src/Layer/layerStack.ts@@ -6,8 +6,8 @@* @file layerStack.ts* @input Uses the isImeKeyEvent predicate from utils/ime* @output Exports the shared layer dismissal stack: registration, top-most- * ordering, the document-level Escape listener, and its internal local-event- * dispatcher+ * ordering, the Escape listener on each document that holds a layer, and its+ * internal local-event dispatcher* @position Internal to the Layer system; consumed by useLayerDismissal, which* is what overlays actually call. Not exported from the package root.*@@ -26,12 +26,27 @@** ## Only the top layer acts*- * The stack owns ONE `keydown` listener on `document` and routes the press to+ * The stack owns ONE `keydown` listener per document and routes the press to* the top-most layer itself. Overlays do not listen; they register and say what* they want done. The alternative — every layer listens and filters itself out* — is what forces `stopPropagation()` choreography between element-level and* document-level listeners, and it silently breaks whenever a layer forgets.*+ * ## One listener per document+ *+ * A layer can live in a document other than the one this module was loaded+ * in: an app may render into a same-origin iframe or a Document+ * Picture-in-Picture window through a portal. A key press reaches only the+ * document it happened in, so the listener goes on the layer's own document —+ * its container's `ownerDocument` — with that document's first layer, and comes+ * off with its last. A layer that names no container counts as the global+ * `document`'s.+ *+ * The top-most layer is chosen among the layers of the document the press+ * arrived in, the way each document keeps its own browser top layer. A press in+ * one window never reaches past it to dismiss a layer in another, and one press+ * still dismisses exactly one layer.+ ** ## Bubble phase, not capture** The listener is on the BUBBLE phase so content inside a layer can claim the@@ -114,10 +129,11 @@ export interface LayerStackEntry {seq: number;behavior: LayerEscapeBehavior;/**- * The layer's container element, read lazily at press time. Used only to- * break ties between layers the React tree reports at the same depth — a raw+ * The layer's container element, read lazily at press time. Used to break+ * ties between layers the React tree reports at the same depth — a raw* `useFocusTrap` cannot wrap its content in a depth provider (it renders- * nothing), so DOM containment is the only nesting signal those have.+ * nothing), so DOM containment is the only nesting signal those have — and,+ * once at registration, to find the document the layer lives in.*/getContainer?: () => HTMLElement | null;/**@@ -133,7 +149,13 @@ export interface LayerStackEntry {dismiss: () => void;}-const entries: LayerStackEntry[] = [];+/** An entry and the document it was registered in. */+interface DocumentEntry extends LayerStackEntry {+ /** The layer's document; null only where there is no DOM at all. */+ ownerDocument: Document | null;+}++const entries: DocumentEntry[] = [];// Registration order per layer identity. `useLayerDismissal` keeps one token// through effect re-registration while an active layer changes depth or behavior// — a Dialog whose `purpose` flips while open, a focus trap that moves — and@@ -143,7 +165,9 @@ const entries: LayerStackEntry[] = [];// the browser top layer's show order.let seqByToken = new WeakMap<object, number>();let nextSeq = 0;-let isListening = false;+// How many registered layers live in each document: the listeners go on a+// document with its first layer and come off with its last.+const layerCountByDocument = new Map<Document, number>();function seqFor(token: object): number {const existing = seqByToken.get(token);@@ -204,9 +228,9 @@ function isPresentEntry(entry: LayerStackEntry): boolean {return entry.isPresent?.() ?? true;}-// Whether a text composition is running anywhere on the page. Tracked from+// The documents in which a text composition is running. Tracked from// composition events because the DOM offers no way to ask.-let isComposing = false;+const composingDocuments = new Set<Document>();/*** Whether the user is part-way through composing text with an IME.@@ -225,29 +249,35 @@ let isComposing = false;* recover from, and the alternative — matching the composing element against* a layer's container — cannot work for the layers that do not have one.*- * A composition already running when the first layer registers is invisible- * here: the listeners go on with the stack's own.+ * A composition already running when a document's first layer registers is+ * invisible here: the listeners go on with the stack's own. Page-wide means+ * every document that holds a layer.*/export function isTextComposing(): boolean {- return isComposing;+ return composingDocuments.size > 0;}-function handleCompositionStart(): void {- isComposing = true;+// The listeners sit on documents, so the current target is the document the+// composition runs in.+function handleCompositionStart(event: Event): void {+ composingDocuments.add(event.currentTarget as Document);}// Focus leaving the field ends the composition too. Clearing on blur as well// means a compositionend this listener never sees cannot leave the flag stuck// on, swallowing every later close request.-function handleCompositionEnd(): void {- isComposing = false;+function handleCompositionEnd(event: Event): void {+ composingDocuments.delete(event.currentTarget as Document);}-/** The top-most present layer, or null when nothing is on screen. */-function topPresentEntry(): LayerStackEntry | null {- let top: LayerStackEntry | null = null;+/**+ * The top-most present layer of `doc`, or null when nothing is on screen+ * there.+ */+function topPresentEntry(doc: Document | null): DocumentEntry | null {+ let top: DocumentEntry | null = null;for (const entry of entries) {- if (!isPresentEntry(entry)) {+ if (entry.ownerDocument !== doc || !isPresentEntry(entry)) {continue;}if (top == null || compareEntries(entry, top) > 0) {@@ -258,17 +288,41 @@ function topPresentEntry(): LayerStackEntry | null {}/**- * Whether `token` identifies the top-most layer. Overlays that still own a- * dismissal channel the stack does not model yet (outside-press, swipe) can- * gate on this so every channel agrees on who is on top.+ * Whether `token` identifies the top-most layer of its own document. Overlays+ * that still own a dismissal channel the stack does not model yet+ * (outside-press, swipe) can gate on this so every channel agrees on who is on+ * top.*/export function isTopmostLayer(token: object): boolean {- return topPresentEntry()?.token === token;+ const entry = entries.find(candidate => candidate.token === token);+ return entry != null && topPresentEntry(entry.ownerDocument) === entry;}-/** Resolve an Escape press against the stack. Returns whether it was handled. */-function dispatchEscape(): boolean {- const top = topPresentEntry();+/** The global document, or null where there is no DOM. */+function globalDocument(): Document | null {+ return typeof document === 'undefined' ? null : document;+}++/**+ * The document a key press happened in: its target's, or the target itself+ * when the press was dispatched at a document. Read from `nodeType` rather+ * than `instanceof`, which names this module's window and so misses a node+ * of another one.+ */+function documentOfEvent(event: Event): Document | null {+ const target = event.target as Node | null;+ if (target == null) {+ return null;+ }+ return target.nodeType === 9 ? (target as Document) : target.ownerDocument;+}++/**+ * Resolve an Escape press against the layers of `doc`. Returns whether it was+ * handled.+ */+function dispatchEscape(doc: Document | null): boolean {+ const top = topPresentEntry(doc);if (top == null) {return false;}@@ -292,6 +346,7 @@ export function dispatchLayerEscapeKeyDown(event: KeyboardEvent): void {if (event.key !== 'Escape') {return;}+ const doc = documentOfEvent(event) ?? globalDocument();// An IME user pressing Escape is cancelling a composition, not dismissing a// layer. Claim the press anyway, then stand down: left unclaimed, the browser// raises its own close request, which arrives at a layer's `cancel` handler@@ -299,7 +354,7 @@ export function dispatchLayerEscapeKeyDown(event: KeyboardEvent): void {// guard that only returns behaves exactly like no guard at all. Claim it only// while a layer is on screen; with nothing to protect, the press is not ours.if (isImeKeyEvent(event)) {- if (topPresentEntry() != null) {+ if (topPresentEntry(doc) != null) {event.preventDefault();}return;@@ -309,7 +364,7 @@ export function dispatchLayerEscapeKeyDown(event: KeyboardEvent): void {if (event.defaultPrevented) {return;}- if (dispatchEscape()) {+ if (dispatchEscape(doc)) {// Suppress the browser's own close-watcher so it cannot dismiss a second// layer behind our back. Propagation is left alone: consumers may// legitimately listen for Escape on window, and the stack's decision is@@ -318,31 +373,19 @@ export function dispatchLayerEscapeKeyDown(event: KeyboardEvent): void {}}-function startListening(): void {- if (isListening || typeof document === 'undefined') {- return;- }- document.addEventListener('keydown', dispatchLayerEscapeKeyDown);- document.addEventListener('compositionstart', handleCompositionStart, true);- document.addEventListener('compositionend', handleCompositionEnd, true);- document.addEventListener('blur', handleCompositionEnd, true);- isListening = true;+function startListening(doc: Document): void {+ doc.addEventListener('keydown', dispatchLayerEscapeKeyDown);+ doc.addEventListener('compositionstart', handleCompositionStart, true);+ doc.addEventListener('compositionend', handleCompositionEnd, true);+ doc.addEventListener('blur', handleCompositionEnd, true);}-function stopListening(): void {- if (!isListening || typeof document === 'undefined') {- return;- }- document.removeEventListener('keydown', dispatchLayerEscapeKeyDown);- document.removeEventListener(- 'compositionstart',- handleCompositionStart,- true,- );- document.removeEventListener('compositionend', handleCompositionEnd, true);- document.removeEventListener('blur', handleCompositionEnd, true);- isComposing = false;- isListening = false;+function stopListening(doc: Document): void {+ doc.removeEventListener('keydown', dispatchLayerEscapeKeyDown);+ doc.removeEventListener('compositionstart', handleCompositionStart, true);+ doc.removeEventListener('compositionend', handleCompositionEnd, true);+ doc.removeEventListener('blur', handleCompositionEnd, true);+ composingDocuments.delete(doc);}/**@@ -350,26 +393,50 @@ function stopListening(): void {* function; callers own calling it.*/export function registerLayer(entry: Omit<LayerStackEntry, 'seq'>): () => void {- const full: LayerStackEntry = {...entry, seq: seqFor(entry.token)};+ // The document the layer lives in: its container's, else the global one.+ const ownerDocument =+ entry.getContainer?.()?.ownerDocument ?? globalDocument();+ const full: DocumentEntry = {+ ...entry,+ seq: seqFor(entry.token),+ ownerDocument,+ };entries.push(full);- startListening();+ if (ownerDocument != null) {+ const count = layerCountByDocument.get(ownerDocument) ?? 0;+ layerCountByDocument.set(ownerDocument, count + 1);+ if (count === 0) {+ startListening(ownerDocument);+ }+ }return () => {const index = entries.indexOf(full);- if (index !== -1) {- entries.splice(index, 1);+ if (index === -1) {+ return;+ }+ entries.splice(index, 1);+ if (ownerDocument == null) {+ return;}- if (entries.length === 0) {- stopListening();+ const count = layerCountByDocument.get(ownerDocument) ?? 1;+ if (count > 1) {+ layerCountByDocument.set(ownerDocument, count - 1);+ return;}+ layerCountByDocument.delete(ownerDocument);+ stopListening(ownerDocument);};}-/** Test-only: drop all entries and detach the listener. */+/** Test-only: drop all entries and detach every listener. */export function resetLayerStackForTests(): void {entries.length = 0;seqByToken = new WeakMap();nextSeq = 0;- isComposing = false;- stopListening();+ for (const doc of layerCountByDocument.keys()) {+ stopListening(doc);+ }+ layerCountByDocument.clear();+ composingDocuments.clear();}diff --git a/packages/core/src/Layer/useLayer.test.tsx b/packages/core/src/Layer/useLayer.test.tsxindex 96aa5acb83..846229370b 100644--- a/packages/core/src/Layer/useLayer.test.tsx+++ b/packages/core/src/Layer/useLayer.test.tsx@@ -733,6 +733,62 @@ describe('useLayer', () => {});});+ describe('the invoker source', () => {+ /**+ * Mirror the Popover API's option conversion: `source` must be an HTML+ * element, from any document, and any other element throws before the+ * popover shows.+ */+ function installSourceCheckingShowPopover(+ view: Window & typeof globalThis,+ ) {+ const showSpy = vi.fn(function (+ this: HTMLElement,+ options?: ShowPopoverOptions,+ ) {+ const source: Element | undefined = options?.source;+ const sourceView = source?.ownerDocument.defaultView;+ if (+ source != null &&+ !(sourceView != null && source instanceof sourceView.HTMLElement)+ ) {+ throw new TypeError(+ "Failed to execute 'showPopover' on 'HTMLElement': Failed to read the 'source' property from 'ShowPopoverOptions': Failed to convert value to 'HTMLElement'.",+ );+ }+ this.dataset.open = 'true';+ });+ view.HTMLElement.prototype.showPopover = showSpy;+ return showSpy;+ }++ it('keeps an HTML trigger in another document as the source', () => {+ const frame = document.createElement('iframe');+ document.body.append(frame);+ try {+ const frameWindow = frame.contentWindow as Window & typeof globalThis;+ const showSpy = installSourceCheckingShowPopover(frameWindow);+ const container = frameWindow.document.body.appendChild(+ frameWindow.document.createElement('div'),+ );+ const {unmount} = render(<ContextLayerHarness />, {container});+ const trigger = container.querySelector('button') as HTMLElement;+ // An element of the frame's window, not of the test's.+ expect(trigger).not.toBeInstanceOf(HTMLElement);++ fireEvent.click(trigger);++ // Compared by identity: a deep comparison does not walk a node from+ // another window.+ expect(showSpy).toHaveBeenCalledOnce();+ expect(showSpy.mock.calls[0]?.[0]?.source).toBe(trigger);+ unmount();+ } finally {+ frame.remove();+ }+ });+ });+describe('show() while another popover is mid show/hide', () => {/*** Mirror the Popover API's re-entrancy rule: hiding a popover hands focusdiff --git a/packages/core/src/Layer/useLayer.tsx b/packages/core/src/Layer/useLayer.tsxindex a68c0ec8e6..1859efc3c2 100644--- a/packages/core/src/Layer/useLayer.tsx+++ b/packages/core/src/Layer/useLayer.tsx@@ -766,12 +766,18 @@ function useLayerImplementation(// trigger is an `SVGElement`, whose dictionary conversion throws// before the popover opens. Omitting the option for it still anchors// the layer, because positioning reads the anchor-name pair, and only- // gives up the invoker's focus order.- const trigger =- triggerRef.current instanceof HTMLElement- ? triggerRef.current- : undefined;- popover.showPopover({source: trigger});+ // gives up the invoker's focus order. The check asks the trigger's own+ // window: an HTML trigger rendered into another document (an iframe,+ // a Picture-in-Picture window) is not an instance of this window's+ // `HTMLElement`, and keeps its source.+ const trigger = triggerRef.current;+ const triggerView = trigger?.ownerDocument.defaultView;+ popover.showPopover({+ source:+ triggerView != null && trigger instanceof triggerView.HTMLElement+ ? trigger+ : undefined,+ });});} else {popover.style.display = 'block';diff --git a/packages/core/src/Layer/useLayerDismissal.test.tsx b/packages/core/src/Layer/useLayerDismissal.test.tsxindex 219d967fa1..995b5dd9a8 100644--- a/packages/core/src/Layer/useLayerDismissal.test.tsx+++ b/packages/core/src/Layer/useLayerDismissal.test.tsx@@ -10,9 +10,10 @@* question the stack exists to answer.*/-import {render, fireEvent} from '@testing-library/react';-import {describe, expect, it, vi, afterEach} from 'vitest';+import {render, fireEvent, cleanup} from '@testing-library/react';+import {describe, expect, it, vi, afterEach, beforeEach} from 'vitest';import {StrictMode, useRef} from 'react';+import {createPortal} from 'react-dom';import {LayerDepthProvider} from './LayerDepthContext';import {useLayerDismissal} from './useLayerDismissal';@@ -467,6 +468,88 @@ describe('useLayerDismissal', () => {fireEvent.blur(field);expect(ask(onAsk)).toBe(true);});++ it('answers against the top-most layer of its own document', () => {+ // A layer that opened later in a second document is on top there, not+ // here: it cannot make a close request in this document decline.+ const onAsk = vi.fn();+ const frame = document.createElement('iframe');+ document.body.appendChild(frame);+ try {+ render(<CloseRequestLayer onAsk={onAsk} />);+ render(+ createPortal(+ <Layer onDismiss={vi.fn()} />,+ frame.contentDocument!.body,+ ),+ );++ expect(ask(onAsk)).toBe(true);+ } finally {+ cleanup();+ frame.remove();+ }+ });+ });++ describe('in a second document', () => {+ // A same-origin iframe stands in for any second document an app renders+ // layers into through a portal, Document Picture-in-Picture included. A+ // key press reaches only the document it happened in.+ let frame: HTMLIFrameElement;+ let secondDocument: Document;++ beforeEach(() => {+ frame = document.createElement('iframe');+ document.body.appendChild(frame);+ secondDocument = frame.contentDocument!;+ });++ afterEach(() => {+ // Unmount before the frame goes, or React removes nodes from a+ // document that no longer exists.+ cleanup();+ frame.remove();+ });++ it('dismisses the top-most layer of the document the press arrived in', () => {+ const here = vi.fn();+ const there = vi.fn();+ render(<Layer onDismiss={here} />);+ // Registered later, so one order across both documents would put it on+ // top of the layer here as well.+ render(createPortal(<Layer onDismiss={there} />, secondDocument.body));++ fireEvent.keyDown(secondDocument, {key: 'Escape'});+ expect(there).toHaveBeenCalledTimes(1);+ expect(here).not.toHaveBeenCalled();++ pressEscape();+ expect(here).toHaveBeenCalledTimes(1);+ expect(there).toHaveBeenCalledTimes(1);+ });++ it('listens in a document once, and only while it holds a layer', () => {+ const added = vi.spyOn(secondDocument, 'addEventListener');+ const removed = vi.spyOn(secondDocument, 'removeEventListener');+ const keydownCalls = (spy: typeof added) =>+ spy.mock.calls.filter(([type]) => type === 'keydown').length;++ const {unmount} = render(+ createPortal(+ <>+ <Layer onDismiss={vi.fn()} />+ <Layer onDismiss={vi.fn()} />+ </>,+ secondDocument.body,+ ),+ );+ expect(keydownCalls(added)).toBe(1);+ expect(keydownCalls(removed)).toBe(0);++ unmount();+ expect(keydownCalls(removed)).toBe(1);+ });});it('leaves the event alone when no layer is open', () => {diff --git a/packages/core/src/Layer/useLayerDismissal.ts b/packages/core/src/Layer/useLayerDismissal.tsindex 42ad0bc4fc..0168ef100d 100644--- a/packages/core/src/Layer/useLayerDismissal.ts+++ b/packages/core/src/Layer/useLayerDismissal.ts@@ -7,8 +7,8 @@* @input Uses React hooks, the layer stack, and LayerDepthContext* @output Exports useLayerDismissal + its option/return types* @position The API overlays use to join the shared dismissal stack. Wraps- * layerStack (registration + the single Escape listener) and reads nesting- * depth from LayerDepthContext.+ * layerStack (registration + the Escape listener on each layer's document)+ * and reads nesting depth from LayerDepthContext.** SYNC: When modified, update:* - /packages/core/src/Layer/index.ts@@ -48,7 +48,10 @@ export interface UseLayerDismissalOptions {/*** This layer's container element, read lazily. Optional: supply it when the* layer cannot wrap its content in `LayerDepthProvider` (a bare focus trap- * renders nothing), so nesting can still be recovered from the DOM.+ * renders nothing), so nesting can still be recovered from the DOM. Its+ * document is also the layer's: the stack listens there and ranks the layer+ * among that document's layers. Without it, the layer belongs to the global+ * `document`.*/getContainer?: () => HTMLElement | null;/**@@ -94,12 +97,12 @@ export interface UseLayerDismissalReturn {/*** Join the shared layer dismissal stack for as long as this layer is active.*- * The layer does NOT attach a key listener — the stack owns one listener and- * routes each Escape press to the top-most REGISTERED layer, so one press- * dismisses exactly one of them. Dialog (and what is built on it, including- * CommandPalette), Popover and the menus built on it, ContextMenu, Tooltip,- * HoverCard, Lightbox, MobileNav, BottomSheet, BottomSheetSwitcher and- * `Drawer` register today.+ * The layer does NOT attach a key listener — the stack owns one listener per+ * document and routes each Escape press to the top-most REGISTERED layer of+ * the document it arrived in, so one press dismisses exactly one of them.+ * Dialog (and what is built on it, including CommandPalette), Popover and the+ * menus built on it, ContextMenu, Tooltip, HoverCard, Lightbox, MobileNav,+ * BottomSheet, BottomSheetSwitcher and `Drawer` register today.** `DropdownMenuSubMenu` and `PowerSearchEditPopover` still run their own Escape* listeners. They stay safe next to the stack only because each claims the pressdiff --git a/packages/core/src/Lightbox/Lightbox.tsx b/packages/core/src/Lightbox/Lightbox.tsxindex 64354c1574..376ed067b6 100644--- a/packages/core/src/Lightbox/Lightbox.tsx+++ b/packages/core/src/Lightbox/Lightbox.tsx@@ -438,6 +438,9 @@ export function Lightbox({const {shouldDismissOnCloseRequest} = useLayerDismissal({isActive: isOpen,onDismiss: handleClose,+ // The dialog's document is this layer's: rendered into an iframe or a+ // Picture-in-Picture window, it ranks with the layers opened inside it.+ getContainer: () => dialogRef.current,});// The native `cancel` event is the browser's own close-watcher firing: andiff --git a/packages/core/src/MobileNav/MobileNav.tsx b/packages/core/src/MobileNav/MobileNav.tsxindex 0f342f725c..b32cf6e979 100644--- a/packages/core/src/MobileNav/MobileNav.tsx+++ b/packages/core/src/MobileNav/MobileNav.tsx@@ -632,6 +632,9 @@ export function MobileNav({const {shouldDismissOnCloseRequest} = useLayerDismissal({isActive: isOpen,onDismiss: () => onOpenChange(false),+ // The dialog's document is this layer's: rendered into an iframe or a+ // Picture-in-Picture window, it ranks with the layers opened inside it.+ getContainer: () => dialogRef.current,});// The native `cancel` event is the browser's own close-watcher firing: andiff --git a/packages/core/src/Popover/Popover.test.tsx b/packages/core/src/Popover/Popover.test.tsxindex 3cdfde58b2..d5c5597851 100644--- a/packages/core/src/Popover/Popover.test.tsx+++ b/packages/core/src/Popover/Popover.test.tsx@@ -10,12 +10,30 @@* SYNC: When Popover.tsx changes, update tests to match new behavior*/-import {describe, it, expect, vi, beforeAll, afterAll} from 'vitest';-import {render, screen, fireEvent, waitFor, act} from '@testing-library/react';+import {+ describe,+ it,+ expect,+ vi,+ beforeAll,+ afterAll,+ beforeEach,+ afterEach,+} from 'vitest';+import {+ render,+ screen,+ fireEvent,+ waitFor,+ act,+ within,+ cleanup,+} from '@testing-library/react';import userEvent from '@testing-library/user-event';import * as stylex from '@stylexjs/stylex';import {readFileSync} from 'node:fs';import React, {useRef} from 'react';+import {createPortal} from 'react-dom';import {Popover} from './Popover';import {usePopover} from './usePopover';import type {UsePopoverReturn} from './usePopover';@@ -1028,6 +1046,183 @@ describe('Popover', () => {});});+ describe('in a second document', () => {+ // An app can render a Popover into a same-origin iframe or a Document+ // Picture-in-Picture window through a portal. Every press and focus change+ // then happens in that document, and none of them reaches this one.+ let frame: HTMLIFrameElement;+ let secondDocument: Document;++ beforeEach(() => {+ frame = document.createElement('iframe');+ document.body.appendChild(frame);+ secondDocument = frame.contentDocument!;+ // The Popover API stand-in above, on the second window's own prototype.+ const {prototype} = secondDocument.defaultView!.HTMLElement;+ prototype.showPopover = HTMLElement.prototype.showPopover;+ prototype.hidePopover = HTMLElement.prototype.hidePopover;+ });++ afterEach(() => {+ // Unmount before the frame goes, or React removes nodes from a+ // document that no longer exists.+ cleanup();+ frame.remove();+ });++ function renderInSecondDocument(hasLightDismiss = true) {+ render(+ createPortal(+ <>+ <Popover+ label="Settings"+ hasLightDismiss={hasLightDismiss}+ content={+ <>+ <button type="button">First</button>+ <button type="button">Last</button>+ </>+ }>+ <button type="button">Settings</button>+ </Popover>+ <p>Outside</p>+ </>,+ secondDocument.body,+ ),+ );+ const view = within(secondDocument.body);+ const trigger = view.getByRole('button', {name: 'Settings'});+ const surface = view.getByRole('dialog', {+ name: 'Settings',+ hidden: true,+ });+ const first = view.getByRole('button', {name: 'First', hidden: true});+ return {trigger, surface, first, view};+ }++ /** Open from the trigger, as a pointer would, and wait for focus to enter. */+ async function open(trigger: HTMLElement, surface: HTMLElement) {+ trigger.focus();+ fireEvent.click(trigger, {detail: 1});+ expect(trigger).toHaveAttribute('aria-expanded', 'true');+ await waitFor(() =>+ expect(surface.contains(secondDocument.activeElement)).toBe(true),+ );+ }++ it('focuses the first content control on open', async () => {+ const {trigger, surface, first} = renderInSecondDocument();+ await open(trigger, surface);++ expect(first).toHaveFocus();+ });++ it('wraps Tab from the last control back to the first', async () => {+ const {trigger, surface, first, view} = renderInSecondDocument();+ await open(trigger, surface);+ const last = view.getByRole('button', {+ name: 'Close popover',+ hidden: true,+ });+ last.focus();++ expect(fireEvent.keyDown(last, {key: 'Tab'})).toBe(false);+ expect(first).toHaveFocus();+ });++ it('closes on Escape through the layer stack and returns focus to the trigger', async () => {+ const {trigger, surface} = renderInSecondDocument();+ await open(trigger, surface);++ // The stack claims the press, so the browser's own close watcher does+ // not act on it a second time.+ expect(+ fireEvent.keyDown(secondDocument.activeElement!, {key: 'Escape'}),+ ).toBe(false);+ expect(trigger).toHaveAttribute('aria-expanded', 'false');+ expect(trigger).toHaveFocus();+ });++ it('closes on Escape when light dismiss is off', async () => {+ const {trigger, surface} = renderInSecondDocument(false);+ await open(trigger, surface);++ fireEvent.keyDown(secondDocument.activeElement!, {key: 'Escape'});+ expect(trigger).toHaveAttribute('aria-expanded', 'false');+ expect(trigger).toHaveFocus();+ });++ it('returns focus to the trigger after an outside click', async () => {+ const {trigger, surface} = renderInSecondDocument();+ await open(trigger, surface);++ // The press on non-focusable content blurs focus to the body, then the+ // browser's light dismiss closes the popover with a `toggle` event.+ (secondDocument.activeElement as HTMLElement).blur();+ expect(secondDocument.activeElement).toBe(secondDocument.body);+ const toggle = new secondDocument.defaultView!.Event('toggle');+ Object.defineProperty(toggle, 'newState', {value: 'closed'});+ fireEvent(secondDocument.querySelector('[popover]')!, toggle);++ expect(trigger).toHaveAttribute('aria-expanded', 'false');+ expect(trigger).toHaveFocus();+ });++ it('keeps a Dialog and the Popover opened inside it in one order', () => {+ // jsdom has no modal <dialog>; stand in for it on the second window.+ const {prototype: dialogPrototype} =+ secondDocument.defaultView!.HTMLDialogElement;+ dialogPrototype.showModal = function (this: HTMLDialogElement) {+ this.setAttribute('open', '');+ };+ dialogPrototype.close = function (this: HTMLDialogElement) {+ this.removeAttribute('open');+ };+ const onOpenChange = vi.fn();+ render(+ createPortal(+ <Dialog+ isOpen={true}+ onOpenChange={onOpenChange}+ purpose="info"+ aria-label="Host">+ <Popover+ label="Tip"+ content={<button type="button">Inside</button>}>+ <button type="button">Open tip</button>+ </Popover>+ </Dialog>,+ secondDocument.body,+ ),+ );+ const trigger = within(secondDocument.body).getByRole('button', {+ name: 'Open tip',+ hidden: true,+ });+ fireEvent.click(trigger);+ expect(trigger).toHaveAttribute('aria-expanded', 'true');++ // A press in this document reaches neither layer of the other one.+ fireEvent.keyDown(document, {key: 'Escape'});+ expect(trigger).toHaveAttribute('aria-expanded', 'true');+ expect(onOpenChange).not.toHaveBeenCalled();++ // The Dialog declines a close request while the Popover is above it.+ const closeRequest = new secondDocument.defaultView!.Event('cancel', {+ cancelable: true,+ });+ fireEvent(secondDocument.querySelector('dialog')!, closeRequest);+ expect(onOpenChange).not.toHaveBeenCalled();++ // In its own document, Escape closes the Popover, then the Dialog.+ fireEvent.keyDown(secondDocument, {key: 'Escape'});+ expect(trigger).toHaveAttribute('aria-expanded', 'false');+ expect(onOpenChange).not.toHaveBeenCalled();+ fireEvent.keyDown(secondDocument, {key: 'Escape'});+ expect(onOpenChange).toHaveBeenCalledExactlyOnceWith(false);+ });+ });+describe('surface padding', () => {// StyleX's dev runtime names the style object a class came from// ("padding__paddingStyles.3"), which is the padding rung the surfacediff --git a/packages/core/src/Popover/__tests__/PopoverSecondDocument.a11y.chromium.spec.ts b/packages/core/src/Popover/__tests__/PopoverSecondDocument.a11y.chromium.spec.tsnew file mode 100644index 0000000000..c7ea319c4e--- /dev/null+++ b/packages/core/src/Popover/__tests__/PopoverSecondDocument.a11y.chromium.spec.ts@@ -0,0 +1,204 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file PopoverSecondDocument.a11y.chromium.spec.ts+ * @input Uses @playwright/test, the a11y-spec static Storybook server, and the+ * checked-in PopoverSecondDocumentA11y story+ * @output Real-browser evidence that a Popover rendered into a second document+ * (a same-origin iframe, a Document Picture-in-Picture window) focuses its+ * first control on open, keeps Tab inside, closes on Escape through the layer+ * stack with and without light dismiss, and hands focus back to its trigger+ * after an outside click, exactly as the same Popover does in the page.+ * @position The half of the second-document rule jsdom cannot honestly reach:+ * real key delivery to another window, native light dismiss, and the+ * browser's own close watcher. The Vitest cases in `Popover/Popover.test.tsx`+ * model the same rule with an iframe.+ *+ * SYNC: Fixture lives in+ * /apps/storybook/stories/PopoverSecondDocumentA11y.stories.tsx.+ */++import {+ expect,+ test,+ type Frame,+ type Keyboard,+ type Locator,+ type Page,+} from '@playwright/test';+import {holdMotionStill} from '@astryxdesign/a11y-spec/chromium';+import {+ DEFAULT_STORYBOOK_DIR,+ serveStorybook,+ type StaticServer,+} from '@astryxdesign/a11y-spec/storybook';++const STORY_ID = 'a11y-popover-in-a-second-document--second-documents';++let storybook: StaticServer;++test.beforeAll(async () => {+ storybook = await serveStorybook(+ process.env.ASTRYX_STORYBOOK_DIR ?? DEFAULT_STORYBOOK_DIR,+ );+});++test.afterAll(async () => {+ await storybook?.close();+});++type Where = 'page' | 'iframe' | 'Picture-in-Picture window';++/** One document of the story: where its controls live and where keys go. */+interface Surface {+ frame: Frame;+ keyboard: Keyboard;+}++/** Load the story and return the document the test drives. */+async function mountStory(page: Page, where: Where): Promise<Surface> {+ await page.goto(+ `${storybook.origin}/iframe.html?id=${STORY_ID}&viewMode=story`,+ {waitUntil: 'load'},+ );+ await holdMotionStill(page);+ const popOut = page.getByRole('button', {name: 'Pop out'});+ await popOut.waitFor();++ if (where === 'page') {+ return {frame: page.mainFrame(), keyboard: page.keyboard};+ }+ if (where === 'iframe') {+ const element = await page+ .locator('iframe[title="Second document"]')+ .elementHandle();+ const frame = await element?.contentFrame();+ if (frame == null) {+ throw new Error('the story renders no iframe');+ }+ await frame.getByRole('button', {name: 'Settings', exact: true}).waitFor();+ // Key presses go to whichever frame holds focus; the clicks below put it+ // in this one.+ return {frame, keyboard: page.keyboard};+ }+ // Opening the window needs a user gesture; the click is one.+ const [pictureInPicture] = await Promise.all([+ page.context().waitForEvent('page'),+ popOut.click(),+ ]);+ await pictureInPicture+ .getByRole('button', {name: 'Settings', exact: true})+ .waitFor();+ return {+ frame: pictureInPicture.mainFrame(),+ keyboard: pictureInPicture.keyboard,+ };+}++/** Open a popover from its trigger with the pointer; returns the trigger. */+async function open(frame: Frame, name: string): Promise<Locator> {+ const trigger = frame.getByRole('button', {name, exact: true});+ await trigger.click();+ await expect(trigger).toHaveAttribute('aria-expanded', 'true');+ await expect(frame.getByRole('dialog', {name, exact: true})).toBeVisible();+ return trigger;+}++for (const where of [+ 'page',+ 'iframe',+ 'Picture-in-Picture window',+] as const satisfies ReadonlyArray<Where>) {+ test.describe(`a Popover in the ${where}`, () => {+ test('focuses its first control on open', async ({page}) => {+ const {frame} = await mountStory(page, where);+ await open(frame, 'Settings');++ await expect(frame.getByRole('button', {name: 'First'})).toBeFocused();+ });++ test('keeps Tab inside: past the last control, focus wraps to the first', async ({+ page,+ }) => {+ const {frame, keyboard} = await mountStory(page, where);+ await open(frame, 'Settings');+ const first = frame.getByRole('button', {name: 'First'});+ await first.focus();++ // First, Last, the fallback Close popover control, then First again.+ for (let press = 0; press < 3; press++) {+ await keyboard.press('Tab');+ }+ await expect(first).toBeFocused();+ });++ test('closes on Escape with light dismiss off, and focus returns to the trigger', async ({+ page,+ }) => {+ const {frame, keyboard} = await mountStory(page, where);+ const trigger = await open(frame, 'Pinned settings');++ await keyboard.press('Escape');+ await expect(trigger).toHaveAttribute('aria-expanded', 'false');+ await expect(trigger).toBeFocused();+ });++ test('closes on Escape through the layer stack with light dismiss on', async ({+ page,+ }) => {+ const {frame, keyboard} = await mountStory(page, where);+ const trigger = await open(frame, 'Settings');+ // The stack claims a press it handles with preventDefault(), so the+ // browser's own close watcher does not act on it too. A window listener+ // runs after the stack's document listener and reads that claim.+ await frame.evaluate(() => {+ window.addEventListener('keydown', event => {+ if (event.key === 'Escape') {+ document.body.dataset.escapeClaimed = String(+ event.defaultPrevented,+ );+ }+ });+ });++ await keyboard.press('Escape');+ await expect(trigger).toHaveAttribute('aria-expanded', 'false');+ expect(+ await frame.evaluate(() => document.body.dataset.escapeClaimed),+ ).toBe('true');+ await expect(trigger).toBeFocused();+ });++ test('closes on an outside click, and focus returns to the trigger', async ({+ page,+ }) => {+ const {frame} = await mountStory(page, where);+ const trigger = await open(frame, 'Settings');++ await frame.getByText('Outside', {exact: true}).click();+ await expect(trigger).toHaveAttribute('aria-expanded', 'false');+ await expect(trigger).toBeFocused();+ });++ if (where !== 'page') {+ test('an Escape press affects only the document it was made in', async ({+ page,+ }) => {+ const {frame, keyboard} = await mountStory(page, where);+ // Opened first, so one order across both documents would put the+ // page's popover above this one.+ const there = await open(frame, 'Pinned settings');+ const here = await open(page.mainFrame(), 'Pinned settings');++ await frame.getByRole('button', {name: 'First'}).click();+ await keyboard.press('Escape');+ await expect(there).toHaveAttribute('aria-expanded', 'false');+ await expect(here).toHaveAttribute('aria-expanded', 'true');++ await page.mainFrame().getByRole('button', {name: 'First'}).click();+ await page.keyboard.press('Escape');+ await expect(here).toHaveAttribute('aria-expanded', 'false');+ });+ }+ });+}diff --git a/packages/core/src/Popover/usePopover.tsx b/packages/core/src/Popover/usePopover.tsxindex c481d37209..42c9519d0e 100644--- a/packages/core/src/Popover/usePopover.tsx+++ b/packages/core/src/Popover/usePopover.tsx@@ -47,7 +47,9 @@ function attemptFocus(element: HTMLElement): boolean {} catch {// Ignore non-focusable elements; the caller will try the next target.}- return document.activeElement === element;+ // The element's own document: a popover rendered into a second document+ // (an iframe, a Picture-in-Picture window) never moves this one's focus.+ return element.ownerDocument.activeElement === element;}function focusFirstContentControl(container: HTMLElement): boolean {diff --git a/packages/core/src/hooks/useFocusTrap.test.tsx b/packages/core/src/hooks/useFocusTrap.test.tsxindex bfa643aa14..e40b340180 100644--- a/packages/core/src/hooks/useFocusTrap.test.tsx+++ b/packages/core/src/hooks/useFocusTrap.test.tsx@@ -9,8 +9,15 @@* SYNC: When useFocusTrap.ts changes, update tests to match new behavior*/-import {describe, it, expect, vi} from 'vitest';-import {render, screen, fireEvent} from '@testing-library/react';+import {describe, it, expect, vi, beforeEach, afterEach} from 'vitest';+import {+ render,+ screen,+ fireEvent,+ within,+ cleanup,+} from '@testing-library/react';+import {createPortal} from 'react-dom';import {FOCUSABLE_SELECTOR} from './focusableSelector';import {useFocusTrap} from './useFocusTrap';@@ -500,3 +507,65 @@ describe('useFocusTrap focus restoration', () => {expect(prev).toHaveFocus();});});++describe('useFocusTrap in a second document', () => {+ // A same-origin iframe stands in for any second document an app renders a+ // trap into through a portal, Document Picture-in-Picture included. Its+ // elements belong to the iframe's own window, and its key presses and focus+ // changes never reach this document.+ let frame: HTMLIFrameElement;+ let secondDocument: Document;++ beforeEach(() => {+ frame = document.createElement('iframe');+ document.body.appendChild(frame);+ secondDocument = frame.contentDocument!;+ });++ afterEach(() => {+ // Unmount before the frame goes, or React removes nodes from a document+ // that no longer exists.+ cleanup();+ frame.remove();+ });++ it('keeps Tab on a programmatic focus target when nothing inside is tabbable', () => {+ render(+ createPortal(+ <Trap>+ <div tabIndex={-1} data-testid="programmatic-target">+ Read-only dialog content+ </div>+ </Trap>,+ secondDocument.body,+ ),+ );+ const target = within(secondDocument.body).getByTestId(+ 'programmatic-target',+ );+ target.focus();++ expect(fireEvent.keyDown(target, {key: 'Tab'})).toBe(false);+ expect(target).toHaveFocus();+ });++ it('returns focus to the element focused before it in that document', () => {+ const {rerender} = render(+ createPortal(<RestoreFixture isActive={false} />, secondDocument.body),+ );+ const view = within(secondDocument.body);+ const prev = view.getByTestId('prev');+ prev.focus();++ rerender(+ createPortal(<RestoreFixture isActive={true} />, secondDocument.body),+ );+ view.getByTestId('inside').focus();+ (secondDocument.activeElement as HTMLElement).blur();++ rerender(+ createPortal(<RestoreFixture isActive={false} />, secondDocument.body),+ );+ expect(prev).toHaveFocus();+ });+});diff --git a/packages/core/src/hooks/useFocusTrap.ts b/packages/core/src/hooks/useFocusTrap.tsindex a39dd143c9..ed30f086e7 100644--- a/packages/core/src/hooks/useFocusTrap.ts+++ b/packages/core/src/hooks/useFocusTrap.ts@@ -102,6 +102,26 @@ export function getFocusableElements(container: HTMLElement): HTMLElement[] {).filter(isVisiblyFocusable);}+/**+ * The document a trap lives in: its container's. An app that renders into a+ * same-origin iframe or a Document Picture-in-Picture window through a portal+ * puts the trap in that window's document, whose key presses and focus+ * changes never reach this module's global `document`.+ */+function trapDocument(container: HTMLElement | null): Document {+ return container?.ownerDocument ?? document;+}++/**+ * `instanceof HTMLElement`, asked of the node's own window: an element of a+ * second document is an instance of that window's `HTMLElement`, not of this+ * one's.+ */+function isHTMLElement(node: Node | null): node is HTMLElement {+ const view = node?.ownerDocument?.defaultView;+ return view != null && node instanceof view.HTMLElement;+}+/*** Attempt to focus an element. Returns true if focus was successful.*/@@ -111,7 +131,7 @@ function attemptFocus(element: HTMLElement): boolean {} catch {// Some elements may throw on focus}- return document.activeElement === element;+ return element.ownerDocument.activeElement === element;}/**@@ -176,7 +196,7 @@ export interface UseFocusTrapReturn<T extends HTMLElement = HTMLElement> {* Hook for trapping focus within a container element.** Implements the WAI-ARIA dialog focus trap pattern:- * - Listens to focus events on the document+ * - Listens to focus events on the container's document* - Redirects focus back into the container if it escapes* - Handles both Tab and Shift+Tab navigation* - Restores focus to the element that was focused before activation when the@@ -278,15 +298,16 @@ export function useFocusTrap<T extends HTMLElement = HTMLElement>(return;}- const previouslyFocused = document.activeElement as HTMLElement | null;// Snapshot the container now; by cleanup it may be detached or unmounted.const container = containerRef.current;+ const doc = trapDocument(container);+ const previouslyFocused = doc.activeElement as HTMLElement | null;// Whether focus ever entered the trap container while it was active.// Initialized from the current active element in case focus was already// inside at activation (e.g. a programmatic focus before the effect ran).let hadFocusInside =- container != null && container.contains(document.activeElement);+ container != null && container.contains(doc.activeElement);const markFocusInside = (event: FocusEvent) => {const target = event.target as Node | null;@@ -294,20 +315,20 @@ export function useFocusTrap<T extends HTMLElement = HTMLElement>(hadFocusInside = true;}};- document.addEventListener('focusin', markFocusInside, true);+ doc.addEventListener('focusin', markFocusInside, true);return () => {- document.removeEventListener('focusin', markFocusInside, true);+ doc.removeEventListener('focusin', markFocusInside, true);if (!hadFocusInside) {return;}- const active = document.activeElement;+ const active = doc.activeElement;const focusWasLost =active == null ||- active === document.body ||- active === document.documentElement ||+ active === doc.body ||+ active === doc.documentElement ||(container != null && container.contains(active));if (!focusWasLost) {@@ -333,6 +354,8 @@ export function useFocusTrap<T extends HTMLElement = HTMLElement>(return;}+ const doc = trapDocument(containerRef.current);+const handleFocus = (event: FocusEvent) => {const container = containerRef.current;if (!container) {@@ -350,11 +373,11 @@ export function useFocusTrap<T extends HTMLElement = HTMLElement>(// If we're back at the same element (Shift+Tab from first element),// try focusing the last element instead- if (focusedFirst && lastFocusRef.current === document.activeElement) {+ if (focusedFirst && lastFocusRef.current === doc.activeElement) {focusLastDescendant(container);} else if (!focusedFirst &&- lastFocusRef.current instanceof HTMLElement &&+ isHTMLElement(lastFocusRef.current) &&container.contains(lastFocusRef.current)) {// A modal surface may intentionally have no tabbable controls and@@ -363,7 +386,7 @@ export function useFocusTrap<T extends HTMLElement = HTMLElement>(attemptFocus(lastFocusRef.current);}- lastFocusRef.current = document.activeElement;+ lastFocusRef.current = doc.activeElement;}// If focus escaped via mouse click, don't redirect - let light dismiss handle it@@ -372,10 +395,10 @@ export function useFocusTrap<T extends HTMLElement = HTMLElement>(};// Use capture phase to intercept focus before it settles- document.addEventListener('focus', handleFocus, true);+ doc.addEventListener('focus', handleFocus, true);return () => {- document.removeEventListener('focus', handleFocus, true);+ doc.removeEventListener('focus', handleFocus, true);};}, [isActive]);@@ -393,6 +416,8 @@ export function useFocusTrap<T extends HTMLElement = HTMLElement>(return;}+ const doc = trapDocument(containerRef.current);+const handleKeyDown = (event: KeyboardEvent) => {const container = containerRef.current;if (!container) {@@ -405,8 +430,8 @@ export function useFocusTrap<T extends HTMLElement = HTMLElement>(const focusable = getFocusableElements(container);if (focusable.length === 0) {- const active = document.activeElement;- if (!(active instanceof HTMLElement) || !container.contains(active)) {+ const active = doc.activeElement;+ if (!isHTMLElement(active) || !container.contains(active)) {// A layer can be open while focus legitimately sits outside it —// a listbox popup anchored to its own input. Cancelling there// would take Tab away from the whole page.@@ -424,7 +449,7 @@ export function useFocusTrap<T extends HTMLElement = HTMLElement>(const first = focusable[0];const last = focusable[focusable.length - 1];- if (document.activeElement === container) {+ if (doc.activeElement === container) {// Programmatic initial focus can sit on the trap container itself// (for example a dialog panel with no content controls). Move into// the tabbable cycle instead of letting Tab escape to the page.@@ -439,13 +464,13 @@ export function useFocusTrap<T extends HTMLElement = HTMLElement>(if (event.shiftKey) {// Shift+Tab: if on first element, wrap to last- if (document.activeElement === first) {+ if (doc.activeElement === first) {event.preventDefault();last.focus();}} else {// Tab: if on last element, wrap to first- if (document.activeElement === last) {+ if (doc.activeElement === last) {event.preventDefault();first.focus();}@@ -453,10 +478,10 @@ export function useFocusTrap<T extends HTMLElement = HTMLElement>(}};- document.addEventListener('keydown', handleKeyDown);+ doc.addEventListener('keydown', handleKeyDown);return () => {- document.removeEventListener('keydown', handleKeyDown);+ doc.removeEventListener('keydown', handleKeyDown);};}, [isActive, onEscape]);