From 92703d5e3d8558e0a9599512c832adf9b0d37a25 Mon Sep 17 00:00:00 2001 From: Kyle Tsang <6854874+kyletsang@users.noreply.github.com> Date: Tue, 6 Dec 2022 17:14:22 -0800 Subject: [PATCH] fix(Modal): fix modal not closing when keyboard=false (#6515) --- src/Modal.tsx | 15 +++++++++------ test/ModalSpec.tsx | 34 +++++++++++++++++++++++++++++++++- 2 files changed, 42 insertions(+), 7 deletions(-) diff --git a/src/Modal.tsx b/src/Modal.tsx index 980c6dfaf5..4e1226a2e7 100644 --- a/src/Modal.tsx +++ b/src/Modal.tsx @@ -391,13 +391,16 @@ const Modal: BsPrefixRefForwardingComponent<'div', ModalProps> = }; const handleEscapeKeyDown = (e) => { - if (!keyboard && backdrop === 'static') { - // Call preventDefault to stop modal from closing in restart ui, - // then play our animation. + if (keyboard) { + onEscapeKeyDown?.(e); + } else { + // Call preventDefault to stop modal from closing in @restart/ui. e.preventDefault(); - handleStaticModalAnimation(); - } else if (keyboard && onEscapeKeyDown) { - onEscapeKeyDown(e); + + if (backdrop === 'static') { + // Play static modal animation. + handleStaticModalAnimation(); + } } }; diff --git a/test/ModalSpec.tsx b/test/ModalSpec.tsx index 06a5c1faf5..d5b51c12ef 100644 --- a/test/ModalSpec.tsx +++ b/test/ModalSpec.tsx @@ -1,7 +1,7 @@ import * as React from 'react'; import sinon from 'sinon'; import { expect } from 'chai'; -import { fireEvent, render } from '@testing-library/react'; +import { fireEvent, render, screen } from '@testing-library/react'; import ModalManager from '@restart/ui/ModalManager'; import Modal, { ModalProps } from '../src/Modal'; @@ -450,6 +450,38 @@ describe('', () => { onEscapeKeyDownSpy.should.not.have.been.called; }); + it('Should not hide modal when keyboard is false', async () => { + function ModalTest() { + const [show, setShow] = React.useState(false); + + return ( + <> + setShow(false)} keyboard={false}> + Message + + + + ); + } + + render(); + + // Show the modal. + fireEvent.click(screen.getByRole('button')); + + // Escape key. + fireEvent.keyDown(screen.getByRole('dialog'), { + keyCode: 27, + }); + + // Wait a bit before checking if modal is still there. + await new Promise((r) => setTimeout(r, 500)); + + expect(screen.queryByRole('dialog')).to.exist; + }); + it('Should use custom props manager if specified', (done) => { class MyModalManager extends ModalManager { // @ts-ignore