From 081b063facdbff59f7861539be3a7f64d5d86c5e Mon Sep 17 00:00:00 2001 From: Arlindo Pereira Date: Mon, 14 Oct 2024 16:12:04 +0200 Subject: [PATCH] Fix Modal handling of Esc keypress to close --- src/components/overlays/Modal/Modal.tsx | 19 +++++-------------- 1 file changed, 5 insertions(+), 14 deletions(-) diff --git a/src/components/overlays/Modal/Modal.tsx b/src/components/overlays/Modal/Modal.tsx index 7cb6817..ac85292 100644 --- a/src/components/overlays/Modal/Modal.tsx +++ b/src/components/overlays/Modal/Modal.tsx @@ -153,21 +153,12 @@ const Modal = ({ [close, closeable], ); - // prevent closing dialog with Esc key - const handleKeyDown = React.useCallback((event: KeyboardEvent) => { - if (event.key !== 'Escape') { - return; - } - if (closeable) { + // "onKeyDown" instead of "onCancel" as the latter is only fired after the cancel already initiated + const handleDialogKeyDown = (event: React.KeyboardEvent) => { + if (event.key === 'Escape' && !closeable) { event.preventDefault(); } - }, [closeable]); - React.useEffect(() => { - document.addEventListener('keydown', handleKeyDown); - return () => { - document.removeEventListener('keydown', handleKeyDown); - }; - }, [handleKeyDown]); + }; return ( // biome-ignore lint/a11y/useKeyWithClickEvents: @@ -186,13 +177,13 @@ const Modal = ({ className, )} onClick={handleDialogClick} + onKeyDown={handleDialogKeyDown} > {closeable && (