Skip to content

Commit

Permalink
feat(Modal): add keyboard event handler
Browse files Browse the repository at this point in the history
  • Loading branch information
JohnsonMao committed Nov 2, 2024
1 parent 00fa281 commit 3dece29
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 8 deletions.
17 changes: 14 additions & 3 deletions components/shared/Modal/Modal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -77,12 +77,23 @@ const InternalModal: ForwardRefRenderFunction<HTMLDivElement, ModalProps> = (
};
}, [isOpen]);

useEffect(() => {
const handleWindowKeyUp = (e: KeyboardEvent) => {
if (e.key === "Escape") {
onClose?.();
}
};
window.addEventListener("keyup", handleWindowKeyUp);

return () => window.removeEventListener("keyup", handleWindowKeyUp);
}, [onClose]);

return (
!removeDOM && (
<Portal>
<div
<button
className={cn(
"duration-200",
"cursor-auto duration-200",
"fixed top-0 left-0 w-screen h-screen bg-basic-black/60 z-10",
isOpen ? "opacity-100" : "opacity-0"
)}
Expand All @@ -100,13 +111,13 @@ const InternalModal: ForwardRefRenderFunction<HTMLDivElement, ModalProps> = (
>
<BoxFancy
ref={ref}
component="dialog"
className={cn(
"px-10 py-12 flex flex-col gap-8",
"text-primary-100 bg-primary-700/40 rounded-2xl drop-shadow-md",
dialogSize[size]
)}
{...restProps}
role="alertdialog"
>
<header className="text-[22px] text-center">{title}</header>
<div>{children}</div>
Expand Down
8 changes: 3 additions & 5 deletions components/shared/Modal/modal.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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(
<Modal isOpen title="Test Title">
Test Content
</Modal>
);
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(<Modal title="Test Title">Test Content</Modal>);
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 () => {
Expand Down

0 comments on commit 3dece29

Please sign in to comment.