diff --git a/packages/client/src/components/OriginalDialog.tsx b/packages/client/src/components/OriginalDialog.tsx index d00f4f2e0e..56125d169e 100644 --- a/packages/client/src/components/OriginalDialog.tsx +++ b/packages/client/src/components/OriginalDialog.tsx @@ -84,6 +84,25 @@ const escapeBelongsToPopup = (ownerDocument: Document): boolean => { return false; }; +const dialogEscapeHandlers = new WeakMap void>(); + +/** Visual order can differ from registration order while portals mount or animate out. */ +const frontmostDialog = (ownerDocument: Document): HTMLElement | null => { + const stackOrder = (element: HTMLElement): number => { + const zIndex = Number(ownerDocument.defaultView?.getComputedStyle(element).zIndex); + return Number.isNaN(zIndex) ? 0 : zIndex; + }; + return Array.from( + ownerDocument.querySelectorAll( + '[role="dialog"][data-state="open"], [role="alertdialog"][data-state="open"]', + ), + ).reduce( + (highest, candidate) => + highest == null || stackOrder(candidate) >= stackOrder(highest) ? candidate : highest, + null, + ); +}; + interface OGDialogProps extends DialogPrimitive.DialogProps { triggerRef?: React.RefObject; triggerRefs?: React.RefObject[]; @@ -239,9 +258,13 @@ const DialogContent: React.ForwardRefExoticComponent< const depth = React.useContext(DialogDepthContext); const contentZIndex = 140 + (depth - 1) * 60; const contentRef = React.useRef(null); + const closeOnEscapeRef = React.useRef<(event: KeyboardEvent) => void>(() => undefined); const composedRef = React.useCallback( (node: HTMLDivElement | null) => { + if (contentRef.current != null) dialogEscapeHandlers.delete(contentRef.current); contentRef.current = node; + if (node != null) + dialogEscapeHandlers.set(node, (event) => closeOnEscapeRef.current(event)); if (typeof ref !== 'function') { if (ref) { (ref as React.MutableRefObject).current = node; @@ -257,6 +280,7 @@ const DialogContent: React.ForwardRefExoticComponent< return undefined; } return () => { + if (node != null) dialogEscapeHandlers.delete(node); contentRef.current = null; (cleanup as () => void)(); }; @@ -271,14 +295,19 @@ const DialogContent: React.ForwardRefExoticComponent< * it, and the reader has to press it twice. * * A toast is transient status, not something the reader is working in, so - * the dialog takes Escape back while one is up. Scoped to exactly that - * case: with no toast on screen Radix's own arbitration is untouched, and - * only the frontmost dialog acts, so an inner dialog still closes alone. + * the dialog takes Escape back while one is up. This listener handles + * only the toast case; native dialog callbacks also verify visual ownership. * Closing goes through a hidden `Dialog.Close`, which drives Radix's own * close path and therefore works for controlled and uncontrolled dialogs * alike. */ const escapeFallbackRef = React.useRef(null); + closeOnEscapeRef.current = (event) => { + propsOnEscapeKeyDown?.(event); + if (event.defaultPrevented) return; + event.preventDefault(); + escapeFallbackRef.current?.click(); + }; React.useEffect(() => { const handleKeyDown = (event: KeyboardEvent) => { const content = contentRef.current; @@ -303,41 +332,8 @@ const DialogContent: React.ForwardRefExoticComponent< if (toast == null) { return; } - /** Read the RESOLVED z-index: dialogs outside this primitive carry - * theirs in a class (`ImagePreview` is `z-[250]`), and an inline-only - * reading scores those zero and mistakes the dialog underneath for the - * frontmost one. Ties fall to the later element, which is the one - * painted on top. */ - const stackOrder = (element: HTMLElement): number => { - const zIndex = Number(ownerDocument.defaultView?.getComputedStyle(element).zIndex); - return Number.isNaN(zIndex) ? 0 : zIndex; - }; - const frontmost = Array.from( - ownerDocument.querySelectorAll( - '[role="dialog"][data-state="open"], [role="alertdialog"][data-state="open"]', - ), - ).reduce( - (highest, candidate) => - highest == null || stackOrder(candidate) >= stackOrder(highest) ? candidate : highest, - null, - ); - if (frontmost !== content) { - return; - } - /** Only now, with this dialog established as the one the Escape belongs - * to. Every mounted dialog runs this listener, and calling a consumer's - * handler from the ones underneath would fire their side effects for - * someone else's keystroke — and a `preventDefault()` there would stop - * the frontmost dialog from closing at all. - * - * The consumer's own `onEscapeKeyDown` never ran: Radix calls it only - * for the highest layer, which the toast is. Give it the say it would - * have had, so a dialog that refuses to close on Escape still does. */ - propsOnEscapeKeyDown?.(event); - if (event.defaultPrevented) { - return; - } - escapeFallbackRef.current?.click(); + if (frontmostDialog(ownerDocument) !== content) return; + closeOnEscapeRef.current(event); }; document.addEventListener('keydown', handleKeyDown); return () => document.removeEventListener('keydown', handleKeyDown); @@ -348,11 +344,21 @@ const DialogContent: React.ForwardRefExoticComponent< that our tooltips be dismissable with Escape key) */ const handleEscapeKeyDown = React.useCallback( (event: KeyboardEvent) => { - if (escapeBelongsToPopup(document)) { + if (event.defaultPrevented) return; + const content = contentRef.current; + const ownerDocument = content?.ownerDocument ?? document; + if (escapeBelongsToPopup(ownerDocument)) { event.preventDefault(); return; } + const frontmost = frontmostDialog(ownerDocument); + const closeFrontmost = frontmost && dialogEscapeHandlers.get(frontmost); + if (frontmost != null && frontmost !== content) { + closeFrontmost?.(event); + event.preventDefault(); + return; + } propsOnEscapeKeyDown?.(event); }, [propsOnEscapeKeyDown], diff --git a/packages/client/src/components/__tests__/dialogToastEscape.spec.tsx b/packages/client/src/components/__tests__/dialogToastEscape.spec.tsx index 592cddb6f5..a231099208 100644 --- a/packages/client/src/components/__tests__/dialogToastEscape.spec.tsx +++ b/packages/client/src/components/__tests__/dialogToastEscape.spec.tsx @@ -1,8 +1,8 @@ import '@testing-library/jest-dom'; import userEvent from '@testing-library/user-event'; import * as RadixToast from '@radix-ui/react-toast'; -import { render, screen } from '@testing-library/react'; -import { OGDialog, OGDialogContent } from '../OriginalDialog'; +import { fireEvent, render, screen } from '@testing-library/react'; +import { OGDialog, OGDialogContent, OGDialogTitle, DialogLayer } from '../OriginalDialog'; /** * Radix hands Escape to the highest dismissable layer only, and a toast @@ -160,31 +160,36 @@ describe('dialog Escape', () => { /** A dialog that carries its z-index in a class — `ImagePreview` is * `z-[250]` — still outranks this one, so Escape there must not close the * dialog underneath it. */ - it('does not close a dialog ranked under a class-styled dialog above it', async () => { - const onOpenChange = jest.fn(); - render( - - - - - - - -
- -
- - Saved - - -
, - ); + it.each([false, true])( + 'does not close a dialog under an unregistered preview (toast: %s)', + async (toast) => { + const onOpenChange = jest.fn(); + render( + + + + + + + +
+ +
+ {toast && ( + + Saved + + )} + +
, + ); - screen.getByText('preview').focus(); - await userEvent.keyboard('{Escape}'); + screen.getByText('preview').focus(); + await userEvent.keyboard('{Escape}'); - expect(onOpenChange).not.toHaveBeenCalled(); - }); + expect(onOpenChange).not.toHaveBeenCalled(); + }, + ); it('closes the dialog while a toast is on screen', async () => { const onOpenChange = jest.fn(); @@ -206,3 +211,52 @@ describe('dialog Escape', () => { expect(onOpenChange).toHaveBeenCalledWith(false); }); }); + +it('consumes a fallback Escape before another listener can dismiss the dialog underneath', () => { + const onOpenChange = jest.fn(); + render(); + const inside = screen.getByText('inside the dialog'); + inside.focus(); + const escape = new KeyboardEvent('keydown', { key: 'Escape', bubbles: true, cancelable: true }); + fireEvent(inside, escape); + expect(onOpenChange).toHaveBeenCalledTimes(1); + expect(onOpenChange).toHaveBeenCalledWith(false); + expect(escape.defaultPrevented).toBe(true); +}); + +it.each([false, true])( + 'routes Escape to the visible top dialog (consumer prevents close: %s)', + async (preventClose) => { + const outerClose = jest.fn(); + const innerClose = jest.fn(); + const lowerEscape = jest.fn(); + const upperEscape = jest.fn((event: KeyboardEvent) => { + if (preventClose) event.preventDefault(); + }); + render( + <> + + + + Document preview + + + + + + + Your files + + + + , + ); + screen.getByText('nested preview').focus(); + await userEvent.keyboard('{Escape}'); + expect(upperEscape).toHaveBeenCalledTimes(1); + expect(lowerEscape).not.toHaveBeenCalled(); + if (preventClose) expect(innerClose).not.toHaveBeenCalled(); + else expect(innerClose).toHaveBeenCalledWith(false); + expect(outerClose).not.toHaveBeenCalled(); + }, +);