Skip to content

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

Merged
cixzhang merged 2 commits into
meta:mainfrom
vjeux:dialog-second-document
Oct 30, 2026
Merged

cixzhang merged 2 commits into
meta:mainfrom
vjeux:dialog-second-document

Conversation

@vjeux

@vjeux vjeux commented Oct 25, 2026 •

Copy link
Copy Markdown
Contributor

User impact

Why: Keyboard and screen reader users lose their place when a dialog inside an iframe closes: both ways to close it (2 of 2: Escape or a button) send focus to the frame's empty page.

What: The dialog now returns focus to the control that opened it, with a ring after a key, none after a click. Picture-in-Picture windows were already fine.

How to check: In the "Dialog in a second document" story, open the frame's dialog and press Escape: focus returns to "Open dialog", with its ring.

Problem and solution fit

What led here: we hit this moving one product onto Astryx, which renders some UI in a second window. Dialog remembers its opener as the page's document.activeElement, which for focus inside an iframe is the <iframe>. Focusing that <iframe> on close moves the frame's focus to its <body>.

Options:

  • Follow the page's active element into iframes: misses Picture-in-Picture windows, which the page cannot see into.
  • Always read the dialog's own document: a page control opening a dialog inside an iframe would lose focus.
  • Read the dialog's own document while it has focus, else the page's: covers both. Chosen.

For the ring, Dialog tracks its own document's input, which the page never hears. Skipping its focus call would change the page, where it hides WebKit's ring after a click.

Expected behavior and authority

component:Dialog (current) FR4 and AR2: closing returns focus to the element that opened it. architecture:interaction-modality (current) INV1: programmatic focus shows the ring only after keyboard input. Neither is page-only; #7356 fixed this for Popover.

Smallest restoration

  • Dialog.tsx: record the opener as above, take the entry direction from its window, return focus with its document's modality.
  • Internal utils: trackInteractionModalityIn(doc), counted so the last mounted Dialog removes its listeners; an optional document for getInteractionModality; an optional modality for focusForLastInput, which checks text fields against their own window. The page's tracker and other callers are unchanged.

No public API, visual or timing change.

Evidence

  • Reproduction before the change: main fails the iframe cases in Chromium and WebKit.
  • Result after the change: every case passes.
  • Representative unchanged path: the page Dialog passes before and after; the page's modality ignores other documents.
  • Regression test or other mutation-sensitive proof: the Testing cases, red without the fix.

Scope

  • One defect is restored.
  • Separable contradictory or unsettled tagalongs were removed or split.
  • No new public API, visual representation, default, or interaction model is hidden under the bug-fix label.
  • Public text and artifacts contain no internal Meta context.

Testing

@vercel

vercel Bot commented Oct 25, 2026 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated
astryx Ready Ready Preview Oct 30, 2026 9:24pm UTC

Request Review

@astracat-bot

astracat-bot Bot commented Oct 25, 2026 •

Copy link
Copy Markdown
Contributor

AI review status for this pull request.

Review status Updated
🔄 In progress (for maintainers only) Oct 30, 2026, 9:12 PM UTC

@astracat-bot astracat-bot Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reading the opener from the dialog's own document fixes focus return for a Dialog opened from inside a same-origin iframe, and the new Vitest case and the spec's iframe cases fail without the change. Two regressions need fixing before this can be approved:

  • A control in the page that opens a Dialog rendered into an iframe now leaves focus on the frame's <body> on close instead of returning it to that control; reading the dialog's document only when dialogDocument.hasFocus() keeps your fix and restores this case.
  • In a Picture-in-Picture window, closing with a key after the last input in the page was a pointer (such as clicking Pop out) now hides the focus indicator the browser's own restore showed, because focusForLastInput reads the page's modality; the modality needs to follow the dialog's document.

Please add a test for each, and drop the Picture-in-Picture claim from the changeset, since that path already returned focus.

[Automated review]

Comment thread packages/core/src/Dialog/Dialog.tsx Resolved
Comment thread packages/core/src/Dialog/Dialog.tsx Resolved
@vjeux
vjeux force-pushed the dialog-second-document branch from 2159d96 to 0d47027 Compare October 25, 2026 07:28
@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Oct 25, 2026

@astracat-bot astracat-bot Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Both earlier regressions and the changeset are fixed: a page control that opens a dialog in the iframe gets focus back, and a keyboard close in a Picture-in-Picture window keeps the focus ring. Two changes are still needed before this can be approved:

  • focusForLastInput detects text entry with the page's HTMLInputElement, HTMLTextAreaElement and HTMLSelectElement, which never match a field from another window, so a text field that opened the dialog in an iframe or a Picture-in-Picture window is blurred and refocused without :focus-visible after a pointer close; checking against the constructors of element.ownerDocument.defaultView fixes it, and a test for that case would keep it fixed.
  • The listeners trackInteractionModalityIn adds to the dialog's document are never removed, while architecture:react-component-runtime INV3 asks an effect's cleanup to release what it installs, so please remove them in the cleanup (a pair per Dialog, or a counted installation) unless an engineering owner documents that lifetime.

