Skip to content

Commit

Permalink
Fix Modal handling of Esc keypress to close
Browse files Browse the repository at this point in the history
  • Loading branch information
nighto committed Oct 14, 2024
1 parent f6eb9de commit 081b063
Showing 1 changed file with 5 additions and 14 deletions.
19 changes: 5 additions & 14 deletions src/components/overlays/Modal/Modal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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: <explanation>
Expand All @@ -186,13 +177,13 @@ const Modal = ({
className,
)}
onClick={handleDialogClick}
onKeyDown={handleDialogKeyDown}
>
{closeable && (
<button
type="button"
className={cx(cl['bk-modal__close'])}
onClick={close}
onKeyUp={close}
>
<Icon icon="close-x" />
</button>
Expand Down

0 comments on commit 081b063

Please sign in to comment.