From 4d9e4879ed5e853fbbb737b00769d2c10e6d7ab1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?marcin=20miko=C5=82ajczak?= Date: Thu, 10 Nov 2022 21:46:51 +0100 Subject: [PATCH] Fix Escape key not working in modals MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: marcin mikołajczak --- app/soapbox/components/modal_root.tsx | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/app/soapbox/components/modal_root.tsx b/app/soapbox/components/modal_root.tsx index eabd450d0..f34597d5b 100644 --- a/app/soapbox/components/modal_root.tsx +++ b/app/soapbox/components/modal_root.tsx @@ -47,12 +47,13 @@ const ModalRoot: React.FC = ({ 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 = ({ 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 = ({ 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 = ({ children, onCancel, onClose, type }) } }); - const visible = !!children; - if (!visible) { return (