[Automated review]

Comment thread packages/core/src/utils/focusReturn.ts Resolved
Comment thread packages/core/src/Dialog/Dialog.tsx Resolved

@astracat-bot astracat-bot Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Recommending approval: a Dialog portalled into a same-origin iframe now returns focus on close to the control that opened it, with the focus ring after Escape and none after a pointer close, while page and Picture-in-Picture behaviour is unchanged. Both points from the last review are addressed: text entry is now checked against the field's own window, and a second document's listeners are released with its last Dialog, each covered by a test that fails without the fix. Nothing more is needed from you; the remaining step is an engineering owner's review.

[Automated review]

@github-actions

github-actions Bot commented Oct 25, 2026 •

Copy link
Copy Markdown
Contributor

PR Analysis Report

Current run: The current CI run concluded failure. Current analysis is unavailable.

View Storybook for this PR · View Sandbox for this PR


Generated by PR Enrichment workflow | View current CI run

Dialog captured the element to return focus to from the page's
document.activeElement. When an app renders the dialog into a same-origin
iframe, the control that opened it is focused in the iframe's document, and
the page's document reports the <iframe> element: closing then moved the
frame's focus to its <body>.

Read the active element of the dialog's own document while it holds focus,
and the page's otherwise, so a control in the page that opens a dialog in an
iframe still gets focus back. Return focus with the modality of the opener's
own document: Dialog tracks its own document's input while it is mounted,
since input in a second document never reaches the page's listeners; the
first mounted Dialog in a document installs the listeners and the last one
removes them. focusForLastInput knows a text field by its own window's
constructors. Measure the entry animation's direction in the opener's own
window.

@astracat-bot astracat-bot Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Recommending approval: a Dialog portalled into a same-origin iframe now returns focus on close to the control that opened it, with the focus ring after Escape and none after a pointer close, while page dialogs are unchanged and a Picture-in-Picture window returns focus the same way. The new Vitest cases fail without each part of the fix, and the browser spec covers the iframe, page-control and Picture-in-Picture paths. Nothing more is needed from you; the remaining step is an engineering owner's review.

[Automated review]

@vjeux
vjeux marked this pull request as draft October 29, 2026 22:45
@vjeux
vjeux marked this pull request as ready for review October 29, 2026 23:59
@vjeux
vjeux marked this pull request as draft October 30, 2026 03:37
@cixzhang
cixzhang marked this pull request as ready for review October 30, 2026 19:37
@cixzhang cixzhang added the ci:run A maintainer lets this outside contributor's pull request run CI (AST-030 FR17) label Oct 30, 2026
@cixzhang
cixzhang merged commit cf71dcf into meta:main Oct 30, 2026
53 of 54 checks passed
@vjeux
vjeux deleted the dialog-second-document branch October 30, 2026 22:11
cixzhang pushed a commit that referenced this pull request Oct 31, 2026
…igin style sheets (#9063)

The Dialog and Popover second-document stories' style copy now skips only stylesheets from another origin, which the browser won't let them read, and lets any other error throw, so a real failure isn't hidden. Found in a review of error handling and split out of #8381 so it could merge as is.

## Maintainer impact

Both stories copy the page's style sheets into a same-origin iframe and a Document Picture-in-Picture window, where the second-document browser specs run. The copy wrapped each sheet in a catch that ignored every error, so a broken copy would fail silently and leave those frames unstyled.

## Intended invariant

The stories copy every same-origin and inline sheet, as before. A cross-origin sheet, which the browser forbids reading, is still skipped. The specs that use these stories behave the same.

## Change

In both stories, `adoptPageStyles` skips a sheet only when its `href` origin differs from the page's, and any other error throws. Story code only: no package source changes, so no changeset.

## Evidence

- Failure before the change: any error while copying a sheet was swallowed, with nothing reported.
- Success after the change: in Chromium 149 and WebKit 26.5, reading `cssRules` throws a `SecurityError` only for the cross-origin sheet; same-origin and inline sheets read fine and are copied.
- Product/runtime behavior verified unchanged: the Dialog and Popover second-document specs pass.

## Scope

- [x] No intended public API, product behavior, visual direction, or policy change.
- [x] Product changes discovered during the work were removed or split.
- [x] Public text and artifacts contain no internal Meta context.

## Testing

Local gates at a2492d4 (on main d48bca5):

- `pnpm exec playwright test packages/core/src/Dialog/__tests__/DialogSecondDocument.a11y.browser.spec.ts packages/core/src/Popover/__tests__/PopoverSecondDocument.a11y.chromium.spec.ts --project=chromium`: 27 passed (10 Dialog, 17 Popover).
- The Dialog spec with `--project=webkit` (WebKit 26.5): 7 passed, and the 3 Picture-in-Picture cases are skipped, since only Chromium has that window.
- A page with a same-origin, a cross-origin and an inline sheet, in Chromium and WebKit: only the cross-origin sheet throws on `cssRules`.
- The story typecheck (no errors in either story), the Storybook build, `pnpm check:repo`, ESLint and Prettier pass. Changeset coverage: nothing here ships to consumers.
- Prior art: searched all 596 open pull requests for changes to `adoptPageStyles`, `DialogSecondDocumentA11y.stories.tsx` and `PopoverSecondDocumentA11y.stories.tsx`: none touches either story or the helper.
cixzhang pushed a commit that referenced this pull request Oct 31, 2026
…8543)

