Fix Escape key not working in modals

Signed-off-by: marcin mikołajczak <git@mkljczk.pl>
This commit is contained in:
marcin mikołajczak 2022-11-10 21:46:51 +01:00
parent d19a93f109
commit 4d9e4879ed
1 changed files with 8 additions and 7 deletions

View File

@ -47,12 +47,13 @@ const ModalRoot: React.FC<IModalRoot> = ({ children, onCancel, onClose, type })
const isEditing = useAppSelector(state => state.compose.get('compose-modal')?.id !== null);
const handleKeyUp = useCallback((e) => {
if ((e.key === 'Escape' || e.key === 'Esc' || e.keyCode === 27)
&& !!children) {
const visible = !!children;
const handleKeyUp = (e: KeyboardEvent) => {
if (e.key === 'Escape' || e.key === 'Esc' || e.keyCode === 27) {
handleOnClose();
}
}, []);
};
const handleOnClose = () => {
dispatch((_, getState) => {
@ -136,6 +137,8 @@ const ModalRoot: React.FC<IModalRoot> = ({ children, onCancel, onClose, type })
};
useEffect(() => {
if (!visible) return;
window.addEventListener('keyup', handleKeyUp, false);
window.addEventListener('keydown', handleKeyDown, false);
@ -143,7 +146,7 @@ const ModalRoot: React.FC<IModalRoot> = ({ children, onCancel, onClose, type })
window.removeEventListener('keyup', handleKeyUp);
window.removeEventListener('keydown', handleKeyDown);
};
}, []);
}, [visible]);
useEffect(() => {
if (!!children && !prevChildren) {
@ -172,8 +175,6 @@ const ModalRoot: React.FC<IModalRoot> = ({ children, onCancel, onClose, type })
}
});
const visible = !!children;
if (!visible) {
return (
<div className='z-50 transition-all' ref={ref} style={{ opacity: 0 }} />