-
-
Notifications
You must be signed in to change notification settings - Fork 32.4k
/
Modal.js
362 lines (326 loc) · 10.4 KB
/
Modal.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
import React from 'react';
import ReactDOM from 'react-dom';
import PropTypes from 'prop-types';
import { getThemeProps, useTheme } from '@material-ui/styles';
import { elementAcceptingRef } from '@material-ui/utils';
import ownerDocument from '../utils/ownerDocument';
import Portal from '../Portal';
import createChainedFunction from '../utils/createChainedFunction';
import useForkRef from '../utils/useForkRef';
import useEventCallback from '../utils/useEventCallback';
import zIndex from '../styles/zIndex';
import ModalManager, { ariaHidden } from './ModalManager';
import TrapFocus from './TrapFocus';
import SimpleBackdrop from './SimpleBackdrop';
function getContainer(container) {
container = typeof container === 'function' ? container() : container;
return ReactDOM.findDOMNode(container);
}
function getHasTransition(props) {
return props.children ? props.children.props.hasOwnProperty('in') : false;
}
// A modal manager used to track and manage the state of open Modals.
// Modals don't open on the server so this won't conflict with concurrent requests.
const defaultManager = new ModalManager();
export const styles = theme => ({
/* Styles applied to the root element. */
root: {
position: 'fixed',
zIndex: theme.zIndex.modal,
right: 0,
bottom: 0,
top: 0,
left: 0,
},
/* Styles applied to the root element if the `Modal` has exited. */
hidden: {
visibility: 'hidden',
},
});
/**
* Modal is a lower-level construct that is leveraged by the following components:
*
* - [Dialog](/api/dialog/)
* - [Drawer](/api/drawer/)
* - [Menu](/api/menu/)
* - [Popover](/api/popover/)
*
* If you are creating a modal dialog, you probably want to use the [Dialog](/api/dialog/) component
* rather than directly using Modal.
*
* This component shares many concepts with [react-overlays](https://react-bootstrap.github.io/react-overlays/#modals).
*/
const Modal = React.forwardRef(function Modal(inProps, ref) {
const theme = useTheme();
const props = getThemeProps({ name: 'MuiModal', props: { ...inProps }, theme });
const {
BackdropComponent = SimpleBackdrop,
BackdropProps,
children,
closeAfterTransition = false,
container,
disableAutoFocus = false,
disableBackdropClick = false,
disableEnforceFocus = false,
disableEscapeKeyDown = false,
disablePortal = false,
disableRestoreFocus = false,
disableScrollLock = false,
hideBackdrop = false,
keepMounted = false,
manager = defaultManager,
onBackdropClick,
onClose,
onEscapeKeyDown,
onRendered,
open,
...other
} = props;
const [exited, setExited] = React.useState(true);
const modal = React.useRef({});
const mountNodeRef = React.useRef(null);
const modalRef = React.useRef(null);
const handleRef = useForkRef(modalRef, ref);
const hasTransition = getHasTransition(props);
const getDoc = () => ownerDocument(mountNodeRef.current);
const getModal = () => {
modal.current.modalRef = modalRef.current;
modal.current.mountNode = mountNodeRef.current;
return modal.current;
};
const handleMounted = () => {
manager.mount(getModal(), { disableScrollLock });
// Fix a bug on Chrome where the scroll isn't initially 0.
modalRef.current.scrollTop = 0;
};
const handleOpen = useEventCallback(() => {
const resolvedContainer = getContainer(container) || getDoc().body;
manager.add(getModal(), resolvedContainer);
// The element was already mounted.
if (modalRef.current) {
handleMounted();
}
});
const isTopModal = React.useCallback(() => manager.isTopModal(getModal()), [manager]);
const handlePortalRef = useEventCallback(node => {
mountNodeRef.current = node;
if (!node) {
return;
}
if (onRendered) {
onRendered();
}
if (open && isTopModal()) {
handleMounted();
} else {
ariaHidden(modalRef.current, true);
}
});
const handleClose = React.useCallback(() => {
manager.remove(getModal());
}, [manager]);
React.useEffect(() => {
return () => {
handleClose();
};
}, [handleClose]);
React.useEffect(() => {
if (open) {
handleOpen();
} else if (!hasTransition || !closeAfterTransition) {
handleClose();
}
}, [open, handleClose, hasTransition, closeAfterTransition, handleOpen]);
if (!keepMounted && !open && (!hasTransition || exited)) {
return null;
}
const handleEnter = () => {
setExited(false);
};
const handleExited = () => {
setExited(true);
if (closeAfterTransition) {
handleClose();
}
};
const handleBackdropClick = event => {
if (event.target !== event.currentTarget) {
return;
}
if (onBackdropClick) {
onBackdropClick(event);
}
if (!disableBackdropClick && onClose) {
onClose(event, 'backdropClick');
}
};
const handleKeyDown = event => {
// The handler doesn't take event.defaultPrevented into account:
//
// event.preventDefault() is meant to stop default behaviours like
// clicking a checkbox to check it, hitting a button to submit a form,
// and hitting left arrow to move the cursor in a text input etc.
// Only special HTML elements have these default behaviors.
if (event.key !== 'Escape' || !isTopModal()) {
return;
}
// Swallow the event, in case someone is listening for the escape key on the body.
event.stopPropagation();
if (onEscapeKeyDown) {
onEscapeKeyDown(event);
}
if (!disableEscapeKeyDown && onClose) {
onClose(event, 'escapeKeyDown');
}
};
const inlineStyle = styles(theme || { zIndex });
const childProps = {};
if (children.props.tabIndex === undefined) {
childProps.tabIndex = children.props.tabIndex || '-1';
}
// It's a Transition like component
if (hasTransition) {
childProps.onEnter = createChainedFunction(handleEnter, children.props.onEnter);
childProps.onExited = createChainedFunction(handleExited, children.props.onExited);
}
return (
<Portal ref={handlePortalRef} container={container} disablePortal={disablePortal}>
{/*
Marking an element with the role presentation indicates to assistive technology
that this element should be ignored; it exists to support the web application and
is not meant for humans to interact with directly.
https://github.com/evcohen/eslint-plugin-jsx-a11y/blob/master/docs/rules/no-static-element-interactions.md
*/}
<div
data-mui-test="Modal"
ref={handleRef}
onKeyDown={handleKeyDown}
role="presentation"
{...other}
style={{
...inlineStyle.root,
...(!open && exited ? inlineStyle.hidden : {}),
...other.style,
}}
>
{hideBackdrop ? null : (
<BackdropComponent open={open} onClick={handleBackdropClick} {...BackdropProps} />
)}
<TrapFocus
disableEnforceFocus={disableEnforceFocus}
disableAutoFocus={disableAutoFocus}
disableRestoreFocus={disableRestoreFocus}
getDoc={getDoc}
isEnabled={isTopModal}
open={open}
>
{React.cloneElement(children, childProps)}
</TrapFocus>
</div>
</Portal>
);
});
Modal.propTypes = {
/**
* A backdrop component. This prop enables custom backdrop rendering.
*/
BackdropComponent: PropTypes.elementType,
/**
* Props applied to the [`Backdrop`](/api/backdrop/) element.
*/
BackdropProps: PropTypes.object,
/**
* A single child content element.
*/
children: elementAcceptingRef.isRequired,
/**
* When set to true the Modal waits until a nested Transition is completed before closing.
*/
closeAfterTransition: PropTypes.bool,
/**
* A node, component instance, or function that returns either.
* The `container` will have the portal children appended to it.
*/
container: PropTypes.oneOfType([PropTypes.object, PropTypes.func]),
/**
* If `true`, the modal will not automatically shift focus to itself when it opens, and
* replace it to the last focused element when it closes.
* This also works correctly with any modal children that have the `disableAutoFocus` prop.
*
* Generally this should never be set to `true` as it makes the modal less
* accessible to assistive technologies, like screen readers.
*/
disableAutoFocus: PropTypes.bool,
/**
* If `true`, clicking the backdrop will not fire any callback.
*/
disableBackdropClick: PropTypes.bool,
/**
* If `true`, the modal will not prevent focus from leaving the modal while open.
*
* Generally this should never be set to `true` as it makes the modal less
* accessible to assistive technologies, like screen readers.
*/
disableEnforceFocus: PropTypes.bool,
/**
* If `true`, hitting escape will not fire any callback.
*/
disableEscapeKeyDown: PropTypes.bool,
/**
* Disable the portal behavior.
* The children stay within it's parent DOM hierarchy.
*/
disablePortal: PropTypes.bool,
/**
* If `true`, the modal will not restore focus to previously focused element once
* modal is hidden.
*/
disableRestoreFocus: PropTypes.bool,
/**
* Disable the scroll lock behavior.
*/
disableScrollLock: PropTypes.bool,
/**
* If `true`, the backdrop is not rendered.
*/
hideBackdrop: PropTypes.bool,
/**
* Always keep the children in the DOM.
* This prop can be useful in SEO situation or
* when you want to maximize the responsiveness of the Modal.
*/
keepMounted: PropTypes.bool,
/**
* @ignore
*/
manager: PropTypes.object,
/**
* Callback fired when the backdrop is clicked.
*/
onBackdropClick: PropTypes.func,
/**
* Callback fired when the component requests to be closed.
* The `reason` parameter can optionally be used to control the response to `onClose`.
*
* @param {object} event The event source of the callback.
* @param {string} reason Can be: `"escapeKeyDown"`, `"backdropClick"`.
*/
onClose: PropTypes.func,
/**
* Callback fired when the escape key is pressed,
* `disableEscapeKeyDown` is false and the modal is in focus.
*/
onEscapeKeyDown: PropTypes.func,
/**
* Callback fired once the children has been mounted into the `container`.
* It signals that the `open={true}` prop took effect.
*
* This prop will be deprecated and removed in v5, the ref can be used instead.
*/
onRendered: PropTypes.func,
/**
* If `true`, the modal is open.
*/
open: PropTypes.bool.isRequired,
};
export default Modal;