Return focus to the control that opened a dialog instead of leaving it on the document body.
Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
@@ -1,6 +1,7 @@
|
||||
import React from "react";
|
||||
import React, { useState } from "react";
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
import { screen, fireEvent, waitFor } from "@testing-library/react";
|
||||
import userEvent from "@testing-library/user-event";
|
||||
import "@testing-library/jest-dom/vitest";
|
||||
import { renderWithProviders } from "../utils/test-utils";
|
||||
import Create from "../../app/components/modals/Create";
|
||||
@@ -8,6 +9,23 @@ import TextInput from "../../app/components/controls/TextInput";
|
||||
|
||||
type CreateProps = React.ComponentProps<typeof Create>;
|
||||
|
||||
function CreateOpenHarness() {
|
||||
const [open, setOpen] = useState(false);
|
||||
return (
|
||||
<>
|
||||
<button type="button" onClick={() => setOpen(true)}>
|
||||
Open create dialog
|
||||
</button>
|
||||
<Create
|
||||
isOpen={open}
|
||||
onClose={() => setOpen(false)}
|
||||
title="Test Create Dialog"
|
||||
description="Test description"
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
describe("Create", () => {
|
||||
const defaultProps: CreateProps = {
|
||||
isOpen: true,
|
||||
@@ -233,6 +251,17 @@ describe("Create", () => {
|
||||
expect(document.body.style.overflow).toBe("");
|
||||
});
|
||||
|
||||
it("restores focus to the control that opened it", async () => {
|
||||
const user = userEvent.setup();
|
||||
renderWithProviders(<CreateOpenHarness />);
|
||||
const trigger = screen.getByRole("button", { name: "Open create dialog" });
|
||||
await user.click(trigger);
|
||||
expect(screen.getByRole("dialog")).toBeInTheDocument();
|
||||
await user.keyboard("{Escape}");
|
||||
expect(screen.queryByRole("dialog")).not.toBeInTheDocument();
|
||||
expect(trigger).toHaveFocus();
|
||||
});
|
||||
|
||||
it("traps focus within create dialog", async () => {
|
||||
renderWithProviders(
|
||||
<Create {...defaultProps}>
|
||||
|
||||
Reference in New Issue
Block a user