1 | import * as React from 'react';
|
2 | import * as ReactDOM from 'react-dom';
|
3 | import PropTypes from 'prop-types';
|
4 | import { exactProp, HTMLElementType, unstable_useEnhancedEffect as useEnhancedEffect, unstable_useForkRef as useForkRef, unstable_setRef as setRef } from '@mui/utils';
|
5 |
|
6 | function getContainer(container) {
|
7 | return typeof container === 'function' ? container() : container;
|
8 | }
|
9 |
|
10 |
|
11 |
|
12 |
|
13 |
|
14 |
|
15 | const Portal = React.forwardRef(function Portal(props, ref) {
|
16 | const {
|
17 | children,
|
18 | container,
|
19 | disablePortal = false
|
20 | } = props;
|
21 | const [mountNode, setMountNode] = React.useState(null);
|
22 | const handleRef = useForkRef( React.isValidElement(children) ? children.ref : null, ref);
|
23 | useEnhancedEffect(() => {
|
24 | if (!disablePortal) {
|
25 | setMountNode(getContainer(container) || document.body);
|
26 | }
|
27 | }, [container, disablePortal]);
|
28 | useEnhancedEffect(() => {
|
29 | if (mountNode && !disablePortal) {
|
30 | setRef(ref, mountNode);
|
31 | return () => {
|
32 | setRef(ref, null);
|
33 | };
|
34 | }
|
35 |
|
36 | return undefined;
|
37 | }, [ref, mountNode, disablePortal]);
|
38 |
|
39 | if (disablePortal) {
|
40 | if ( React.isValidElement(children)) {
|
41 | return React.cloneElement(children, {
|
42 | ref: handleRef
|
43 | });
|
44 | }
|
45 |
|
46 | return children;
|
47 | }
|
48 |
|
49 | return mountNode ? ReactDOM.createPortal(children, mountNode) : mountNode;
|
50 | });
|
51 | process.env.NODE_ENV !== "production" ? Portal.propTypes
|
52 |
|
53 | = {
|
54 |
|
55 |
|
56 |
|
57 |
|
58 |
|
59 | |
60 |
|
61 |
|
62 | children: PropTypes.node,
|
63 |
|
64 | |
65 |
|
66 |
|
67 |
|
68 |
|
69 |
|
70 |
|
71 | container: PropTypes
|
72 |
|
73 | .oneOfType([HTMLElementType, PropTypes.func]),
|
74 |
|
75 | |
76 |
|
77 |
|
78 |
|
79 | disablePortal: PropTypes.bool
|
80 | } : void 0;
|
81 |
|
82 | if (process.env.NODE_ENV !== 'production') {
|
83 |
|
84 | Portal['propTypes' + ''] = exactProp(Portal.propTypes);
|
85 | }
|
86 |
|
87 | export default Portal; |
\ | No newline at end of file |