1- import React , { useState , useLayoutEffect } from 'react' ;
1+ import React , {
2+ useState ,
3+ useLayoutEffect ,
4+ useEffect ,
5+ useCallback ,
6+ } from 'react' ;
27import { motion } from 'framer-motion' ;
38import track from '@codesandbox/common/lib/utils/analytics' ;
49import Portal from '@codesandbox/common/lib/components/Portal' ;
10+ import { ESC } from '@codesandbox/common/lib/utils/keycodes' ;
511import { Container , ContentContainer } from './elements' ;
612
713interface 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