Skip to content

Commit

Permalink
Merge pull request #6 from fortanix/fix/modal-key
Browse files Browse the repository at this point in the history
Fix Modal handling of Esc keypress to close
  • Loading branch information
nighto authored Oct 14, 2024
2 parents b54b7b3 + 081b063 commit e7cc399
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="cross" />
</button>
Expand Down

0 comments on commit e7cc399

Please sign in to comment.