Skip to content

Commit 4a8506b

Browse files
authored
fix(modal): close on blur (#704)
1 parent 3875c11 commit 4a8506b

File tree

2 files changed

+24
-1
lines changed

2 files changed

+24
-1
lines changed

packages/modal/src/ModalContainer.spec.tsx

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77

88
import React, { createRef } from 'react';
99
import userEvent from '@testing-library/user-event';
10-
import { render, fireEvent } from '@testing-library/react';
10+
import { render, fireEvent, waitFor } from '@testing-library/react';
1111
import { KEYS } from '@zendeskgarden/container-utilities';
1212
import { ModalContainer, IUseModalReturnValue } from './';
1313

@@ -105,6 +105,16 @@ describe('FocusJailContainer', () => {
105105
expect(onCloseSpy).not.toHaveBeenCalled();
106106
});
107107
});
108+
109+
it('closes modal on blur', async () => {
110+
render(<BasicExample onClose={onCloseSpy} />);
111+
112+
await waitFor(async () => {
113+
await user.click(document.body);
114+
});
115+
116+
expect(onCloseSpy).toHaveBeenCalled();
117+
});
108118
});
109119

110120
describe('getTitleProps()', () => {

packages/modal/src/useModal.ts

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,7 @@ export const useModal = <T extends Element = Element>({
5454

5555
const getModalProps: IUseModalReturnValue['getModalProps'] = ({
5656
role = 'dialog',
57+
onBlur,
5758
onKeyDown,
5859
onMouseDown,
5960
...other
@@ -63,6 +64,18 @@ export const useModal = <T extends Element = Element>({
6364
'aria-modal': true,
6465
'aria-labelledby': titleId,
6566
'aria-describedby': contentId,
67+
onBlur: composeEventHandlers(onBlur, event => {
68+
const doc = environment || document;
69+
70+
// Timeout is required to ensure blur is handled after focus
71+
setTimeout(() => {
72+
const activeElement = doc.activeElement;
73+
74+
if (!modalRef.current?.contains(activeElement)) {
75+
closeModal(event);
76+
}
77+
});
78+
}),
6679
onMouseDown: composeEventHandlers(onMouseDown, () => {
6780
isModalMousedDownRef.current = true;
6881
}),

0 commit comments

Comments
 (0)