Skip to content

fix(dialog): close only the top-most modal on Escape (shared escape stack) - #4865

Closed
freddymeta wants to merge 1 commit into
mainfrom
fix/dialog-escape-stack
Closed

freddymeta wants to merge 1 commit into
mainfrom
fix/dialog-escape-stack

Conversation

@freddymeta

Copy link
Copy Markdown
Contributor

The bug

Pressing Escape inside a modal that was opened from within another modal closes both modals (and the same for a Sheet opened over a Modal, etc.).

Astryx already has top-most-only Escape dismissal — but only for focus-trap overlays (Popover, menus) via useFocusTrap's shared escape stack. Dialog (which backs Modal and the Sheet/drawer variant) takes a separate path: it uses the native <dialog> element and attaches its own keydown listener. That listener:

  1. never calls stopPropagation(), and
  2. only reads the focus-trap escape state (hasActiveFocusTrapEscape()) to defer to a popover on top — it never registers itself.

So when Modal L1 is opened from inside Modal L0, L1's <dialog> is a DOM descendant of L0's. An Escape inside L1 → L1's handler closes it, then the event bubbles to L0's handler, which also sees "no focus-trap on top" and closes too. Dialog-on-dialog had no coordination at all.

The fix

Extract the escape-stack coordination that already lived inside useFocusTrap — the push/pop registry and the DOM-containment top-most resolver — into a small shared hook, useEscapeStack, and have both overlay families register on it:

  • useFocusTrap (Popover, menus) now consumes useEscapeStack internally — behavior unchanged.
  • Dialog registers its <dialog> on the same stack, gates both its keydown handler and its native cancel handler on isTopmost(), and stopPropagation()s when it handles the press.

Result: one Escape press dismisses exactly one layer — the top-most — whether the top is a popover, a menu, or another modal. Top-most is resolved by DOM containment (correct even when an inner and outer overlay mount in the same commit, where React runs the child effect first). One stack and one resolver now serve the whole overlay family, which is the maintenance win — no parallel escape logic to keep in sync.

// before: two nested Modals both close on one Escape
// after: only the inner Modal closes; the outer stays open

Why a shared hook (not duplicating logic in Dialog)

