UNPKG

14.6 kBJavaScriptView Raw
1"use strict";
2
3var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
4Object.defineProperty(exports, "__esModule", {
5 value: true
6});
7exports.default = void 0;
8var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));
9var _objectWithoutPropertiesLoose2 = _interopRequireDefault(require("@babel/runtime/helpers/objectWithoutPropertiesLoose"));
10var React = _interopRequireWildcard(require("react"));
11var _propTypes = _interopRequireDefault(require("prop-types"));
12var _utils = require("@mui/utils");
13var _composeClasses = _interopRequireDefault(require("../composeClasses"));
14var _Portal = _interopRequireDefault(require("../Portal"));
15var _ModalManager = _interopRequireWildcard(require("./ModalManager"));
16var _FocusTrap = _interopRequireDefault(require("../FocusTrap"));
17var _modalClasses = require("./modalClasses");
18var _utils2 = require("../utils");
19var _ClassNameConfigurator = require("../utils/ClassNameConfigurator");
20var _jsxRuntime = require("react/jsx-runtime");
21const _excluded = ["children", "closeAfterTransition", "container", "disableAutoFocus", "disableEnforceFocus", "disableEscapeKeyDown", "disablePortal", "disableRestoreFocus", "disableScrollLock", "hideBackdrop", "keepMounted", "manager", "onBackdropClick", "onClose", "onKeyDown", "open", "onTransitionEnter", "onTransitionExited", "slotProps", "slots"];
22function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
23function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
24const useUtilityClasses = ownerState => {
25 const {
26 open,
27 exited
28 } = ownerState;
29 const slots = {
30 root: ['root', !open && exited && 'hidden'],
31 backdrop: ['backdrop']
32 };
33 return (0, _composeClasses.default)(slots, (0, _ClassNameConfigurator.useClassNamesOverride)(_modalClasses.getModalUtilityClass));
34};
35function getContainer(container) {
36 return typeof container === 'function' ? container() : container;
37}
38function getHasTransition(children) {
39 return children ? children.props.hasOwnProperty('in') : false;
40}
41
42// A modal manager used to track and manage the state of open Modals.
43// Modals don't open on the server so this won't conflict with concurrent requests.
44const defaultManager = new _ModalManager.default();
45
46/**
47 * Modal is a lower-level construct that is leveraged by the following components:
48 *
49 * * [Dialog](https://mui.com/material-ui/api/dialog/)
50 * * [Drawer](https://mui.com/material-ui/api/drawer/)
51 * * [Menu](https://mui.com/material-ui/api/menu/)
52 * * [Popover](https://mui.com/material-ui/api/popover/)
53 *
54 * If you are creating a modal dialog, you probably want to use the [Dialog](https://mui.com/material-ui/api/dialog/) component
55 * rather than directly using Modal.
56 *
57 * This component shares many concepts with [react-overlays](https://react-bootstrap.github.io/react-overlays/#modals).
58 *
59 * Demos:
60 *
61 * - [Modal](https://mui.com/base/react-modal/)
62 *
63 * API:
64 *
65 * - [Modal API](https://mui.com/base/react-modal/components-api/#modal)
66 */
67const Modal = /*#__PURE__*/React.forwardRef(function Modal(props, forwardedRef) {
68 var _props$ariaHidden, _slots$root;
69 const {
70 children,
71 closeAfterTransition = false,
72 container,
73 disableAutoFocus = false,
74 disableEnforceFocus = false,
75 disableEscapeKeyDown = false,
76 disablePortal = false,
77 disableRestoreFocus = false,
78 disableScrollLock = false,
79 hideBackdrop = false,
80 keepMounted = false,
81 // private
82 manager: managerProp = defaultManager,
83 onBackdropClick,
84 onClose,
85 onKeyDown,
86 open,
87 onTransitionEnter,
88 onTransitionExited,
89 slotProps = {},
90 slots = {}
91 } = props,
92 other = (0, _objectWithoutPropertiesLoose2.default)(props, _excluded);
93 // TODO: `modal`` must change its type in this file to match the type of methods
94 // provided by `ModalManager`
95 const manager = managerProp;
96 const [exited, setExited] = React.useState(!open);
97 const modal = React.useRef({});
98 const mountNodeRef = React.useRef(null);
99 const modalRef = React.useRef(null);
100 const handleRef = (0, _utils.unstable_useForkRef)(modalRef, forwardedRef);
101 const hasTransition = getHasTransition(children);
102 const ariaHiddenProp = (_props$ariaHidden = props['aria-hidden']) != null ? _props$ariaHidden : true;
103 const getDoc = () => (0, _utils.unstable_ownerDocument)(mountNodeRef.current);
104 const getModal = () => {
105 modal.current.modalRef = modalRef.current;
106 modal.current.mountNode = mountNodeRef.current;
107 return modal.current;
108 };
109 const handleMounted = () => {
110 manager.mount(getModal(), {
111 disableScrollLock
112 });
113
114 // Fix a bug on Chrome where the scroll isn't initially 0.
115 if (modalRef.current) {
116 modalRef.current.scrollTop = 0;
117 }
118 };
119 const handleOpen = (0, _utils.unstable_useEventCallback)(() => {
120 const resolvedContainer = getContainer(container) || getDoc().body;
121 manager.add(getModal(), resolvedContainer);
122
123 // The element was already mounted.
124 if (modalRef.current) {
125 handleMounted();
126 }
127 });
128 const isTopModal = React.useCallback(() => manager.isTopModal(getModal()), [manager]);
129 const handlePortalRef = (0, _utils.unstable_useEventCallback)(node => {
130 mountNodeRef.current = node;
131 if (!node || !modalRef.current) {
132 return;
133 }
134 if (open && isTopModal()) {
135 handleMounted();
136 } else {
137 (0, _ModalManager.ariaHidden)(modalRef.current, ariaHiddenProp);
138 }
139 });
140 const handleClose = React.useCallback(() => {
141 manager.remove(getModal(), ariaHiddenProp);
142 }, [manager, ariaHiddenProp]);
143 React.useEffect(() => {
144 return () => {
145 handleClose();
146 };
147 }, [handleClose]);
148 React.useEffect(() => {
149 if (open) {
150 handleOpen();
151 } else if (!hasTransition || !closeAfterTransition) {
152 handleClose();
153 }
154 }, [open, handleClose, hasTransition, closeAfterTransition, handleOpen]);
155 const ownerState = (0, _extends2.default)({}, props, {
156 closeAfterTransition,
157 disableAutoFocus,
158 disableEnforceFocus,
159 disableEscapeKeyDown,
160 disablePortal,
161 disableRestoreFocus,
162 disableScrollLock,
163 exited,
164 hideBackdrop,
165 keepMounted
166 });
167 const classes = useUtilityClasses(ownerState);
168 const handleEnter = () => {
169 setExited(false);
170 if (onTransitionEnter) {
171 onTransitionEnter();
172 }
173 };
174 const handleExited = () => {
175 setExited(true);
176 if (onTransitionExited) {
177 onTransitionExited();
178 }
179 if (closeAfterTransition) {
180 handleClose();
181 }
182 };
183 const handleBackdropClick = event => {
184 if (event.target !== event.currentTarget) {
185 return;
186 }
187 if (onBackdropClick) {
188 onBackdropClick(event);
189 }
190 if (onClose) {
191 onClose(event, 'backdropClick');
192 }
193 };
194 const handleKeyDown = event => {
195 if (onKeyDown) {
196 onKeyDown(event);
197 }
198
199 // The handler doesn't take event.defaultPrevented into account:
200 //
201 // event.preventDefault() is meant to stop default behaviors like
202 // clicking a checkbox to check it, hitting a button to submit a form,
203 // and hitting left arrow to move the cursor in a text input etc.
204 // Only special HTML elements have these default behaviors.
205 if (event.key !== 'Escape' || !isTopModal()) {
206 return;
207 }
208 if (!disableEscapeKeyDown) {
209 // Swallow the event, in case someone is listening for the escape key on the body.
210 event.stopPropagation();
211 if (onClose) {
212 onClose(event, 'escapeKeyDown');
213 }
214 }
215 };
216 const childProps = {};
217 if (children.props.tabIndex === undefined) {
218 childProps.tabIndex = '-1';
219 }
220
221 // It's a Transition like component
222 if (hasTransition) {
223 childProps.onEnter = (0, _utils.unstable_createChainedFunction)(handleEnter, children.props.onEnter);
224 childProps.onExited = (0, _utils.unstable_createChainedFunction)(handleExited, children.props.onExited);
225 }
226 const Root = (_slots$root = slots.root) != null ? _slots$root : 'div';
227 const rootProps = (0, _utils2.useSlotProps)({
228 elementType: Root,
229 externalSlotProps: slotProps.root,
230 externalForwardedProps: other,
231 additionalProps: {
232 ref: handleRef,
233 role: 'presentation',
234 onKeyDown: handleKeyDown
235 },
236 className: classes.root,
237 ownerState
238 });
239 const BackdropComponent = slots.backdrop;
240 const backdropProps = (0, _utils2.useSlotProps)({
241 elementType: BackdropComponent,
242 externalSlotProps: slotProps.backdrop,
243 additionalProps: {
244 'aria-hidden': true,
245 onClick: handleBackdropClick,
246 open
247 },
248 className: classes.backdrop,
249 ownerState
250 });
251 if (!keepMounted && !open && (!hasTransition || exited)) {
252 return null;
253 }
254 return /*#__PURE__*/(0, _jsxRuntime.jsx)(_Portal.default
255 // @ts-expect-error TODO: include ref to Base UI Portal props
256 , {
257 ref: handlePortalRef,
258 container: container,
259 disablePortal: disablePortal,
260 children: /*#__PURE__*/(0, _jsxRuntime.jsxs)(Root, (0, _extends2.default)({}, rootProps, {
261 children: [!hideBackdrop && BackdropComponent ? /*#__PURE__*/(0, _jsxRuntime.jsx)(BackdropComponent, (0, _extends2.default)({}, backdropProps)) : null, /*#__PURE__*/(0, _jsxRuntime.jsx)(_FocusTrap.default, {
262 disableEnforceFocus: disableEnforceFocus,
263 disableAutoFocus: disableAutoFocus,
264 disableRestoreFocus: disableRestoreFocus,
265 isEnabled: isTopModal,
266 open: open,
267 children: /*#__PURE__*/React.cloneElement(children, childProps)
268 })]
269 }))
270 });
271});
272process.env.NODE_ENV !== "production" ? Modal.propTypes /* remove-proptypes */ = {
273 // ----------------------------- Warning --------------------------------
274 // | These PropTypes are generated from the TypeScript type definitions |
275 // | To update them edit TypeScript types and run "yarn proptypes" |
276 // ----------------------------------------------------------------------
277 /**
278 * A single child content element.
279 */
280 children: _utils.elementAcceptingRef.isRequired,
281 /**
282 * When set to true the Modal waits until a nested Transition is completed before closing.
283 * @default false
284 */
285 closeAfterTransition: _propTypes.default.bool,
286 /**
287 * An HTML element or function that returns one.
288 * The `container` will have the portal children appended to it.
289 *
290 * By default, it uses the body of the top-level document object,
291 * so it's simply `document.body` most of the time.
292 */
293 container: _propTypes.default /* @typescript-to-proptypes-ignore */.oneOfType([_utils.HTMLElementType, _propTypes.default.func]),
294 /**
295 * If `true`, the modal will not automatically shift focus to itself when it opens, and
296 * replace it to the last focused element when it closes.
297 * This also works correctly with any modal children that have the `disableAutoFocus` prop.
298 *
299 * Generally this should never be set to `true` as it makes the modal less
300 * accessible to assistive technologies, like screen readers.
301 * @default false
302 */
303 disableAutoFocus: _propTypes.default.bool,
304 /**
305 * If `true`, the modal will not prevent focus from leaving the modal while open.
306 *
307 * Generally this should never be set to `true` as it makes the modal less
308 * accessible to assistive technologies, like screen readers.
309 * @default false
310 */
311 disableEnforceFocus: _propTypes.default.bool,
312 /**
313 * If `true`, hitting escape will not fire the `onClose` callback.
314 * @default false
315 */
316 disableEscapeKeyDown: _propTypes.default.bool,
317 /**
318 * The `children` will be under the DOM hierarchy of the parent component.
319 * @default false
320 */
321 disablePortal: _propTypes.default.bool,
322 /**
323 * If `true`, the modal will not restore focus to previously focused element once
324 * modal is hidden or unmounted.
325 * @default false
326 */
327 disableRestoreFocus: _propTypes.default.bool,
328 /**
329 * Disable the scroll lock behavior.
330 * @default false
331 */
332 disableScrollLock: _propTypes.default.bool,
333 /**
334 * If `true`, the backdrop is not rendered.
335 * @default false
336 */
337 hideBackdrop: _propTypes.default.bool,
338 /**
339 * Always keep the children in the DOM.
340 * This prop can be useful in SEO situation or
341 * when you want to maximize the responsiveness of the Modal.
342 * @default false
343 */
344 keepMounted: _propTypes.default.bool,
345 /**
346 * Callback fired when the backdrop is clicked.
347 * @deprecated Use the `onClose` prop with the `reason` argument to handle the `backdropClick` events.
348 */
349 onBackdropClick: _propTypes.default.func,
350 /**
351 * Callback fired when the component requests to be closed.
352 * The `reason` parameter can optionally be used to control the response to `onClose`.
353 *
354 * @param {object} event The event source of the callback.
355 * @param {string} reason Can be: `"escapeKeyDown"`, `"backdropClick"`.
356 */
357 onClose: _propTypes.default.func,
358 /**
359 * If `true`, the component is shown.
360 */
361 open: _propTypes.default.bool.isRequired,
362 /**
363 * The props used for each slot inside the Modal.
364 * @default {}
365 */
366 slotProps: _propTypes.default.shape({
367 backdrop: _propTypes.default.oneOfType([_propTypes.default.func, _propTypes.default.object]),
368 root: _propTypes.default.oneOfType([_propTypes.default.func, _propTypes.default.object])
369 }),
370 /**
371 * The components used for each slot inside the Modal.
372 * Either a string to use a HTML element or a component.
373 * @default {}
374 */
375 slots: _propTypes.default.shape({
376 backdrop: _propTypes.default.elementType,
377 root: _propTypes.default.elementType
378 })
379} : void 0;
380var _default = Modal;
381exports.default = _default;
\No newline at end of file