Skip to content

Commit 796180c

Browse files
authored
Close modal on Escape (#1811)
* Close modal on escape * Add tests
1 parent 7ff7b43 commit 796180c

File tree

2 files changed

+48
-1
lines changed

2 files changed

+48
-1
lines changed
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
/**
2+
* @jest-environment jsdom
3+
*/
4+
import React from 'react'
5+
import { render, cleanup, fireEvent } from '@testing-library/react'
6+
import { Modal } from './Modal'
7+
8+
describe('Modal', () => {
9+
afterEach(() => {
10+
cleanup()
11+
})
12+
13+
it('should call the onClose prop when pressing Escape', () => {
14+
const onClose = jest.fn()
15+
16+
render(<Modal onClose={onClose} />)
17+
18+
fireEvent.keyDown(window, { key: 'Escape' })
19+
20+
expect(onClose).toHaveBeenCalled()
21+
})
22+
23+
it('should not call the onClose prop when pressing other keys', () => {
24+
const onClose = jest.fn()
25+
26+
render(<Modal onClose={onClose} />)
27+
28+
fireEvent.keyDown(window, { key: 'Enter' })
29+
fireEvent.keyDown(window, { key: 'e' })
30+
fireEvent.keyDown(window, { key: 'Space' })
31+
fireEvent.keyDown(window, { key: 'Alt' })
32+
33+
expect(onClose).not.toHaveBeenCalled()
34+
})
35+
})

webview/src/shared/components/modal/Modal.tsx

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import React, { MouseEvent } from 'react'
1+
import React, { MouseEvent, useEffect } from 'react'
22
import styles from './styles.module.scss'
33
import { AllIcons, Icon } from '../Icon'
44

@@ -7,6 +7,18 @@ interface ModalProps {
77
}
88

99
export const Modal: React.FC<ModalProps> = ({ onClose, children }) => {
10+
useEffect(() => {
11+
const checkKeyAndClose = (e: KeyboardEvent) => {
12+
if (e.key === 'Escape') {
13+
onClose()
14+
}
15+
}
16+
window.addEventListener('keydown', checkKeyAndClose)
17+
18+
return () => {
19+
window.removeEventListener('keydown', checkKeyAndClose)
20+
}
21+
}, [onClose])
1022
return (
1123
<div
1224
className={styles.backdrop}

0 commit comments

Comments
 (0)