"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.Portal = void 0;

var _react = require("react");

var _reactDom = require("react-dom");

var _useEnhancedEffect = require("../hooks/useEnhancedEffect");

var _useForkRef = require("../hooks/useForkRef");

var _setRef = require("../utils/setRef");

/**
 * Portal Component
 *
 * The following code is a derivative of the amazing work done by the Material UI team.
 * Original source: https://github.com/mui-org/material-ui/blob/master/packages/material-ui/src/Portal/Portal.js
 */
function getContainer(container) {
  var newContainer = typeof container === 'function' ? container() : container;
  return newContainer;
}

var Portal = /*#__PURE__*/(0, _react.forwardRef)(function (_ref, ref) {
  var children = _ref.children,
      container = _ref.container,
      _ref$isDisabled = _ref.isDisabled,
      isDisabled = _ref$isDisabled === void 0 ? false : _ref$isDisabled,
      onRendered = _ref.onRendered;

  var _useState = (0, _react.useState)(null),
      mountNode = _useState[0],
      setMountNode = _useState[1];

  var childRef = (0, _react.useRef)(children);
  var handleRef = (0, _useForkRef.useForkRef)(childRef, ref);
  (0, _useEnhancedEffect.useEnhancedEffect)(function () {
    if (!isDisabled) {
      setMountNode(getContainer(container) || document.body);
    }
  }, [container, isDisabled]);
  (0, _useEnhancedEffect.useEnhancedEffect)(function () {
    if (mountNode && !isDisabled) {
      (0, _setRef.setRef)(ref, mountNode);
      return function () {
        (0, _setRef.setRef)(ref, null);
      };
    }

    return undefined;
  }, [ref, mountNode, isDisabled]);
  (0, _useEnhancedEffect.useEnhancedEffect)(function () {
    if (onRendered && (mountNode || isDisabled)) {
      onRendered();
    }
  }, [onRendered, mountNode, isDisabled]);

  if (isDisabled) {
    _react.Children.only(children);

    return /*#__PURE__*/(0, _react.cloneElement)(children, {
      ref: handleRef
    });
  }

  return mountNode ? /*#__PURE__*/(0, _reactDom.createPortal)(children, mountNode) : mountNode;
});
exports.Portal = Portal;
//# sourceMappingURL=Portal.js.map