Skip to content

Commit

Permalink
Press escape to close new modal
Browse files Browse the repository at this point in the history
  • Loading branch information
SupertigerDev committed Sep 14, 2024
1 parent c857415 commit 660c9a8
Showing 1 changed file with 24 additions and 1 deletion.
25 changes: 24 additions & 1 deletion src/components/ui/modal/Modal.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,13 @@
import style from "./Modal.module.scss";
import { createContext, JSXElement, Show, useContext } from "solid-js";
import {
createContext,
createEffect,
JSXElement,
onCleanup,
onMount,
Show,
useContext,
} from "solid-js";
import Button, { ButtonProps } from "../Button";
import Icon from "../icon/Icon";
import { cn } from "@/common/classNames";
Expand All @@ -13,6 +21,10 @@ interface RootProps {
children: JSXElement;
close?: () => void;
class?: string;
/**
@default true
*/
closeOnEscape?: boolean;
}
const Root = (props: RootProps) => {
const { isMobileWidth } = useWindowProperties();
Expand All @@ -21,6 +33,17 @@ const Root = (props: RootProps) => {
if (event.target === event.currentTarget) props.close?.();
};

onMount(() => {
const closeOnEscape = props.closeOnEscape ?? true;
if (!closeOnEscape) return;

const onKeyDown = (event: KeyboardEvent) => {
if (event.key === "Escape") props.close?.();
};
document.addEventListener("keydown", onKeyDown);
onCleanup(() => document.removeEventListener("keydown", onKeyDown));
});

return (
<ModalContext.Provider value={{ close: props.close }}>
<div
Expand Down

0 comments on commit 660c9a8

Please sign in to comment.