Repository navigation
fix(dialog): close only the top-most modal on Escape (shared escape stack) - #4865
Closed
freddymeta wants to merge 1 commit into
Closed
freddymeta wants to merge 1 commit into
freddymeta wants to merge 1 commit into
Conversation
…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.
|
The latest updates on your projects. Learn more about Vercel for GitHub. |
Contributor
PR Analysis Report📚 Storybook PreviewView Storybook for this PR 🧪 Sandbox PreviewView Sandbox for this PR Modified ComponentsDialog (@astryxdesign/core) · View in Storybook
Popover (@astryxdesign/core) · View in Storybook
Bundle Size Summary
Accessibility AuditStatus: No accessibility violations detected. Generated by PR Enrichment workflow | Storybook | Sandbox | View full report |
This was referenced Aug 11, 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]>
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
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]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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 ownkeydownlistener. That listener:stopPropagation(), andhasActiveFocusTrapEscape()) 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 consumesuseEscapeStackinternally — behavior unchanged.Dialogregisters its<dialog>on the same stack, gates both itskeydownhandler and its nativecancelhandler onisTopmost(), andstopPropagation()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.
Why a shared hook (not duplicating logic in Dialog)
The two primitives have very different event models (a focus trap listening on
documentvs. a native<dialog>'skeydown/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
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.useFocusTrapEscape tests pass unchanged (97 across the three suites, incl.useFocusTrap's own nested-trap coordination and the popover-falls-through-to-Dialog case).Notes
hasActiveFocusTrapEscapeis kept as a back-compat alias of the renamedhasActiveEscapeLayer.useEscapeStack,hasActiveEscapeLayer, andisImeKeyEventare exported from@astryxdesign/core(viahooks), so other overlays that manage their own Escape can join the same stack.