Skip to content

Commit

Permalink
feat(Modal): Prevent onHide when keyboard event defaultPrevented is t…
Browse files Browse the repository at this point in the history
…rue (#816)
  • Loading branch information
kyletsang authored May 14, 2020
1 parent c9e7e46 commit b4ffcec
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 1 deletion.
7 changes: 6 additions & 1 deletion src/Modal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -281,7 +281,10 @@ const Modal: React.ForwardRefExoticComponent<
const handleDocumentKeyDown = useEventCallback((e: KeyboardEvent) => {
if (keyboard && e.keyCode === 27 && modal.isTopModal()) {
onEscapeKeyDown?.(e);
onHide();

if (!e.defaultPrevented) {
onHide();
}
}
});

Expand Down Expand Up @@ -421,6 +424,8 @@ const propTypes = {

/**
* A callback fired when the escape key, if specified in `keyboard`, is pressed.
*
* If preventDefault() is called on the keyboard event, closing the modal will be cancelled.
*/
onEscapeKeyDown: PropTypes.func,

Expand Down
19 changes: 19 additions & 0 deletions test/ModalSpec.js
Original file line number Diff line number Diff line change
Expand Up @@ -202,6 +202,25 @@ describe('<Modal>', () => {
simulant.fire(backdrop, 'keydown', { keyCode: 27 });
});

it('should not trigger onHide if e.preventDefault() called', () => {
const onHideSpy = sinon.spy();
const onEscapeKeyDown = (e) => {
e.preventDefault();
};

let ref = mountWithRef(
<Modal show onHide={onHideSpy} onEscapeKeyDown={onEscapeKeyDown}>
<strong>Message</strong>
</Modal>,
{ attachTo },
);

let { backdrop } = ref.current;

simulant.fire(backdrop, 'keydown', { keyCode: 27 });
expect(onHideSpy).to.not.have.been.called;
});

it('should add role to child', () => {
let dialog;
wrapper = mount(
Expand Down

0 comments on commit b4ffcec

Please sign in to comment.