👯 fix: Collapse Radix Layer Packages to One Copy (#15742)

* 🧬 fix: Collapse Radix Layer Packages to One Copy

Radix coordinates nested layers and focus scopes through module-level state,
so a dialog and a popover inside it cooperate only while they import the same
copy of `react-dismissable-layer` / `react-focus-scope`. This tree had four
and three of them:

  dialog -> react-dialog/node_modules/…  1.0.2   (exact pin)
  select -> react-select/node_modules/…  1.1.10
  menu   -> react-menu/node_modules/…    1.1.0
  hover  -> hoisted                      1.0.5

Split that way, a popover never learns the dialog disabled body pointer
events and the dialog's focus trap is never paused, so in-dialog selects and
hover cards are inert and keyboard-dead (#15738). The exact `1.0.2` pin on
`react-dialog` and `react-alert-dialog` came from #11023, which downgraded
them from ^1.1.15 to fix modal tooltip and dropdown regressions — the same
split seen from the other side, when the dialog was the new package and
everything else was old.

Unpinning both and refreshing the other Radix packages inside their existing
carets collapses the tree to one copy of each. No `overrides` entry: the
resolution stands on its own, and pinning transitive versions would only hide
the next split. `radixLayers.spec.ts` reads the lockfile and fails if either
package is ever nested again; `dialogPopoverFocus.spec.tsx` asserts the
behaviour that invariant exists for — a portaled option holding focus inside
a dialog, which fails on the old tree and passes on this one.

Verified with a real install in a worktree: one copy of each resolved from
dialog, select and hover-card alike; `packages/client` 46 suites / 476 tests
and `client` 323 suites / 3201 tests green; both workspaces typecheck.

Needs a manual pass over the app's modals before merge — what #11023 was
guarding cannot be proven by jsdom.

* 🍞 fix: Give Escape Back to the Dialog Under a Toast

Radix routes Escape to the highest dismissable layer only, and `Toast.Root`
registers one — mounted after whatever dialog is already open. Splitting
`react-dismissable-layer` into per-package copies hid this: toasts and dialogs
were never in the same stack. Collapsing them to one copy puts a status toast
above every open dialog, and it eats the Escape meant for the dialog beneath.

Measured in the running app (mock e2e, instrumented): the dialog's own
`onEscapeKeyDown` was never called, the layer above it was
`<li class="toast-root" data-radix-collection-item>`, and a SECOND Escape
closed the dialog. That is `agent-skills.spec.ts:709`, which failed
deterministically here across three attempts.

The frontmost open dialog now takes Escape back while a toast is present,
closing through a hidden `Dialog.Close` so controlled and uncontrolled dialogs
behave alike. Scoped tightly: no toast on screen leaves Radix's arbitration
untouched, and only the frontmost dialog acts, so an inner dialog still closes
alone.

The toast is matched whatever its `data-state`. A toast that has begun closing
keeps its layer registered until the exit animation ends, and that is exactly
the case that failed — the first attempt keyed on `[data-state="open"]` and
missed it, which the instrumentation caught (`FB toast= null allLis= 1`).

`agent-skills.spec.ts` now passes locally on the deduped tree: 4 passed.
Regression test verified to fail with the fix reverted.

* 🚪 fix: Close the MCP Menu With the Dialog It Opened

Ariakit takes Escape for a menu only when the event target is the menu, its
trigger, or `body`:

    if (event.key !== "Escape") return;
    if (event.defaultPrevented) return;
    ...
    if (isElement(target) && target.tagName === "BODY") return true;
    if (contains(dialog, target)) return true;
    if (contains(disclosureElement, target)) return true;
    return false;                                  // ariakit dialog.tsx:496-517

While the MCP config dialog holds focus none of those is true, so the Escape
that closes the dialog leaves the menu open behind it — and `disabled={isOpen}`
on the trigger then makes it unclickable. The reader is stranded with a menu
they cannot reach and a button they cannot press; `mcp-oauth-readiness` times
out clicking it, three tests over.

Keyed on the dialog CLOSING, not opening. The first attempt closed the menu as
the dialog opened and broke a fourth test that reads the server rows from the
still-mounted menu underneath (`unmountOnHide` deletes them):
`element(s) not found`. Closing on the way back out leaves that untouched.

Local mock e2e on the deduped tree: `mcp-oauth-readiness` 5 passed (was 2/5),
`agent-skills` + `mcp` 5 passed, `client` 3204 tests green, typecheck clean.

* 🛡️ fix: Keep the Escape Fallback Inside Its Lane

Codex found three, all real.

**P1 — the fallback overruled the guards it should obey.** Any Escape while a
toast was up clicked the dialog's close button, including when a select inside
the dialog owned that Escape (WCAG 2.1.1) or when another layer had already
answered it. A reader closing a listbox would have lost the whole dialog and
anything unsaved in it. It now bails on `event.defaultPrevented` and on the
same popup conditions the Radix-provided handler honours — extracted into one
`escapeBelongsToPopup` helper both call, so they cannot drift apart.

**P2 — the frontmost check read inline z-index only.** `ImagePreview` is a raw
`DialogPrimitive.Content` carrying `z-[250]` as a CLASS, so it scored zero and
the My Files dialog underneath was mistaken for the frontmost — Escape in the
preview would have closed it too. Ranking now reads the resolved
`getComputedStyle().zIndex`.

**P2 — the published contract did not carry the singleton.** `@librechat/client`
still admitted `react-toast@1.1.5` and `react-popover@1.0.7`, which depend on
the older dismissable-layer/focus-scope line, so a consumer could reassemble
the very split this PR removes. Radix minimums raised to the versions the
lockfile resolves; the tree still holds exactly one copy of each.

Three regression tests, each verified to fail against the pre-fix component.
`packages/client` 484 tests, `client` 3204 tests, both typecheck clean, local
mock e2e `agent-skills` + `mcp-oauth-readiness` 9 passed.

* 🎚️ fix: Let the Consumer and the Alert Dialog Have Their Say

Two more from codex, both real.

The fallback never ran the dialog's own `onEscapeKeyDown`. Radix calls that
only for the highest layer, which the toast is — so a dialog whose consumer
cancels Escape (`event.preventDefault()`) closed anyway, taking whatever was
in it. The fallback now invokes the supplied handler and honours the
cancellation, exactly as the Radix path does.

The frontmost ranking looked only for `role="dialog"`. `OGDialogContent` is
also used as an alert dialog — the shared-link delete confirmation
(`SharedLinkButton.tsx:426`) — so its content was never found, `frontmost`
stayed null, and the fallback declined to act: that confirmation still needed
two Escapes. Alert dialogs are ranked too.

Two more regression tests, both verified to fail against the previous version.
`packages/client` 486 tests, `client` 3204 tests, typecheck and static checks
clean.
This commit is contained in:
Danny Avila 2026-09-08 16:00:27 -04:00 • committed by GitHub
parent 5020dbd230
commit fd229fe478
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
8 changed files with 1144 additions and 1997 deletions

View file

@ -40,24 +40,24 @@
"@marsidev/react-turnstile": "^1.1.0",
"@mcp-ui/client": "^5.7.0",
"@monaco-editor/react": "^4.7.0",
"@radix-ui/react-accordion": "^1.1.2",
"@radix-ui/react-alert-dialog": "1.0.2",
"@radix-ui/react-checkbox": "^1.0.3",
"@radix-ui/react-collapsible": "^1.0.3",
"@radix-ui/react-dialog": "1.0.2",
"@radix-ui/react-dropdown-menu": "^2.1.1",
"@radix-ui/react-hover-card": "^1.0.5",
"@radix-ui/react-accordion": "^1.2.20",
"@radix-ui/react-alert-dialog": "^1.1.23",
"@radix-ui/react-checkbox": "^1.3.11",
"@radix-ui/react-collapsible": "^1.1.20",
"@radix-ui/react-dialog": "^1.1.23",
"@radix-ui/react-dropdown-menu": "^2.1.24",
"@radix-ui/react-hover-card": "^1.1.23",
"@radix-ui/react-icons": "^1.3.0",
"@radix-ui/react-label": "^2.0.0",
"@radix-ui/react-popover": "^1.0.7",
"@radix-ui/react-popover": "^1.1.23",
"@radix-ui/react-progress": "^1.1.2",
"@radix-ui/react-radio-group": "^1.1.3",
"@radix-ui/react-select": "^2.0.0",
"@radix-ui/react-select": "^2.3.7",
"@radix-ui/react-separator": "^1.0.3",
"@radix-ui/react-slider": "^1.1.1",
"@radix-ui/react-switch": "^1.0.3",
"@radix-ui/react-tabs": "^1.0.3",
"@radix-ui/react-toast": "^1.1.5",
"@radix-ui/react-tabs": "^1.1.21",
"@radix-ui/react-toast": "^1.2.23",
"@react-spring/web": "^9.7.5",
"@tanstack/react-query": "^4.28.0",
"@tanstack/react-table": "^8.11.7",

View file

@ -1,4 +1,4 @@
import React, { memo, useMemo } from 'react';
import React, { memo, useRef, useMemo, useEffect } from 'react';
import * as Ariakit from '@ariakit/react';
import { ChevronDown } from 'lucide-react';
import { PermissionTypes, Permissions } from 'librechat-data-provider';
@ -17,6 +17,25 @@ function MCPSelectContent() {
const menuStore = Ariakit.useMenuStore({ focusLoop: true });
const isOpen = menuStore.useState('open');
const configDialogOpen = manager?.getConfigDialogProps()?.isOpen === true;
/**
* The menu closes with the dialog it launched. Ariakit only takes Escape for
* a menu when the event target is the menu, its trigger, or `body`, so while
* the config dialog holds focus the menu never sees it — the Escape that
* closes the dialog leaves the menu open behind it, and `disabled={isOpen}`
* then makes its trigger unclickable, stranding the reader
* (`mcp-oauth-readiness` e2e). Keyed on the dialog CLOSING, not opening: the
* menu stays mounted underneath while the dialog is up, which is where its
* server rows are read from.
*/
const configDialogWasOpen = useRef(false);
useEffect(() => {
if (configDialogWasOpen.current && !configDialogOpen) {
menuStore.hide();
}
configDialogWasOpen.current = configDialogOpen;
}, [configDialogOpen, menuStore]);
const selectedServers = useMemo(() => {
if (!manager?.mcpValues || manager.mcpValues.length === 0) {

2686
package-lock.json generated

File diff suppressed because it is too large Load diff

View file

@ -45,25 +45,25 @@
"@dicebear/collection": "^9.4.3",
"@dicebear/core": "^9.4.3",
"@headlessui/react": "^2.1.2",
"@radix-ui/react-accordion": "^1.2.11",
"@radix-ui/react-alert-dialog": "1.0.2",
"@radix-ui/react-checkbox": "^1.0.3",
"@radix-ui/react-collapsible": "^1.1.11",
"@radix-ui/react-dialog": "1.0.2",
"@radix-ui/react-dropdown-menu": "^2.1.1",
"@radix-ui/react-hover-card": "^1.0.5",
"@radix-ui/react-accordion": "^1.2.20",
"@radix-ui/react-alert-dialog": "^1.1.23",
"@radix-ui/react-checkbox": "^1.3.11",
"@radix-ui/react-collapsible": "^1.1.20",
"@radix-ui/react-dialog": "^1.1.23",
"@radix-ui/react-dropdown-menu": "^2.1.24",
"@radix-ui/react-hover-card": "^1.1.23",
"@radix-ui/react-icons": "^1.3.0",
"@radix-ui/react-label": "^2.1.7",
"@radix-ui/react-popover": "^1.0.7",
"@radix-ui/react-popover": "^1.1.23",
"@radix-ui/react-progress": "^1.1.2",
"@radix-ui/react-radio-group": "^1.3.7",
"@radix-ui/react-select": "^2.2.5",
"@radix-ui/react-select": "^2.3.7",
"@radix-ui/react-separator": "^1.1.7",
"@radix-ui/react-slider": "^1.3.5",
"@radix-ui/react-slot": "^1.0.0",
"@radix-ui/react-switch": "^1.2.5",
"@radix-ui/react-tabs": "^1.0.3",
"@radix-ui/react-toast": "^1.1.5",
"@radix-ui/react-tabs": "^1.1.21",
"@radix-ui/react-toast": "^1.2.23",
"@rc-component/mini-decimal": "^1.0.1",
"@react-spring/web": "^10.0.1",
"@tanstack/react-query": "^4.28.0 || ^5.0.0",

View file

@ -44,6 +44,34 @@ export const useNestedPopoverStyle = (): React.CSSProperties | undefined => {
return depth > 0 ? { zIndex, pointerEvents: 'auto' } : undefined;
};
/**
* Whether Escape belongs to something inside the dialog rather than the dialog
* itself: a trigger whose popover is open, focus inside a menu/listbox/combobox,
* or a tooltip. WCAG 2.1.1 wants those dismissable on their own, so the first
* Escape closes them and the dialog stays put.
*/
const escapeBelongsToPopup = (ownerDocument: Document): boolean => {
const activeElement = ownerDocument.activeElement;
if (activeElement?.getAttribute('aria-expanded') === 'true') {
return true;
}
const popovers = ownerDocument.querySelectorAll(
'[role="menu"], [role="listbox"], [role="combobox"]',
);
for (const popover of popovers) {
if (popover.contains(activeElement)) {
return true;
}
}
const tooltips = ownerDocument.querySelectorAll('.tooltip');
for (const tooltip of tooltips) {
if (tooltip.contains(activeElement)) {
return true;
}
}
return false;
};
interface OGDialogProps extends DialogPrimitive.DialogProps {
triggerRef?: React.RefObject<HTMLButtonElement | HTMLInputElement | HTMLDivElement | null>;
triggerRefs?: React.RefObject<HTMLButtonElement | HTMLInputElement | HTMLDivElement | null>[];
@ -145,40 +173,102 @@ const DialogContent: React.ForwardRefExoticComponent<
) => {
const depth = React.useContext(DialogDepthContext);
const contentZIndex = 140 + (depth - 1) * 60;
const contentRef = React.useRef<HTMLDivElement | null>(null);
const composedRef = React.useCallback(
(node: HTMLDivElement | null) => {
contentRef.current = node;
if (typeof ref === 'function') {
ref(node);
} else if (ref) {
(ref as React.MutableRefObject<HTMLDivElement | null>).current = node;
}
},
[ref],
);
/**
* Radix routes Escape to the highest dismissable layer only, and a toast
* registers one *above* whatever dialog is already open — so a status toast
* on screen swallows the Escape that should have closed the dialog under
* 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.
* 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<HTMLButtonElement>(null);
React.useEffect(() => {
const handleKeyDown = (event: KeyboardEvent) => {
const content = contentRef.current;
if (content == null || event.key !== 'Escape' || event.isComposing) {
return;
}
/** Another layer already answered this Escape — a select inside the
* dialog closing its own listbox, say. Forcing the dialog shut on top
* of that would take the reader's work with it. */
if (event.defaultPrevented) {
return;
}
const ownerDocument = content.ownerDocument;
if (escapeBelongsToPopup(ownerDocument)) {
return;
}
/** The consumer's own `onEscapeKeyDown` never ran: Radix only calls it
* 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;
}
/** Radix Toast's own `li`. Matched whatever its `data-state`, because a
* toast that has begun closing keeps its dismissable layer registered
* until the exit animation ends — and that layer is what takes the
* Escape. */
const toast = ownerDocument.querySelector('li[data-radix-collection-item]');
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<HTMLElement>(
'[role="dialog"][data-state="open"], [role="alertdialog"][data-state="open"]',
),
).reduce<HTMLElement | null>(
(highest, candidate) =>
highest == null || stackOrder(candidate) >= stackOrder(highest) ? candidate : highest,
null,
);
if (frontmost !== content) {
return;
}
escapeFallbackRef.current?.click();
};
document.addEventListener('keydown', handleKeyDown);
return () => document.removeEventListener('keydown', handleKeyDown);
}, [propsOnEscapeKeyDown]);
/* Handle Escape key to prevent closing dialog if a tooltip or dropdown has focus
(this is a workaround in order to achieve WCAG compliance which requires
that our tooltips be dismissable with Escape key) */
const handleEscapeKeyDown = React.useCallback(
(event: KeyboardEvent) => {
const activeElement = document.activeElement;
// Check if active element is a trigger with an open popover (aria-expanded="true")
if (activeElement?.getAttribute('aria-expanded') === 'true') {
if (escapeBelongsToPopup(document)) {
event.preventDefault();
return;
}
// Check if a dropdown menu, listbox, or combobox has focus (focus is within it)
const popoverElements = document.querySelectorAll(
'[role="menu"], [role="listbox"], [role="combobox"]',
);
for (const popover of popoverElements) {
if (popover.contains(activeElement)) {
event.preventDefault();
return;
}
}
// Check if a tooltip has focus (focus is within it)
const tooltips = document.querySelectorAll('.tooltip');
for (const tooltip of tooltips) {
if (tooltip.contains(activeElement)) {
event.preventDefault();
return;
}
}
propsOnEscapeKeyDown?.(event);
},
[propsOnEscapeKeyDown],
@ -188,7 +278,7 @@ const DialogContent: React.ForwardRefExoticComponent<
<DialogPortal>
<DialogOverlay className={overlayClassName} />
<DialogPrimitive.Content
ref={ref}
ref={composedRef}
style={{ ...style, zIndex: contentZIndex }}
onEscapeKeyDown={handleEscapeKeyDown}
className={cn(
@ -200,6 +290,12 @@ const DialogContent: React.ForwardRefExoticComponent<
{...props}
>
{children}
<DialogPrimitive.Close
ref={escapeFallbackRef}
className="sr-only"
tabIndex={-1}
aria-hidden="true"
/>
{showCloseButton && (
<DialogPrimitive.Close className="absolute right-4 top-4 rounded-sm opacity-70 ring-ring-primary ring-offset-surface-dialog transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-text-primary focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-surface-hover data-[state=open]:text-text-secondary">
<X className="h-6 w-6" aria-hidden="true" />

View file

@ -0,0 +1,36 @@
import '@testing-library/jest-dom';
import { render, screen } from '@testing-library/react';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '../Select';
import { OGDialog, OGDialogContent } from '../OriginalDialog';
/**
* A dialog traps focus, and a popover opened inside it is expected to take that
* trap over — Radix does this by pausing the outer scope when the inner one
* mounts. Both scopes have to come from the same copy of
* `@radix-ui/react-focus-scope` for that hand-off to happen; with duplicates,
* the dialog never yields and the popover's options cannot be reached by
* keyboard. `radixLayers.spec.ts` pins the packaging invariant; this asserts
* the behaviour it exists for.
*/
it('lets a portaled select option hold focus inside a dialog', () => {
render(
<OGDialog open>
<OGDialogContent>
<Select open value="ask">
<SelectTrigger aria-label="Execution environment">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="ask">Ask before changes</SelectItem>
<SelectItem value="accept">Accept edits</SelectItem>
</SelectContent>
</Select>
</OGDialogContent>
</OGDialog>,
);
const option = screen.getByRole('option', { name: 'Accept edits' });
option.focus();
expect(document.activeElement).toBe(option);
});

View file

@ -0,0 +1,176 @@
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';
/**
* Radix hands Escape to the highest dismissable layer only, and a toast
* registers one above whatever dialog is already open. Sharing a single copy of
* `react-dismissable-layer` puts both in the same stack, so a status toast on
* screen swallowed the Escape that should have closed the dialog beneath it.
*/
function Harness({
onOpenChange,
toast,
}: {
onOpenChange: (open: boolean) => void;
toast: boolean;
}) {
return (
<RadixToast.Provider>
<OGDialog open onOpenChange={onOpenChange}>
<OGDialogContent>
<button type="button">inside the dialog</button>
</OGDialogContent>
</OGDialog>
{toast && (
<RadixToast.Root open duration={Infinity} className="toast-root">
<RadixToast.Description>Skill created</RadixToast.Description>
</RadixToast.Root>
)}
<RadixToast.Viewport />
</RadixToast.Provider>
);
}
describe('dialog Escape', () => {
/** The fallback must not overrule the guards the dialog already honours: a
* popup inside it owns the first Escape (WCAG 2.1.1), and a layer that has
* already answered the event owns it outright. */
it('leaves the dialog open when Escape belongs to a popup inside it', async () => {
const onOpenChange = jest.fn();
render(
<RadixToast.Provider>
<OGDialog open onOpenChange={onOpenChange}>
<OGDialogContent>
<div role="listbox" tabIndex={-1}>
<button type="button">an option</button>
</div>
</OGDialogContent>
</OGDialog>
<RadixToast.Root open duration={Infinity} className="toast-root">
<RadixToast.Description>Skill created</RadixToast.Description>
</RadixToast.Root>
<RadixToast.Viewport />
</RadixToast.Provider>,
);
screen.getByText('an option').focus();
await userEvent.keyboard('{Escape}');
expect(onOpenChange).not.toHaveBeenCalled();
});
it('leaves the dialog open when another layer already answered the Escape', async () => {
const onOpenChange = jest.fn();
render(<Harness onOpenChange={onOpenChange} toast />);
const answerFirst = (event: KeyboardEvent) => event.preventDefault();
document.addEventListener('keydown', answerFirst, { capture: true });
try {
screen.getByText('inside the dialog').focus();
await userEvent.keyboard('{Escape}');
} finally {
document.removeEventListener('keydown', answerFirst, { capture: true });
}
expect(onOpenChange).not.toHaveBeenCalled();
});
it("respects a consumer's onEscapeKeyDown that cancels the close", async () => {
const onOpenChange = jest.fn();
render(
<RadixToast.Provider>
<OGDialog open onOpenChange={onOpenChange}>
<OGDialogContent onEscapeKeyDown={(event) => event.preventDefault()}>
<button type="button">inside the dialog</button>
</OGDialogContent>
</OGDialog>
<RadixToast.Root open duration={Infinity} className="toast-root">
<RadixToast.Description>Saved</RadixToast.Description>
</RadixToast.Root>
<RadixToast.Viewport />
</RadixToast.Provider>,
);
screen.getByText('inside the dialog').focus();
await userEvent.keyboard('{Escape}');
expect(onOpenChange).not.toHaveBeenCalled();
});
/** `OGDialogContent` is also used as an alert dialog — the shared-link delete
* confirmation — which the frontmost ranking has to see, or its Escape is
* dropped instead of closing it. */
it('closes an alert dialog while a toast is on screen', async () => {
const onOpenChange = jest.fn();
render(
<RadixToast.Provider>
<OGDialog open onOpenChange={onOpenChange}>
<OGDialogContent role="alertdialog" showCloseButton={false}>
<button type="button">delete it</button>
</OGDialogContent>
</OGDialog>
<RadixToast.Root open duration={Infinity} className="toast-root">
<RadixToast.Description>Link copied</RadixToast.Description>
</RadixToast.Root>
<RadixToast.Viewport />
</RadixToast.Provider>,
);
screen.getByText('delete it').focus();
await userEvent.keyboard('{Escape}');
expect(onOpenChange).toHaveBeenCalledWith(false);
});
/** 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(
<RadixToast.Provider>
<style>{'.on-top { z-index: 250; }'}</style>
<OGDialog open onOpenChange={onOpenChange}>
<OGDialogContent>
<button type="button">under</button>
</OGDialogContent>
</OGDialog>
<div role="dialog" data-state="open" className="on-top">
<button type="button">preview</button>
</div>
<RadixToast.Root open duration={Infinity} className="toast-root">
<RadixToast.Description>Saved</RadixToast.Description>
</RadixToast.Root>
<RadixToast.Viewport />
</RadixToast.Provider>,
);
screen.getByText('preview').focus();
await userEvent.keyboard('{Escape}');
expect(onOpenChange).not.toHaveBeenCalled();
});
it('closes the dialog while a toast is on screen', async () => {
const onOpenChange = jest.fn();
render(<Harness onOpenChange={onOpenChange} toast />);
screen.getByText('inside the dialog').focus();
await userEvent.keyboard('{Escape}');
expect(onOpenChange).toHaveBeenCalledWith(false);
});
it('still closes the dialog with no toast up', async () => {
const onOpenChange = jest.fn();
render(<Harness onOpenChange={onOpenChange} toast={false} />);
screen.getByText('inside the dialog').focus();
await userEvent.keyboard('{Escape}');
expect(onOpenChange).toHaveBeenCalledWith(false);
});
});

View file

@ -0,0 +1,32 @@
import { join } from 'node:path';
import { readFileSync } from 'node:fs';
/**
* Radix coordinates nested layers and focus scopes through module-level state,
* so a dialog and the popover inside it cooperate only while they import the
* *same copy* of these packages. Duplicates are silent: the popover opens
* behind the dialog's overlay with pointer events off and cannot hold focus —
* which is how the Run Code settings became unusable (#15738), and what
* #11023's modal tooltip and dropdown regressions look like from the other
* side of the same split.
*
* Read from the lockfile rather than from resolution, so the invariant holds
* for whoever installs it next rather than for whatever this machine happens
* to have on disk.
*/
const SINGLETONS = ['@radix-ui/react-dismissable-layer', '@radix-ui/react-focus-scope'];
type Lockfile = { packages: Record<string, { version?: string }> };
const lockfile = (): Lockfile =>
JSON.parse(readFileSync(join(__dirname, '../../../../../package-lock.json'), 'utf8')) as Lockfile;
describe('Radix layer packages', () => {
it.each(SINGLETONS)('resolves %s to a single copy', (name) => {
const paths = Object.keys(lockfile().packages).filter((path) =>
path.endsWith(`node_modules/${name}`),
);
expect(paths).toEqual([`node_modules/${name}`]);
});
});