Skip to content

Commit e16f90e

Browse files
committed
Add option to close Overlay with escape
1 parent 956cb0d commit e16f90e

File tree

1 file changed

+24
-4
lines changed

1 file changed

+24
-4
lines changed

packages/app/src/app/components/Overlay/Overlay.tsx

Lines changed: 24 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,13 @@
1-
import React, { useState, useLayoutEffect } from 'react';
1+
import React, {
2+
useState,
3+
useLayoutEffect,
4+
useEffect,
5+
useCallback,
6+
} from 'react';
27
import { motion } from 'framer-motion';
38
import track from '@codesandbox/common/lib/utils/analytics';
49
import Portal from '@codesandbox/common/lib/components/Portal';
10+
import { ESC } from '@codesandbox/common/lib/utils/keycodes';
511
import { Container, ContentContainer } from './elements';
612

713
interface IOverlayProps {
@@ -63,7 +69,7 @@ export const Overlay: React.FC<IOverlayProps> = ({
6369
};
6470
}, []);
6571

66-
const handleClick = () => {
72+
const handleClose = useCallback(() => {
6773
if (openState) {
6874
if (event) {
6975
track(`Closed ${event}`);
@@ -76,7 +82,21 @@ export const Overlay: React.FC<IOverlayProps> = ({
7682
setOpen(false);
7783
}
7884
}
79-
};
85+
}, [openState, isControlled, onClose, setOpen, event]);
86+
87+
useEffect(() => {
88+
const handleEscape = (e: KeyboardEvent) => {
89+
if (e.keyCode === ESC) {
90+
handleClose();
91+
}
92+
};
93+
94+
document.addEventListener('keypress', handleEscape);
95+
96+
return () => {
97+
document.removeEventListener('keypress', handleEscape);
98+
};
99+
}, [handleClose]);
80100

81101
const handleOpen = () => {
82102
if (event) {
@@ -97,7 +117,7 @@ export const Overlay: React.FC<IOverlayProps> = ({
97117

98118
{openState && (
99119
<Portal>
100-
<ContentContainer onClick={handleClick}>
120+
<ContentContainer onClick={handleClose}>
101121
<motion.div
102122
onClick={e => e.stopPropagation()}
103123
style={{

0 commit comments

Comments
 (0)