The two primitives have very different event models (a focus trap listening on document vs. a native <dialog>'s keydown/cancel), but the coordination — who's on top, who handles Escape — is identical. Keeping it in one place means there's a single source of truth for top-most-only dismissal across every overlay.

Tests

  • New modal-in-modal regression test in Dialog.test.tsx: an Escape fired from inside a DOM-nested inner dialog closes only the inner one, and a follow-up asserts the outer closes once it's top-most. I verified this test fails on the pre-fix behavior (it reports the outer being closed too), so it's a real guard.
  • All existing Dialog, Popover, and useFocusTrap Escape tests pass unchanged (97 across the three suites, incl. useFocusTrap's own nested-trap coordination and the popover-falls-through-to-Dialog case).

Notes

  • No API change. hasActiveFocusTrapEscape is kept as a back-compat alias of the renamed hasActiveEscapeLayer.
  • useEscapeStack, hasActiveEscapeLayer, and isImeKeyEvent are exported from @astryxdesign/core (via hooks), so other overlays that manage their own Escape can join the same stack.
  • Typecheck, strict ESLint, and repo guardrails (sync-exports/changesets/boundaries) all clean.

…cape stack

An Escape pressed inside a modal opened FROM another modal closed BOTH. Each
open <dialog> attached its own keydown listener and none stopped propagation,
so the inner dialog closed and the event then bubbled to the DOM-nested outer
dialog and closed it too. Dialog also only read the focus-trap escape state to
defer to a popover on top — it never registered itself, so dialog-on-dialog had
no coordination at all.

Extract the escape-stack coordination (push/pop + DOM-containment top-most
resolver) that lived inside useFocusTrap into a shared useEscapeStack hook, and
have BOTH useFocusTrap (Popover, menus) and Dialog (Modal, Sheet) register on
it. Only the top-most layer handles Escape and stops propagation, so a single
press dismisses one layer whether the top is a popover or another modal. Keeps
one stack and one resolver for the whole overlay family (maintenance win).

- New packages/core/src/hooks/useEscapeStack.ts (shared stack + hasActiveEscapeLayer + isImeKeyEvent).
- useFocusTrap consumes it; behavior unchanged (16 focus-trap tests green, incl nested-trap Escape).
- Dialog registers its <dialog>, gates keydown + native cancel on isTopmost(), and stopPropagation()s.
- hasActiveFocusTrapEscape kept as a back-compat alias.
- Adds a modal-in-modal regression test (verified it fails on the pre-fix behavior).
- No API change.
@vercel

vercel Bot commented Aug 10, 2026

Copy link
Copy Markdown

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

1 Skipped Deployment
Project Deployment Actions Updated (UTC)
astryx Ignored Ignored Aug 10, 2026 1:59pm

Request Review

@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Aug 10, 2026
@github-actions github-actions Bot added community Authored by a community contributor (not on the eng/design team) needs:code-review High-risk change (new package/component/API) — needs human code review before merge labels Aug 10, 2026
@github-actions

Copy link
Copy Markdown
Contributor

PR Analysis Report

📚 Storybook Preview

View Storybook for this PR
GitHub Pages may take up to a minute to hydrate after deploy.

🧪 Sandbox Preview

View Sandbox for this PR
GitHub Pages may take up to a minute to hydrate after deploy.

Modified Components

Dialog (@astryxdesign/core) · View in Storybook
Metric Before After Delta
Bundle Size (ESM) N/A N/A N/A
Lines of Code N/A 640 -
Complexity N/A Very High (82) -
Popover (@astryxdesign/core) · View in Storybook
Metric Before After Delta
Bundle Size (ESM) N/A N/A N/A
Lines of Code N/A 540 -
Complexity N/A Very High (51) -

Bundle Size Summary

Package Size (ESM) Size (CJS) Gzipped
@astryxdesign/core N/A 4.7KB 1.2KB

Accessibility Audit

Status: No accessibility violations detected.


Generated by PR Enrichment workflow | Storybook | Sandbox | View full report

github-actions Bot added a commit that referenced this pull request Aug 10, 2026
cixzhang added a commit that referenced this pull request Aug 17, 2026
`handleCancel` became a bare `preventDefault()` when Dialog moved onto the
shared dismissal stack, so a dismissal the browser starts on its own — the
Android back gesture, the platform close watcher — stopped closing a modal
at all. Escape presses the stack owns never reach `cancel` (the stack
preventDefault()s those), so this path only ever sees the dismissals the
stack did not route, and dropping it silently lost them.

The cancel handler now answers with the stack's own ordering: still always
`preventDefault()`, so the browser cannot close a controlled `<dialog>`
behind React's back, but dismiss when this dialog is `isTopmost()` and
Escape-dismissible. Approach carried from #4865, adapted from its
`useEscapeStack` to `layerStack`/`useLayerDismissal`.

Also carries #4865's Dialog-level modal-in-modal Escape test — the only real
`Dialog` mount guarding nested dismissal in either PR; the stack's own tests
are all synthetic layers. It fails against the pre-stack Dialog handler
(outer closes too) and passes here, alongside two `cancel` tests, top-most
and not.

Co-authored-by: Freddy Kusnadi Tan <[email protected]>
@cixzhang

Copy link
Copy Markdown
Contributor

Thanks for this — the modal-in-modal repro and the containment resolver are spot on. Two came in for the same bug and we're going with #4881, since it takes every overlay type onto one stack. Your cancel gate and your Dialog-level Escape test are both in it, credited.

[Reviewed by Robohands and Cindy]

@cixzhang cixzhang closed this Aug 19, 2026
@github-actions
github-actions Bot deleted the fix/dialog-escape-stack branch August 19, 2026 06:11
cixzhang added a commit that referenced this pull request Aug 24, 2026
`handleCancel` became a bare `preventDefault()` when Dialog moved onto the
shared dismissal stack, so a dismissal the browser starts on its own — the
Android back gesture, the platform close watcher — stopped closing a modal
at all. Escape presses the stack owns never reach `cancel` (the stack
preventDefault()s those), so this path only ever sees the dismissals the
stack did not route, and dropping it silently lost them.

The cancel handler now answers with the stack's own ordering: still always
`preventDefault()`, so the browser cannot close a controlled `<dialog>`
behind React's back, but dismiss when this dialog is `isTopmost()` and
Escape-dismissible. Approach carried from #4865, adapted from its
`useEscapeStack` to `layerStack`/`useLayerDismissal`.

Also carries #4865's Dialog-level modal-in-modal Escape test — the only real
`Dialog` mount guarding nested dismissal in either PR; the stack's own tests
are all synthetic layers. It fails against the pre-stack Dialog handler
(outer closes too) and passes here, alongside two `cancel` tests, top-most
and not.

Co-authored-by: Freddy Kusnadi Tan <[email protected]>
cixzhang added a commit that referenced this pull request Aug 24, 2026
* feat(core): one shared dismissal stack for every overlay layer

Every overlay owned its own Escape listener, so one press could dismiss
two layers — a popover and the Dialog hosting it, or a modal and the
modal it was opened from. Patching that per primitive had already
produced parallel registries (the focus-trap Escape stack, Drawer's LIFO
registry, useScrollLock's counter). This is the single registry those
collapse into, per the plan in #3343.

- `useLayerDismissal` registers a layer while it is active; `layerStack`
  owns ONE document listener and routes each press to the top-most
  layer. Layers no longer listen, so there is no stopPropagation
  choreography between element- and document-level handlers to keep in
  sync.
- One press dismisses exactly one layer, with no per-component
  exceptions. `escapeBehavior` is `close` (default) or `block` — a
  `required` Dialog swallows the press without closing, so nothing
  behind it dismisses either.
- Top-most is resolved from React-tree nesting via `LayerDepthProvider`,
  which survives portals and is fixed during render, so an inner and
  outer layer that mount in the same commit order correctly. DOM
  containment remains a tie-break for bare focus traps, which render
  nothing and so cannot provide depth. Nothing is mounted at the app
  root: the context defaults to 0 and each layer provides depth for its
  own content.
- Presence is asked at press time, not inferred from registration.
  Hover layers register for their lifetime because their open state lags
  the DOM by a frame, and answer presence from the DOM instead — so an
  idle tooltip in the tree never claims an Escape.
- The stack calls preventDefault on presses it handles, suppressing the
  browser's own close-watcher so native and JS cannot both act. One code
  path covers modal `<dialog>`, non-modal `show()`, `popover="auto"` and
  `popover="manual"` alike.

Fixes two live bugs: a Tooltip inside a Dialog closed the Dialog instead
of the tip, and useHoverCard's trigger listener called stopPropagation on
ANY Escape while merely focused, silently eating presses meant for a
host Dialog.

Verified in Chromium against four new stories — modal-in-modal,
popover-in-modal, hover-tip-in-modal (both showing and idle), and
required-blocks-Escape — plus 15 unit tests, typecheck, eslint and
check:repo.

* fix(storybook): use the supporting text type in the layer-dismissal story

`caption` is not a built-in `TextType` — it only appears as an example of a
theme-augmented custom type in the CustomTextTypes JSDoc — so the storybook
typecheck failed the build-storybook job. `supporting` is the built-in that
carries the intended meaning: 12px (--text-supporting-size) and secondary
color by default, i.e. the system's de-emphasized note under a line of body
text.

* fix(core): a browser-initiated dismissal closes the top-most Dialog

`handleCancel` became a bare `preventDefault()` when Dialog moved onto the
shared dismissal stack, so a dismissal the browser starts on its own — the
Android back gesture, the platform close watcher — stopped closing a modal
at all. Escape presses the stack owns never reach `cancel` (the stack
preventDefault()s those), so this path only ever sees the dismissals the
stack did not route, and dropping it silently lost them.

The cancel handler now answers with the stack's own ordering: still always
`preventDefault()`, so the browser cannot close a controlled `<dialog>`
behind React's back, but dismiss when this dialog is `isTopmost()` and
Escape-dismissible. Approach carried from #4865, adapted from its
`useEscapeStack` to `layerStack`/`useLayerDismissal`.

Also carries #4865's Dialog-level modal-in-modal Escape test — the only real
`Dialog` mount guarding nested dismissal in either PR; the stack's own tests
are all synthetic layers. It fails against the pre-stack Dialog handler
(outer closes too) and passes here, alongside two `cancel` tests, top-most
and not.

Co-authored-by: Freddy Kusnadi Tan <[email protected]>

* fix(core): keep a layer's place in the dismissal order across re-registration

registerLayer handed out a fresh seq on every registration, and
useLayerDismissal re-registers whenever escapeBehavior or depth changes.
So a Dialog whose `purpose` flipped between info and required while open
jumped ahead of same-depth layers that had opened after it, and one
Escape closed the wrong one — or, flipping the other way, closed nothing
because the promoted layer swallowed the press.

seq now hangs off the entry's token, which useLayerDismissal already
keeps stable across re-registration, so it is assigned once per layer
identity. That also makes StrictMode's double-invoked effects stop
burning a second seq per layer (they never reordered anything, since the
double invoke preserves relative order, but the numbers moved).

* fix(core): keep hasActiveFocusTrapEscape trap-only

The shim went public in 0.4.2 meaning 'an Escape-dismissible focus trap
is active' — `escapeStack.length > 0`, and only `useFocusTrap` ever
pushed there. Rewriting it over `hasOpenLayer()` silently widened that
to 'any layer is present'. BottomSheetSwitcher.tsx gates its own
dismissal on it, so the sheet stopped closing whenever a tooltip, hover
card or dialog was up.

It counts Escape-dismissible traps again. The count is driven by the
same expression that registers the trap on the stack, so the two cannot
disagree about whether this trap is active.

* fix(core): Lightbox and MobileNav join the shared dismissal stack

Both closed on the native `cancel` event alone, so neither was on the
stack. The stack preventDefault()s every press it handles, and a
`required` Dialog registers with `block` — so once one of those was
open, an Escape aimed at a Lightbox or MobileNav sitting above it was
swallowed and never reached their cancel handler. On main the same press
got through, because Dialog listened on the <dialog> ELEMENT and focus
inside the layer above meant its handler never ran.

Registering them is the fix rather than letting the stack fall through
when nothing claims a press: the point of one stack is that every
overlay family is in it, and a fall-through would hand the press back to
the browser's close watcher, which reaches only whichever families
happen to be native <dialog> or popover=auto — so the same press would
still be lost for anything else, and a `block` layer could no longer
promise that nothing behind it moves.

Their `cancel` handlers stay for the dismissals the browser starts
itself — the Android back gesture, the platform close watcher — gated on
isTopmost() like Dialog's, so a back gesture still closes the top-most
layer and only that one. Escape presses the stack owns never reach
cancel, so nothing dismisses twice.

Also drops layerStack's now-unused hasOpenLayer(): with these two
registered it has no caller, and 'is anything open' is exactly the
question that produced the bug above it.

* test(core): cover the two families the stack was missing

Four Chromium-verified cases as stories — a Lightbox and a MobileNav
over a required Dialog, and each alone — plus a non-modal bottom sheet
with a hover tip showing, which is what the widened
hasActiveFocusTrapEscape broke.

* fix(core): an IME Escape cancels the composition, not the layer

A CJK user pressing Escape to back out of a half-formed character lost the
whole layer, and everything already typed into it. The stack guarded the
composing keydown — but only by returning, which is measurably the same as no
guard at all: an unclaimed Escape is exactly what makes the browser raise its
own close request, and that request arrives at Dialog's `cancel` handler,
which has no composition state to read and dismisses on the same keypress.

- layerStack claims the composing Escape (`preventDefault`) before standing
  down, so no close request follows. It claims only while a layer is actually
  on screen; with nothing to protect, the press is not ours to take.
- Close requests that arrive with no keydown to read — the Android back
  gesture, the platform close watcher, or a composing Escape that content
  stopped before it reached the stack — are answered with
  `shouldDismissOnCloseRequest()`, which adds "not mid-composition" to the
  existing top-most rule. Dialog, Lightbox and MobileNav ask it from their
  `cancel` handlers instead of `isTopmost()`, so the policy lives in the stack
  rather than in three copies.
- The stack tracks composition from document-level composition events, since
  the DOM offers no way to ask; a blur clears it too, so a compositionend it
  never sees cannot leave the flag stuck on.

useFocusTrap needs nothing — it claims only Tab and renders no element with a
close watcher — and now says so where the next person will look.

Measured in Chromium with a real Hangul composition driven through CDP
(Input.imeSetComposition), against Dialog, AlertDialog and a modal-in-modal,
plus the two close-request paths. Before: 1 layer lost on every row. After: 0,
with the composition still standing in the field. Plain Escape is unchanged on
all seven regression rows — one press, exactly one layer, and a `required`
dialog still blocks.

* test(core): pin the dismissal invariant against real overlays

Asserts which layers are still on screen after one Escape rather than
which dismiss handler ran: a spy passes when the stack routes to the
wrong layer, an open-dialog census does not. Adds the cases nothing
covered — three deep, teardown leaving the stack clean, a required
Dialog that must not block a layer above it, and presence asked at
press time — plus stories for three-deep and a purpose flip while open.

Drops isTopmost and useLayerDepth from the public surface: neither has
a caller, and everything reachable from @astryxdesign/core/Layer is
permanent.

* test(storybook): open the second modal from inside the first in the purpose-flip story

A modal makes everything outside it inert, so the trigger for the second
modal has to live in the first one's content or it can never be reached.

* fix(lab): InfoTip lets the shared stack take Escape

InfoTip stopPropagation()'d Escape at its trigger button, so the press
never reached the dismissal stack -- but the browser's own close watcher
still fired cancel on an enclosing Dialog, and one press took the tip and
the dialog with it (#5168). The trigger now handles no keys of its own;
the Tooltip it renders is already on the stack and takes the press.

Measured in Chromium: before, one Escape over an open tip inside a Dialog
leaves nothing on screen; after, the tip hides and the Dialog stands, and
a second Escape closes it.

* docs(core): say which layers are on the dismissal stack and what the rest cost

The hook's docblock listed 'Bottom Sheet' among the registered layers -- the
standalone BottomSheet is not one; only BottomSheetSwitcher is focus-trapped.
It also warned about InfoTip, which now defers to its Tooltip's entry.

Replaced with the measured picture: who registers, who still self-handles, why
that is safe next to the stack (they claim the press at element level and the
stack honours defaultPrevented), and the one thing it still costs -- a
registered layer opened inside an unstacked host never gets the press.

* fix(core): HoverCard content lets the shared stack take Escape

The card's content wrapper still ran its own Escape handler with a bare
stopPropagation(). That kept the press from the dialog's own listener but
not from the browser's close watcher, so a keyboard user who tabbed into a
HoverCard inside a Dialog pressed Escape once and lost both.

The card is already on the dismissal stack; its onDismiss now also returns
focus to the trigger, which is the only thing the local handler did that
the stack did not. Measured in Chromium on a real HoverCard inside a real
Dialog, focus on a button inside the card: before, one Escape leaves nothing
on screen; after, the card hides, the dialog stands and focus is back on the
trigger. Same on the trigger-focused path, which was already correct.

The docblock now names BottomSheetSwitcher's split behaviour precisely.

* fix(core): a HoverCard only reclaims focus when it had it

The onDismiss added in the previous commit refocused the trigger and armed
the re-show guard on every stack-driven dismissal. The handler it replaced
could only ever run with focus already inside the card, so that widened two
things:

- a card showing on hover while the user types elsewhere dragged their caret
  onto the trigger on Escape; main left the field alone
- on the keyboard path focus is already on the trigger, so focus() is a
  no-op, no focusin fires, and nothing clears isEscapeDismissingRef -- the
  next time they tabbed back the card refused to open

Both are gated on the card actually containing the active element, which is
what the two old handlers did between them. Measured in Chromium against
main: typing elsewhere, focus stays in the field; tab away and back after an
Escape, the card opens again; focus inside the card, it returns to the
trigger and the host dialog stands.

* fix(core): a controlled HoverCard stays off the dismissal stack

A hover card whose visibility is the consumer's `isOpen` cannot be dismissed
by the stack -- so it must not consume the press either. It did: pinned open
inside a Dialog, it took every Escape and acted on none, and the dialog could
not be closed from the keyboard at all. Measured in Chromium: three presses,
nothing moved.

Tooltip already opts out for exactly this reason (useTooltip.tsx:556) with the
rationale written out; this is the same line in the sibling that was missed.
After: one Escape closes the modal and leaves the pinned card alone.

No unit test: jsdom cannot answer `:popover-open`, so the card's presence
probe reads false there and the stack routes to the dialog whether the opt-out
is present or not -- the test passes with the fix reverted. Pinned instead by
the new PinnedHoverCardInModal story and the Chromium row in the description.

* docs(core): a controlled hover layer stops taking Escape

isOpen on a Tooltip or HoverCard now turns off Escape dismissal, and the
prop docblock listed three behaviors without saying so -- someone pinning a
card with interactive content inside a Dialog would find Escape closing the
Dialog and nothing they could read said it would.

useLayerDismissal's isEnabled docblock named only Dialog's inline mode as the
case it exists for; controlled hover layers are the second.

* docs(core): put the controlled-Escape note on the component props too

The note landed on TooltipOptions/HoverCardOptions, but a builder writing
<HoverCard isOpen> hovers the component prop, not the hook option -- which is
what the PR's own pinned story does.

* docs(changeset): record that a window Escape listener now sees the press

The stack claims a press with preventDefault() but leaves propagation alone
on purpose, so a keydown listener on window sees an Escape that a focus-
trapped layer used to stop. Measured: none on main, one here, with
defaultPrevented already true. Anyone listening at that level needs to know.

* fix(storybook): make the purpose-flip story drivable

'Make first required' sat in the first modal, which is inert once the
second is open -- so the story could not be driven the way its own copy
reads. Moved into the second modal.

Driven in Chromium: flip while both are open, one Escape closes the
second (the re-registered first does not overtake it), a second Escape
leaves the required first standing.

* docs(core): say what seq actually orders, and drop roadmap from a story

seq's docblock said 'monotonic open order'. True for a layer that registers
when it opens; a hover layer registers at mount and answers isPresent, so for
two of those it is mount order. Measured: with a focus-shown tip and a
hover-shown tip both up, one Escape takes the earlier-mounted one. Strictly
better than main, which took both -- the comment overstated, the code did not.

The sheet story's copy told the reader our migration plan. The caller-facing
fact stays, the roadmap goes; Scope / follow-ups already carries it.

* docs(core): seq is registration order, said the same way in all three places

Two comments still called it 'open order' after the field's own docblock
stopped. Also names the consequence the ordering rule has and the field's
docblock does not: a layer keeps its place for as long as its identity
lives, so one that closes and reopens does not move to the top.

* docs(changeset): say identity, not 'when it opens'

The code keys order to the layer's identity; 'fixed when it opens' is true
for the re-registration case the sentence is about but not in general, and
the body's Known edges already carries the precise version.

* chore(changeset): classify the dismissal stack as breaking

A window keydown listener now sees an Escape that a focus-trapped layer
used to stop, and the change adds useLayerDismissal and escapeBehavior as
public surface. [fix] was the one category it could not be.

* feat(core)!: controlled hover layers follow control state on Escape

A controlled Tooltip or HoverCard used to opt out of the dismissal stack
entirely, so its Escape fell through and closed the Dialog underneath.
It now stays registered, takes the press when it is top-most, and answers
by calling onOpenChange(false) rather than hiding itself — whether it
closes is the caller's update to make, exactly as for a controlled Dialog.

A controlled close now restores focus to the trigger when the card held
it; without that the consumer's own state flip stranded focus on <body>.

---------

Co-authored-by: Freddy Kusnadi Tan <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

CLA Signed This label is managed by the Meta Open Source bot. community Authored by a community contributor (not on the eng/design team) needs:code-review High-risk change (new package/component/API) — needs human code review before merge

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants