Skip to content

Commit c4d0cf3

Browse files
authored
fix: should be closed when press esc after click portal (#273)
* fix: should be closed when press esc after click portal * test: add case * test: add called times
1 parent 3931701 commit c4d0cf3

2 files changed

Lines changed: 47 additions & 0 deletions

File tree

src/Operations.tsx

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import Portal from '@rc-component/portal';
22
import classnames from 'classnames';
33
import CSSMotion from 'rc-motion';
4+
import KeyCode from 'rc-util/lib/KeyCode';
45
import * as React from 'react';
56
import { useContext } from 'react';
67
import { PreviewGroupContext } from './context';
@@ -75,6 +76,22 @@ const Operations: React.FC<OperationsProps> = props => {
7576
const { rotateLeft, rotateRight, zoomIn, zoomOut, close, left, right, flipX, flipY } = icons;
7677
const toolClassName = `${prefixCls}-operations-operation`;
7778

79+
React.useEffect(() => {
80+
const onKeyDown = (e: KeyboardEvent) => {
81+
if (e.keyCode === KeyCode.ESC) {
82+
onClose();
83+
}
84+
};
85+
86+
if (visible) {
87+
window.addEventListener('keydown', onKeyDown);
88+
}
89+
90+
return () => {
91+
window.removeEventListener('keydown', onKeyDown);
92+
};
93+
}, [visible]);
94+
7895
const tools = [
7996
{
8097
icon: flipY,

tests/preview.test.tsx

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -861,4 +861,34 @@ describe('Preview', () => {
861861

862862
expect(document.querySelector('video')).toBeTruthy();
863863
});
864+
865+
it('should be closed when press esc after click portal', () => {
866+
const onVisibleChange = jest.fn();
867+
const { container } = render(
868+
<Image
869+
src="https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png"
870+
preview={{
871+
onVisibleChange,
872+
}}
873+
/>,
874+
);
875+
876+
fireEvent.click(container.querySelector('.rc-image'));
877+
act(() => {
878+
jest.runAllTimers();
879+
});
880+
881+
expect(document.querySelector('.rc-image-preview')).toBeTruthy();
882+
883+
expect(onVisibleChange).toBeCalledWith(true, false);
884+
885+
fireEvent.click(document.querySelector('.rc-image-preview-operations'));
886+
887+
fireEvent.keyDown(window, { key: 'Escape', keyCode: 27 });
888+
889+
expect(onVisibleChange).toBeCalledWith(false, true);
890+
expect(onVisibleChange).toBeCalledTimes(2);
891+
892+
onVisibleChange.mockRestore();
893+
});
864894
});

0 commit comments

Comments
 (0)