Skip to content

Commit

Permalink
Close modal on Escape (#1811)
Browse files Browse the repository at this point in the history
* Close modal on escape

* Add tests
  • Loading branch information
sroy3 authored Jun 1, 2022
1 parent 7ff7b43 commit 796180c
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 1 deletion.
35 changes: 35 additions & 0 deletions webview/src/shared/components/modal/Modal.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
/**
* @jest-environment jsdom
*/
import React from 'react'
import { render, cleanup, fireEvent } from '@testing-library/react'
import { Modal } from './Modal'

describe('Modal', () => {
afterEach(() => {
cleanup()
})

it('should call the onClose prop when pressing Escape', () => {
const onClose = jest.fn()

render(<Modal onClose={onClose} />)

fireEvent.keyDown(window, { key: 'Escape' })

expect(onClose).toHaveBeenCalled()
})

it('should not call the onClose prop when pressing other keys', () => {
const onClose = jest.fn()

render(<Modal onClose={onClose} />)

fireEvent.keyDown(window, { key: 'Enter' })
fireEvent.keyDown(window, { key: 'e' })
fireEvent.keyDown(window, { key: 'Space' })
fireEvent.keyDown(window, { key: 'Alt' })

expect(onClose).not.toHaveBeenCalled()
})
})
14 changes: 13 additions & 1 deletion webview/src/shared/components/modal/Modal.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import React, { MouseEvent } from 'react'
import React, { MouseEvent, useEffect } from 'react'
import styles from './styles.module.scss'
import { AllIcons, Icon } from '../Icon'

Expand All @@ -7,6 +7,18 @@ interface ModalProps {
}

export const Modal: React.FC<ModalProps> = ({ onClose, children }) => {
useEffect(() => {
const checkKeyAndClose = (e: KeyboardEvent) => {
if (e.key === 'Escape') {
onClose()
}
}
window.addEventListener('keydown', checkKeyAndClose)

return () => {
window.removeEventListener('keydown', checkKeyAndClose)
}
}, [onClose])
return (
<div
className={styles.backdrop}
Expand Down

0 comments on commit 796180c

Please sign in to comment.