CI note: this head's checks were blocked by the repository's Actions policy (no jobs ran since 17:43Z); they need a re-run.

## Why, what, how to check

**Why.** This comes from one product's effort to get its production JavaScript errors to zero: its log shows this one 12 times from 5 people in 7 days (9 on WebKit, 3 on Chrome). Pressing Escape inside an open popover throws it: the browser closes the popover and returns focus to its button, the tooltip there asks to open while the close still runs, and Chromium 151 and 156 refuse (149 does not). The tooltip stays closed.

**What led here.** The Popover API refuses a show while any popover shows or hides, and a hide returns focus inside that window. #6941 makes a show wait while `useLayer` runs its own show or hide; a close the browser runs itself (Escape, a tap outside) never entered that bookkeeping.

**Options.** (a) Catch the error and drop it: hides a real failure, and the tooltip still never opens. (b) Wait out every browser close before any show: tried first; it delayed a press that closes one menu and opens another, so focus no longer moved into the new menu. (c) Count the browser's close, try the show at once, retry after the close only if the browser refused. Chosen: it fixes the Escape case and keeps every other path as fast as before.

**What.** `useLayer` counts the browser's own popover closes in its ledger, from the close's start to its `toggle` event; a show refused during one replays after it, once.

**How to check.** Storybook `Core/Layer` → `BrowserHideWakesAFocusLayer`, Chromium 151+: Tab, Enter, Tab, Escape. Before: `InvalidStateError` in the console, no tooltip. After: no error, the tooltip shows.

## Expected behavior and authority

`architecture:layer-runtime` (current): browser-initiated closes are observed through the queued `toggle` event; that holds. Restored: #6941.

## Smallest restoration

- `popoverOperations.ts` holds the ledger `useLayer.tsx` kept privately, plus the browser-close count and the replay, tested alone there. No public API, default, record or visual change.

## Scope

- [x] One defect is restored.
- [x] Separable contradictory or unsettled tagalongs were removed or split.
- [x] No new public API, visual representation, default, or interaction model is hidden under the bug-fix label.
- [x] Public text and artifacts contain no internal Meta context.

## Testing

- Unit tests for Layer, its ledger, Tooltip, DropdownMenu, Popover, Drawer and Selector: 7 files, 652 passed. Without the fix, `useLayer.test.tsx` "defers the show a browser-run hide wakes…" and "keeps counting…" fail; with option (b), "opens a layer at once…" fails; `popoverOperations.test.ts` "ends each hide exactly once…" fails without `clearTimeout`.
- Type check, repository checks, lint, formatting: clean.
- Browser spec `LayerBrowserHide.a11y.chromium.spec.ts` (3 cases) on this branch's Storybook build: 3 passed. CI's Playwright runs Chromium 149, which allows these shows, so there the spec passes on main too. On Chromium 156 the story's steps throw `InvalidStateError … during another show operation` on main, tooltip hidden, and show it with no error here; a tap outside closes the layer with no error on both; the press that closes one layer and opens another focuses the new one at once.
- Open PRs #7732, #8381 and #8014 touch nothing under `packages/core/src/Layer/`; a trial merge with #7732 is clean; the other two conflict with main on their own.
cixzhang added a commit that referenced this pull request Oct 31, 2026
…ce and modality tracking

With #9139's INV16 on main, the runtime record owns two more concerns:
slot-presence (isRenderable, or a typeof ... !== 'boolean' check) and
modality-tracking (useInteractionModalityTracking, or a pointerdown or
keydown listener) both route INV16, beside interaction-modality's own
INV1-INV3 for modality.

Tests: #8236's Badge check routes INV16 naming isRenderable; #8381's diff
now also routes INV16.

This branch was successfully deployed

1 active deployment
Preview — 3b40c815 Deployed Oct 30, 2026 by vercel[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci:run A maintainer lets this outside contributor's pull request run CI (AST-030 FR17) CLA Signed This label is managed by the Meta Open Source bot.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants