Modal takes a required initialFocus (field / close / action), a field that loads late takes the focus while it still rests on the close button, and ModalFooter portals a dialog's commit row under the scrolling body from any depth. The header and footer fades follow the body's scroll timeline, and the viewport's interactive-widget=resizes-content keeps the footer above an on-screen keyboard.
55 lines
2.4 KiB
TypeScript
55 lines
2.4 KiB
TypeScript
// @vitest-environment jsdom
|
|
//
|
|
// The dialog's focus behaviour under React 18 StrictMode — its own file because StrictMode's
|
|
// mount→cleanup→mount is what the code under test reacts to, and the module-level layer stack in
|
|
// ui/Modal (and the overlay-host registry in ui/Toaster) leaks between tests in one file.
|
|
//
|
|
// Round 5 fixed this in Chrome and shipped it with NO test: the second mount found the focus
|
|
// outside the dialog (its own cleanup had just handed it back to the trigger) and moved it to the
|
|
// first focusable — taking it off an `autoFocus` field a beat after the browser had put it there.
|
|
// The command palette opened focused on its ✕ in dev and on its search field in prod, from the same
|
|
// code. Round 6 measured that deleting the fix left all 1009 tests green, which is why this exists.
|
|
//
|
|
// Same offsetParent stub as Modal.dom.test.tsx: jsdom never lays out, so every element reports
|
|
// offsetParent null and `focusablesIn` would see nothing.
|
|
import { describe, it, expect, beforeEach, afterEach, vi } from "vitest";
|
|
import { StrictMode } from "react";
|
|
import { render, screen, cleanup } from "@testing-library/react";
|
|
|
|
vi.mock("react-i18next", async (importOriginal) => {
|
|
const actual = await importOriginal<typeof import("react-i18next")>();
|
|
return { ...actual, useTranslation: () => ({ t: (key: string) => key }) };
|
|
});
|
|
vi.mock("../../lib/history", () => ({ useBackToClose: () => {} }));
|
|
|
|
import Modal from "./Modal";
|
|
|
|
describe("Modal focus under StrictMode", () => {
|
|
let origDesc: PropertyDescriptor | undefined;
|
|
beforeEach(() => {
|
|
origDesc = Object.getOwnPropertyDescriptor(HTMLElement.prototype, "offsetParent");
|
|
Object.defineProperty(HTMLElement.prototype, "offsetParent", {
|
|
configurable: true,
|
|
get(this: HTMLElement) {
|
|
return this.isConnected ? document.body : null;
|
|
},
|
|
});
|
|
});
|
|
afterEach(() => {
|
|
cleanup();
|
|
if (origDesc) Object.defineProperty(HTMLElement.prototype, "offsetParent", origDesc);
|
|
});
|
|
|
|
it("keeps the focus its autoFocus child asked for across the double mount", () => {
|
|
render(
|
|
<StrictMode>
|
|
<Modal initialFocus="close" title="t" onClose={() => {}}>
|
|
<input aria-label="field" autoFocus />
|
|
</Modal>
|
|
</StrictMode>,
|
|
);
|
|
// Without the remembered focus the second mount lands on the first focusable — the header ✕.
|
|
expect(document.activeElement).toBe(screen.getByLabelText("field"));
|
|
});
|
|
});
|