From 3dece299f2c1a0f27753b9466ab287e47f200353 Mon Sep 17 00:00:00 2001 From: Johnson Mao Date: Sat, 2 Nov 2024 21:47:21 +0800 Subject: [PATCH] feat(Modal): add keyboard event handler --- components/shared/Modal/Modal.tsx | 17 ++++++++++++++--- components/shared/Modal/modal.test.tsx | 8 +++----- 2 files changed, 17 insertions(+), 8 deletions(-) diff --git a/components/shared/Modal/Modal.tsx b/components/shared/Modal/Modal.tsx index 2ae322bb..e1878b4a 100644 --- a/components/shared/Modal/Modal.tsx +++ b/components/shared/Modal/Modal.tsx @@ -77,12 +77,23 @@ const InternalModal: ForwardRefRenderFunction = ( }; }, [isOpen]); + useEffect(() => { + const handleWindowKeyUp = (e: KeyboardEvent) => { + if (e.key === "Escape") { + onClose?.(); + } + }; + window.addEventListener("keyup", handleWindowKeyUp); + + return () => window.removeEventListener("keyup", handleWindowKeyUp); + }, [onClose]); + return ( !removeDOM && ( -
= ( >
{title}
{children}
diff --git a/components/shared/Modal/modal.test.tsx b/components/shared/Modal/modal.test.tsx index 8ad58623..ff75fcf1 100644 --- a/components/shared/Modal/modal.test.tsx +++ b/components/shared/Modal/modal.test.tsx @@ -5,22 +5,20 @@ import userEvent from "@testing-library/user-event"; import Modal from "."; describe("Modal", () => { - it("should render Modal when isOpen is true", () => { + it("should render Modal when isOpen is true", async () => { render( Test Content ); - const modal = screen.getByRole("dialog"); - expect(modal).toBeInTheDocument(); expect(screen.getByText("Test Title")).toBeInTheDocument(); expect(screen.getByText("Test Content")).toBeInTheDocument(); }); it("should not render Modal when isOpen is not setting", () => { render(Test Content); - const modal = screen.queryByRole("dialog"); - expect(modal).toBeNull(); + expect(screen.queryByText("Test Title")).not.toBeInTheDocument(); + expect(screen.queryByText("Test Content")).not.toBeInTheDocument(); }); it("should call onClose when close button is clicked", async () => {