Skip to content

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

TypeScript

fix(Dialog): closing returns focus to the opener in a second document (#8381)

Christopher Chedeaucf71dcf07ae4
diff --git a/.changeset/dialog-second-document-focus-return.md b/.changeset/dialog-second-document-focus-return.md
new file mode 100644
index 0000000000..7cbe1296c8
--- /dev/null
+++ b/.changeset/dialog-second-document-focus-return.md
@@ -0,0 +1,6 @@
+---
+'@astryxdesign/core': patch
+---
+
+[fix] A `Dialog` rendered into a same-origin iframe through a portal now returns focus, when it closes, to the control in the iframe that opened it, as it does in the page.
+@vjeux
diff --git a/apps/storybook/stories/DialogSecondDocumentA11y.stories.tsx b/apps/storybook/stories/DialogSecondDocumentA11y.stories.tsx
new file mode 100644
index 0000000000..1f726639b8
--- /dev/null
+++ b/apps/storybook/stories/DialogSecondDocumentA11y.stories.tsx
@@ -0,0 +1,217 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file DialogSecondDocumentA11y.stories.tsx
+ * @input Uses Dialog, DialogHeader, Layout, Button, Text, TextInput and VStack
+ * from core, and React portals
+ * @output The fixture the second-document Dialog spec drives in a real
+ * browser: the same dialog in the page, in a same-origin iframe, and in a
+ * Document Picture-in-Picture window.
+ * @position The reproduction path for
+ * `packages/core/src/Dialog/__tests__/DialogSecondDocument.a11y.browser.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 Dialog opened there returns focus, when it closes,
+ * to the control that opened it, 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 dialog's controls by name. Nothing at compile time catches
+ * a rename — the browser 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 {Dialog, DialogHeader} from '@astryxdesign/core/Dialog';
+import {Layout, LayoutContent, VStack} from '@astryxdesign/core/Layout';
+import {Text} from '@astryxdesign/core/Text';
+import {TextInput} from '@astryxdesign/core/TextInput';
+import {isImeKeyEvent} from '@astryxdesign/core/utils';
+
+const meta: Meta = {
+ title: 'a11y/Dialog in a second document',
+ // This fixture exists to be DRIVEN by the regression spec, not photographed:
+ // what is under test is where focus goes in the iframe and the window it
+ // opens, which no frame of the page shows.
+ tags: ['no-visual'],
+ parameters: {
+ docs: {
+ description: {
+ component:
+ 'The same dialog in the page, in a same-origin iframe, and in a Picture-in-Picture window (Pop out). In every document, closing the dialog with Escape or its button returns focus to Open dialog, or to Search when Enter there opened it. Open dialog in the frame, a control in the page, opens a dialog in the iframe; closing it returns focus to that control.',
+ },
+ },
+ },
+};
+
+export default meta;
+
+const styles = stylex.create({
+ frame: {
+ width: 480,
+ height: 360,
+ borderWidth: 1,
+ borderStyle: 'solid',
+ borderColor: 'currentColor',
+ },
+});
+
+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.
+ }
+ }
+}
+
+/**
+ * A control that opens a dialog, which closes on Escape or its button, and a
+ * text field that opens it on Enter.
+ */
+function DialogDemo() {
+ const [isOpen, setIsOpen] = useState(false);
+ const [query, setQuery] = useState('');
+ return (
+ <>
+ <Button label="Open dialog" onClick={() => setIsOpen(true)} />
+ <TextInput
+ label="Search"
+ value={query}
+ onChange={setQuery}
+ onKeyDown={event => {
+ if (event.key === 'Enter' && !isImeKeyEvent(event)) {
+ setIsOpen(true);
+ }
+ }}
+ />
+ <Dialog isOpen={isOpen} onOpenChange={setIsOpen}>
+ <Layout
+ header={<DialogHeader title="Review changes" />}
+ content={
+ <LayoutContent>
+ <VStack gap={3} align="start">
+ <Text type="body">
+ Close this dialog with Escape or the button.
+ </Text>
+ <Button label="Close dialog" onClick={() => setIsOpen(false)} />
+ </VStack>
+ </LayoutContent>
+ }
+ />
+ </Dialog>
+ </>
+ );
+}
+
+/**
+ * The dialog again, portalled into a same-origin iframe, and a second dialog in
+ * the iframe that a control in the page opens.
+ */
+function FramedDialog() {
+ const [body, setBody] = useState<HTMLElement | null>(null);
+ const [isOpenFromPage, setIsOpenFromPage] = useState(false);
+ 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)}
+ />
+ <Button
+ label="Open dialog in the frame"
+ onClick={() => setIsOpenFromPage(true)}
+ />
+ {body != null &&
+ createPortal(
+ <>
+ <DialogDemo />
+ <Dialog isOpen={isOpenFromPage} onOpenChange={setIsOpenFromPage}>
+ <Layout
+ header={<DialogHeader title="Opened from the page" />}
+ content={
+ <LayoutContent>
+ <Text type="body">
+ A control in the page opened this dialog.
+ </Text>
+ </LayoutContent>
+ }
+ />
+ </Dialog>
+ </>,
+ body,
+ )}
+ </>
+ );
+}
+
+/** The dialog again, portalled into a Document Picture-in-Picture window. */
+function PictureInPictureDialog() {
+ 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: 480,
+ height: 360,
+ });
+ 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(<DialogDemo />, body)}
+ </>
+ );
+}
+
+/**
+ * One dialog 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">
+ <DialogDemo />
+ <FramedDialog />
+ <PictureInPictureDialog />
+ </VStack>
+ ),
+};
diff --git a/packages/core/src/Dialog/Dialog.test.tsx b/packages/core/src/Dialog/Dialog.test.tsx
index b676be0215..1a9bb5c430 100644
--- a/packages/core/src/Dialog/Dialog.test.tsx
+++ b/packages/core/src/Dialog/Dialog.test.tsx
@@ -13,7 +13,14 @@ import {useState, type SyntheticEvent} from 'react';
import {readFileSync} from 'node:fs';
import {describe, it, expect, vi, beforeEach, afterEach} from 'vitest';
import type {MockInstance} from 'vitest';
-import {render, screen, fireEvent} from '@testing-library/react';
+import {
+ render,
+ screen,
+ fireEvent,
+ within,
+ cleanup,
+} from '@testing-library/react';
+import {createPortal} from 'react-dom';
import {
Dialog,
dialogFullscreenSafeAreaPaddingContract,
@@ -21,7 +28,10 @@ import {
} from './Dialog';
import {DialogHeader} from './DialogHeader';
import {defineTheme, generateThemeCSS} from '../theme';
-import {__resetInteractionModalityForTest} from '../utils/interactionModality';
+import {
+ __resetInteractionModalityForTest,
+ getInteractionModality,
+} from '../utils/interactionModality';
function generateThemeTestCSS(
theme: Parameters<typeof generateThemeCSS>[0],
@@ -555,6 +565,210 @@ describe('Dialog', () => {
}).not.toThrow();
expect(dialog).not.toHaveAttribute('open');
});
+
+ describe('in a second document', () => {
+ // An app can render a Dialog into a same-origin iframe or a Document
+ // Picture-in-Picture window through a portal. The control that opens it
+ // is focused in that document; the page's document reports only the
+ // iframe element.
+ let frame: HTMLIFrameElement;
+ let secondDocument: Document;
+
+ beforeEach(() => {
+ frame = document.createElement('iframe');
+ document.body.appendChild(frame);
+ secondDocument = frame.contentDocument!;
+ // The showModal/close stand-ins above, on the second window's own
+ // prototype.
+ const {prototype} = secondDocument.defaultView!.HTMLDialogElement;
+ prototype.showModal = HTMLDialogElement.prototype.showModal;
+ prototype.close = HTMLDialogElement.prototype.close;
+ });
+
+ afterEach(() => {
+ // Unmount before the frame goes, or React removes nodes from a
+ // document that no longer exists.
+ cleanup();
+ frame.remove();
+ });
+
+ function SecondDocumentDialog({isOpen}: {isOpen: boolean}) {
+ return createPortal(
+ <>
+ <button type="button">Open dialog</button>
+ <Dialog isOpen={isOpen} onOpenChange={() => {}} aria-label="Review">
+ <button type="button">Inside</button>
+ </Dialog>
+ </>,
+ secondDocument.body,
+ );
+ }
+
+ function PageOpensSecondDocumentDialog({isOpen}: {isOpen: boolean}) {
+ return (
+ <>
+ <button type="button">Open from the page</button>
+ {createPortal(
+ <Dialog
+ isOpen={isOpen}
+ onOpenChange={() => {}}
+ aria-label="Review">
+ <button type="button">Inside</button>
+ </Dialog>,
+ secondDocument.body,
+ )}
+ </>
+ );
+ }
+
+ function SecondDocumentFieldDialog({isOpen}: {isOpen: boolean}) {
+ return createPortal(
+ <>
+ <input aria-label="Search" />
+ <Dialog isOpen={isOpen} onOpenChange={() => {}} aria-label="Review">
+ <button type="button">Inside</button>
+ </Dialog>
+ </>,
+ secondDocument.body,
+ );
+ }
+
+ function SecondDocumentDialogs({count}: {count: number}) {
+ return createPortal(
+ <>
+ {count > 0 && (
+ <Dialog isOpen={false} onOpenChange={() => {}} aria-label="First">
+ First
+ </Dialog>
+ )}
+ {count > 1 && (
+ <Dialog
+ isOpen={false}
+ onOpenChange={() => {}}
+ aria-label="Second">
+ Second
+ </Dialog>
+ )}
+ </>,
+ secondDocument.body,
+ );
+ }
+
+ it('returns focus to the control that opened it, in its own document', () => {
+ const {rerender} = render(<SecondDocumentDialog isOpen={false} />);
+ const view = within(secondDocument.body);
+ const opener = view.getByRole('button', {name: 'Open dialog'});
+ opener.focus();
+ expect(document.activeElement).toBe(frame);
+
+ rerender(<SecondDocumentDialog isOpen={true} />);
+ view.getByRole('button', {name: 'Inside', hidden: true}).focus();
+
+ rerender(<SecondDocumentDialog isOpen={false} />);
+ expect(opener).toHaveFocus();
+ });
+
+ it('returns focus to a control in the page that opened it', () => {
+ const {rerender} = render(
+ <PageOpensSecondDocumentDialog isOpen={false} />,
+ );
+ const opener = screen.getByRole('button', {name: 'Open from the page'});
+ opener.focus();
+
+ rerender(<PageOpensSecondDocumentDialog isOpen={true} />);
+ within(secondDocument.body)
+ .getByRole('button', {name: 'Inside', hidden: true})
+ .focus();
+
+ rerender(<PageOpensSecondDocumentDialog isOpen={false} />);
+ expect(opener).toHaveFocus();
+ });
+
+ it('takes the ring from the last input in its own document', () => {
+ __resetInteractionModalityForTest();
+ const {rerender} = render(<SecondDocumentDialog isOpen={false} />);
+ const opener = within(secondDocument.body).getByRole('button', {
+ name: 'Open dialog',
+ });
+ // The page's last input was a pointer press (say, on the control that
+ // popped the window out); the dialog then closes from the keyboard in
+ // its own document.
+ fireEvent.pointerDown(document.body);
+ opener.focus();
+ rerender(<SecondDocumentDialog isOpen={true} />);
+ fireEvent.keyDown(secondDocument.body, {key: 'Escape'});
+ const focus = vi.spyOn(
+ secondDocument.defaultView!.HTMLElement.prototype,
+ 'focus',
+ );
+
+ rerender(<SecondDocumentDialog isOpen={false} />);
+ expect(opener).toHaveFocus();
+ expect(
+ focus.mock.calls.filter(
+ (_call, index) => focus.mock.contexts[index] === opener,
+ ),
+ ).toEqual([[]]);
+ focus.mockRestore();
+ });
+
+ it('keeps plain focus on a text field that opened it after a pointer close', () => {
+ const {rerender} = render(<SecondDocumentFieldDialog isOpen={false} />);
+ const field = within(secondDocument.body).getByRole('textbox', {
+ name: 'Search',
+ });
+ field.focus();
+ rerender(<SecondDocumentFieldDialog isOpen={true} />);
+ const inside = within(secondDocument.body).getByRole('button', {
+ name: 'Inside',
+ hidden: true,
+ });
+ inside.focus();
+ fireEvent.pointerDown(inside);
+ // The field's own window's prototype: a field there is never an
+ // instance of the page's constructors.
+ const {prototype} = secondDocument.defaultView!.HTMLElement;
+ const focus = vi.spyOn(prototype, 'focus');
+ const blur = vi.spyOn(prototype, 'blur');
+
+ rerender(<SecondDocumentFieldDialog isOpen={false} />);
+ expect(field).toHaveFocus();
+ expect(
+ focus.mock.calls.filter(
+ (_call, index) => focus.mock.contexts[index] === field,
+ ),
+ ).toEqual([[]]);
+ expect(blur.mock.contexts).not.toContain(field);
+ focus.mockRestore();
+ blur.mockRestore();
+ });
+
+ it('tracks its document while any Dialog there is mounted, and releases it after the last', () => {
+ const removeEventListener = vi.spyOn(
+ secondDocument,
+ 'removeEventListener',
+ );
+ const removedModalityListeners = () =>
+ removeEventListener.mock.calls
+ .map(([type]) => type)
+ .filter(type => type === 'pointerdown' || type === 'keydown')
+ .sort();
+ const {rerender} = render(<SecondDocumentDialogs count={2} />);
+ fireEvent.pointerDown(secondDocument.body);
+ expect(getInteractionModality(secondDocument)).toBe('pointer');
+
+ rerender(<SecondDocumentDialogs count={1} />);
+ fireEvent.keyDown(secondDocument.body, {key: 'Tab'});
+ expect(getInteractionModality(secondDocument)).toBe('keyboard');
+ expect(removedModalityListeners()).toEqual([]);
+
+ rerender(<SecondDocumentDialogs count={0} />);
+ expect(removedModalityListeners()).toEqual(['keydown', 'pointerdown']);
+ fireEvent.pointerDown(secondDocument.body);
+ expect(getInteractionModality(secondDocument)).toBe('keyboard');
+ removeEventListener.mockRestore();
+ });
+ });
});
// jsdom draws no focus ring, so these prove only which focus call Dialog
diff --git a/packages/core/src/Dialog/Dialog.tsx b/packages/core/src/Dialog/Dialog.tsx
index 2f1e5806bd..475465ec16 100644
--- a/packages/core/src/Dialog/Dialog.tsx
+++ b/packages/core/src/Dialog/Dialog.tsx
@@ -76,7 +76,11 @@ import {DialogContext} from './DialogContext';
import {themeProps} from '../utils/themeProps';
import type {DialogVariantMap} from './index';
import {focusOutlineProps} from '../utils/focusOutline.stylex';
-import {useInteractionModalityTracking} from '../utils/interactionModality';
+import {
+ getInteractionModality,
+ trackInteractionModalityIn,
+ useInteractionModalityTracking,
+} from '../utils/interactionModality';
import {focusForLastInput} from '../utils/focusReturn';
import {ModalAnnounceProvider} from '../hooks/ModalAnnounceProvider';
@@ -91,8 +95,11 @@ function getDialogDirection(
distance = 16,
): {x: number; y: number} {
const rect = triggerEl.getBoundingClientRect();
- const dx = rect.left + rect.width / 2 - window.innerWidth / 2;
- const dy = rect.top + rect.height / 2 - window.innerHeight / 2;
+ // The trigger's own window: its rect is measured in that window's viewport,
+ // which is not the page's when the dialog renders into a second document.
+ const view = triggerEl.ownerDocument.defaultView ?? window;
+ const dx = rect.left + rect.width / 2 - view.innerWidth / 2;
+ const dy = rect.top + rect.height / 2 - view.innerHeight / 2;
const dist = Math.sqrt(dx * dx + dy * dy) || 1;
return {
x: Math.round((dx / dist) * distance),
@@ -534,6 +541,18 @@ export function Dialog({
useInteractionModalityTracking();
+ // Input in a second document (a same-origin iframe, a Document
+ // Picture-in-Picture window) never reaches the page's listeners, so the
+ // dialog's own document keeps its own last input for the focus return while
+ // this Dialog is mounted, from before it opens until it unmounts.
+ useEffect(() => {
+ const ownerDocument = dialogRef.current?.ownerDocument;
+ if (ownerDocument == null || ownerDocument === document) {
+ return undefined;
+ }
+ return trackInteractionModalityIn(ownerDocument);
+ }, [isInline]);
+
// This runs in a layout effect so the capture lands before any descendant's
// passive mount effect: all layout effects run before any passive effect,
// while a child's passive effect runs before this parent's passive effect.
@@ -545,7 +564,15 @@ export function Dialog({
if (isInline || !isOpen) {
return;
}
- triggerElementRef.current = document.activeElement as HTMLElement | null;
+ // The dialog's own document while it holds focus: an app can render a
+ // dialog into a second document (a same-origin iframe, a Document
+ // Picture-in-Picture window) through a portal, and a control there that
+ // opens it is focused in that document, which the page's document reports
+ // only as the iframe element, or not at all. A control in the page that
+ // opens such a dialog leaves focus in the page.
+ const dialogDocument = dialogRef.current?.ownerDocument ?? document;
+ const doc = dialogDocument.hasFocus() ? dialogDocument : document;
+ triggerElementRef.current = doc.activeElement as HTMLElement | null;
}, [isOpen, isInline]);
// Derive dismissal behavior from purpose
@@ -567,7 +594,7 @@ export function Dialog({
// captured by the layout effect above, before any descendant effect
// could move focus.
const trigger = triggerElementRef.current;
- if (trigger && trigger !== document.body) {
+ if (trigger && trigger !== trigger.ownerDocument.body) {
const dir = getDialogDirection(trigger);
dialog.style.setProperty('--dialog-dir-x', `${dir.x}px`);
dialog.style.setProperty('--dialog-dir-y', `${dir.y}px`);
@@ -591,9 +618,15 @@ export function Dialog({
if (dialog.open) {
dialog.close();
}
- // Return focus to the element that opened the dialog
- if (triggerElementRef.current) {
- focusForLastInput(triggerElementRef.current);
+ // Return focus to the element that opened the dialog, with the ring
+ // the last input in that element's own document calls for.
+ const trigger = triggerElementRef.current;
+ if (trigger) {
+ focusForLastInput(
+ trigger,
+ undefined,
+ getInteractionModality(trigger.ownerDocument),
+ );
}
triggerElementRef.current = null;
}
diff --git a/packages/core/src/Dialog/__tests__/DialogSecondDocument.a11y.browser.spec.ts b/packages/core/src/Dialog/__tests__/DialogSecondDocument.a11y.browser.spec.ts
new file mode 100644
index 0000000000..216f7effe9
--- /dev/null
+++ b/packages/core/src/Dialog/__tests__/DialogSecondDocument.a11y.browser.spec.ts
@@ -0,0 +1,202 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+// @pr-a11y scope ^(packages/core/src/Dialog/|packages/core/src/utils/(focusReturn|interactionModality)\.ts|apps/storybook/stories/DialogSecondDocumentA11y)
+
+/**
+ * @file DialogSecondDocument.a11y.browser.spec.ts
+ * @input Uses @playwright/test, the a11y-spec static Storybook server, and the
+ * checked-in DialogSecondDocumentA11y story
+ * @output Real-browser evidence that a Dialog rendered into a second document
+ * (a same-origin iframe, a Document Picture-in-Picture window) returns focus
+ * to the control that opened it when it closes, by Escape or by a control
+ * inside it, exactly as the same Dialog does in the page, with the focus
+ * ring that close's input calls for, a text field that opened it keeping
+ * its ring with no extra blur; and that a Dialog in an iframe opened by a
+ * control in the page returns focus to that control.
+ * @position The half of Dialog's focus return jsdom cannot reach: which
+ * document holds focus, and the browser's own focus restore when a modal
+ * dialog closes. The Vitest case in `Dialog/Dialog.test.tsx` models the
+ * same rule with an iframe. Document Picture-in-Picture is Chromium's
+ * alone, so the window's cases skip in other engines; the page and the
+ * iframe run everywhere.
+ *
+ * SYNC: Fixture lives in
+ * /apps/storybook/stories/DialogSecondDocumentA11y.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-dialog-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: 'Open dialog', 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: 'Open dialog',
+ exact: true,
+ })
+ .waitFor();
+ return {
+ frame: pictureInPicture.mainFrame(),
+ keyboard: pictureInPicture.keyboard,
+ };
+}
+
+/** Whether the element matches `:focus-visible`, i.e. would show a ring. */
+async function showsRing(element: Locator): Promise<boolean> {
+ return element.evaluate(node => node.matches(':focus-visible'));
+}
+
+/** Open the dialog from its control with the pointer; returns the control. */
+async function open(frame: Frame): Promise<{opener: Locator; dialog: Locator}> {
+ const opener = frame.getByRole('button', {name: 'Open dialog', exact: true});
+ await opener.click();
+ const dialog = frame.getByRole('dialog', {name: 'Review changes'});
+ await expect(dialog).toBeVisible();
+ return {opener, dialog};
+}
+
+for (const where of [
+ 'page',
+ 'iframe',
+ 'Picture-in-Picture window',
+] as const satisfies ReadonlyArray<Where>) {
+ test.describe(`a Dialog in the ${where}`, () => {
+ test.skip(
+ ({browserName}) =>
+ where === 'Picture-in-Picture window' && browserName !== 'chromium',
+ 'Document Picture-in-Picture is a Chromium API',
+ );
+
+ test('closing with Escape returns focus to the control that opened it', async ({
+ page,
+ }) => {
+ const {frame, keyboard} = await mountStory(page, where);
+ const {opener, dialog} = await open(frame);
+
+ await keyboard.press('Escape');
+ await expect(dialog).toBeHidden();
+ await expect(opener).toBeFocused();
+ // A key closed it, so the ring shows (`architecture:interaction-modality`
+ // INV1), whatever the page's own last input was (a pointer press on Pop
+ // out, for the Picture-in-Picture window).
+ await expect.poll(async () => showsRing(opener)).toBe(true);
+ });
+
+ test('closing from a control inside returns focus to the control that opened it', async ({
+ page,
+ }) => {
+ const {frame} = await mountStory(page, where);
+ const {opener, dialog} = await open(frame);
+
+ await frame.getByRole('button', {name: 'Close dialog'}).click();
+ await expect(dialog).toBeHidden();
+ await expect(opener).toBeFocused();
+ // A pointer closed it, so no ring.
+ await expect.poll(async () => showsRing(opener)).toBe(false);
+ });
+
+ test('a text field that opened it keeps focus and its ring after a pointer close', async ({
+ page,
+ }) => {
+ const {frame} = await mountStory(page, where);
+ const field = frame.getByRole('textbox', {name: 'Search'});
+ await field.click();
+ await field.press('Enter');
+ const dialog = frame.getByRole('dialog', {name: 'Review changes'});
+ await expect(dialog).toBeVisible();
+ // Count the field's blurs from here on: the open already moved focus
+ // away, so any blur now would be the return's own.
+ await field.evaluate(node => {
+ node.dataset.blurs = '0';
+ node.addEventListener('blur', () => {
+ node.dataset.blurs = String(Number(node.dataset.blurs) + 1);
+ });
+ });
+
+ await frame.getByRole('button', {name: 'Close dialog'}).click();
+ await expect(dialog).toBeHidden();
+ await expect(field).toBeFocused();
+ // A text field shows where typing goes whatever moved focus there.
+ await expect.poll(async () => showsRing(field)).toBe(true);
+ await expect(field).toHaveAttribute('data-blurs', '0');
+ });
+ });
+}
+
+test.describe('a Dialog in the iframe that a control in the page opens', () => {
+ test('closing with Escape returns focus to that control', async ({page}) => {
+ const {frame, keyboard} = await mountStory(page, 'iframe');
+ const opener = page.getByRole('button', {name: 'Open dialog in the frame'});
+ await opener.click();
+ const dialog = frame.getByRole('dialog', {name: 'Opened from the page'});
+ await expect(dialog).toBeVisible();
+
+ await keyboard.press('Escape');
+ await expect(dialog).toBeHidden();
+ await expect(opener).toBeFocused();
+ });
+});
diff --git a/packages/core/src/utils/focusReturn.ts b/packages/core/src/utils/focusReturn.ts
index 67e286d31f..e9528330f0 100644
--- a/packages/core/src/utils/focusReturn.ts
+++ b/packages/core/src/utils/focusReturn.ts
@@ -12,7 +12,10 @@
* overlays (Dialog, DropdownMenu) that move focus programmatically.
*/
-import {getInteractionModality} from './interactionModality';
+import {
+ getInteractionModality,
+ type InteractionModality,
+} from './interactionModality';
/**
* True when focus rests on nothing in particular — no active element, or the
@@ -43,21 +46,29 @@ export function isFocusDetached(doc: Document = document): boolean {
* autofocus target, the control that opened a Dialog, or a menu trigger the
* caller renders. Pass `options` (for example `preventScroll`) as to `focus()`.
*
+ * `modality` defaults to the page's last input. A caller moving focus inside a
+ * second document (a same-origin iframe, a Document Picture-in-Picture window)
+ * passes that document's, which it tracks with `trackInteractionModalityIn`.
+ *
* Make sure modality tracking is active (`useInteractionModalityTracking()`)
* in the component that calls this.
*/
export function focusForLastInput(
element: HTMLElement,
options?: FocusOptions,
+ modality: InteractionModality = getInteractionModality(),
): void {
// A text-entry field paints its own focus treatment to show where typing
- // goes, and an extra blur there can run validation or mark it touched.
+ // goes, and an extra blur there can run validation or mark it touched. The
+ // field's own window: one in an iframe or a Picture-in-Picture window is
+ // never an instance of the page's constructors.
+ const view = element.ownerDocument.defaultView ?? window;
const isTextEntry =
- element instanceof HTMLInputElement ||
- element instanceof HTMLTextAreaElement ||
- element instanceof HTMLSelectElement ||
+ element instanceof view.HTMLInputElement ||
+ element instanceof view.HTMLTextAreaElement ||
+ element instanceof view.HTMLSelectElement ||
element.isContentEditable;
- if (isTextEntry || getInteractionModality() !== 'pointer') {
+ if (isTextEntry || modality !== 'pointer') {
if (options === undefined) {
element.focus();
} else {
diff --git a/packages/core/src/utils/interactionModality.test.ts b/packages/core/src/utils/interactionModality.test.ts
index be03723ae3..3d54d18e75 100644
--- a/packages/core/src/utils/interactionModality.test.ts
+++ b/packages/core/src/utils/interactionModality.test.ts
@@ -3,7 +3,8 @@
/**
* @file interactionModality.test.ts
* @input The interaction-modality utility loaded more than once
- * @output Verifies document-wide continuity and shared Shift-key modality policy
+ * @output Verifies document-wide continuity, shared Shift-key modality policy,
+ * and a second document's separate value
* @position Unit coverage for interactionModality.ts
*/
@@ -88,6 +89,49 @@ describe('interactionModality', () => {
).toHaveLength(1);
});
+ it("keeps a second document's input apart from the page's", async () => {
+ const pageDocument = document.implementation.createHTMLDocument();
+ const secondDocument = document.implementation.createHTMLDocument();
+ vi.stubGlobal('document', pageDocument);
+ const tracker = await loadTracker();
+ tracker.__startInteractionModalityTrackingForTest();
+ tracker.trackInteractionModalityIn(secondDocument);
+
+ pageDocument.dispatchEvent(new Event('pointerdown'));
+ secondDocument.dispatchEvent(new KeyboardEvent('keydown', {key: 'Escape'}));
+ expect(tracker.getInteractionModality()).toBe('pointer');
+ expect(tracker.getInteractionModality(pageDocument)).toBe('pointer');
+ expect(tracker.getInteractionModality(secondDocument)).toBe('keyboard');
+
+ secondDocument.dispatchEvent(new Event('pointerdown'));
+ pageDocument.dispatchEvent(new KeyboardEvent('keydown', {key: 'Tab'}));
+ expect(tracker.getInteractionModality()).toBe('keyboard');
+ expect(tracker.getInteractionModality(secondDocument)).toBe('pointer');
+ });
+
+ it("releases a second document's listeners with its last consumer", async () => {
+ const secondDocument = document.implementation.createHTMLDocument();
+ const tracker = await loadTracker();
+ const removeEventListener = vi.spyOn(secondDocument, 'removeEventListener');
+ const releaseFirst = tracker.trackInteractionModalityIn(secondDocument);
+ const releaseSecond = tracker.trackInteractionModalityIn(secondDocument);
+ secondDocument.dispatchEvent(new Event('pointerdown'));
+ expect(tracker.getInteractionModality(secondDocument)).toBe('pointer');
+
+ releaseFirst();
+ releaseFirst();
+ secondDocument.dispatchEvent(new KeyboardEvent('keydown', {key: 'Tab'}));
+ expect(tracker.getInteractionModality(secondDocument)).toBe('keyboard');
+ expect(removeEventListener).not.toHaveBeenCalled();
+
+ releaseSecond();
+ expect(removeEventListener.mock.calls.map(([type]) => type).sort()).toEqual(
+ ['keydown', 'pointerdown'],
+ );
+ secondDocument.dispatchEvent(new Event('pointerdown'));
+ expect(tracker.getInteractionModality(secondDocument)).toBe('keyboard');
+ });
+
it('uses the keyboard-safe default without a document', async () => {
vi.stubGlobal('document', undefined);
const serverModule = await loadTracker();
diff --git a/packages/core/src/utils/interactionModality.ts b/packages/core/src/utils/interactionModality.ts
index e17c6b09d9..abfd8829aa 100644
--- a/packages/core/src/utils/interactionModality.ts
+++ b/packages/core/src/utils/interactionModality.ts
@@ -6,7 +6,9 @@
* @file interactionModality.ts
* @input Global pointerdown/keydown events
* @output `useInteractionModalityTracking()` activates document-lifetime tracking;
- * `getInteractionModality()` reads how the user last interacted
+ * `getInteractionModality()` reads how the user last interacted;
+ * `trackInteractionModalityIn(doc)` and `getInteractionModality(doc)` do the
+ * same for a second document
* @position Internal document-wide singleton; used where `:focus-visible` alone
* is too broad
*
@@ -26,8 +28,12 @@
* The store lives on `document`, so duplicate Astryx bundles share one state
* value and one listener pair. The first mounted consumer activates tracking;
* the listeners then remain for the document lifetime so input during a gap
- * between consumers is not lost. Importing this module has no DOM side effects,
- * and server rendering keeps the keyboard-safe default.
+ * between consumers is not lost. A second document (a same-origin iframe, a
+ * Document Picture-in-Picture window) gets its own store when a component
+ * tracks it, since input there never reaches the page's listeners; its
+ * listeners stay only while a consumer there is mounted. Importing this module
+ * has no DOM side effects, and server rendering keeps the keyboard-safe
+ * default.
*/
import {useEffect} from 'react';
@@ -37,6 +43,8 @@ export type InteractionModality = 'keyboard' | 'pointer';
type InteractionModalityStore = {
modality: InteractionModality;
isListening: boolean;
+ /** Mounted consumers holding a second document's listeners. */
+ consumers?: number;
onPointerDown: () => void;
onKeyDown: (event: KeyboardEvent) => void;
};
@@ -107,8 +115,59 @@ export function useInteractionModalityTracking(): void {
useEffect(() => trackInteractionModality(), []);
}
-/** How the user last interacted with the page. */
-export function getInteractionModality(): InteractionModality {
+/**
+ * Track a second document while a consumer there is mounted: a component an
+ * app renders into a same-origin iframe or a Document Picture-in-Picture
+ * window gets input there that never reaches the page's listeners. The first
+ * consumer installs the document's listener pair and the last one's cleanup
+ * removes it. Read the value with `getInteractionModality(doc)`. The page's
+ * own document keeps its document-lifetime listeners.
+ */
+export function trackInteractionModalityIn(
+ targetDocument: Document,
+): () => void {
+ if (typeof document !== 'undefined' && targetDocument === document) {
+ return trackInteractionModality();
+ }
+ const store = getStore(targetDocument);
+ store.consumers = (store.consumers ?? 0) + 1;
+ if (store.consumers === 1) {
+ store.isListening = true;
+ targetDocument.addEventListener('pointerdown', store.onPointerDown, {
+ capture: true,
+ passive: true,
+ });
+ targetDocument.addEventListener('keydown', store.onKeyDown, {
+ capture: true,
+ passive: true,
+ });
+ }
+ let isReleased = false;
+ return () => {
+ if (isReleased) {
+ return;
+ }
+ isReleased = true;
+ store.consumers = (store.consumers ?? 1) - 1;
+ if (store.consumers === 0) {
+ store.isListening = false;
+ targetDocument.removeEventListener('pointerdown', store.onPointerDown, {
+ capture: true,
+ });
+ targetDocument.removeEventListener('keydown', store.onKeyDown, {
+ capture: true,
+ });
+ }
+ };
+}
+
+/** How the user last interacted with the page, or with `targetDocument`. */
+export function getInteractionModality(
+ targetDocument?: Document,
+): InteractionModality {
+ if (targetDocument != null) {
+ return getStore(targetDocument).modality;
+ }
return typeof document === 'undefined'
? 'keyboard'
: getStore(document).modality;