"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.EuiPortal = void 0;
var _react = require("react");
var _propTypes = _interopRequireDefault(require("prop-types"));
var _reactDom = require("react-dom");
var _services = require("../../services");
var _component_defaults = require("../provider/component_defaults");
function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
function _slicedToArray(r, e) { return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest(); }
function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } }
function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; }
function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } }
function _arrayWithHoles(r) { if (Array.isArray(r)) return r; } /*
 * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
 * or more contributor license agreements. Licensed under the Elastic License
 * 2.0 and the Server Side Public License, v 1; you may not use this file except
 * in compliance with, at your election, the Elastic License 2.0 or the Server
 * Side Public License, v 1.
 */
var usePortalEffect = typeof document === 'undefined' ? _react.useEffect : _react.useLayoutEffect;
var INSERT_POSITIONS = ['after', 'before'];
var insertPositions = {
  after: 'afterend',
  before: 'beforebegin'
};
var EuiPortal = exports.EuiPortal = /*#__PURE__*/(0, _react.memo)(function (_props) {
  var props = (0, _component_defaults.usePropsWithComponentDefaults)('EuiPortal', _props);
  var children = props.children,
    insert = props.insert,
    setPortalRef = props.portalRef;
  var portalRef = (0, _react.useRef)(setPortalRef);
  var _useContext = (0, _react.useContext)(_services.EuiNestedThemeContext),
    hasDifferentColorFromGlobalTheme = _useContext.hasDifferentColorFromGlobalTheme,
    colorClassName = _useContext.colorClassName;
  var _useState = (0, _react.useState)(null),
    _useState2 = _slicedToArray(_useState, 2),
    portalNode = _useState2[0],
    setPortalNode = _useState2[1];

  // Set the inherited color of the portal based on the wrapping EuiThemeProvider
  var setThemeColor = function setThemeColor(portalNode) {
    if (hasDifferentColorFromGlobalTheme && insert == null) {
      portalNode.classList.add(colorClassName);
    }
  };
  var updatePortalRef = function updatePortalRef(ref) {
    var _portalRef$current;
    (_portalRef$current = portalRef.current) === null || _portalRef$current === void 0 || _portalRef$current.call(portalRef, ref);
  };
  (0, _react.useEffect)(function () {
    portalRef.current = setPortalRef;
  }, [setPortalRef]);

  /* Uses `useLayoutEffect` on client-side instead of `useEffect` to ensure the portal
  node is created and inserted into the DOM synchronously. This matches the same timing
  as the previous class component `componentDidMount` behavior.
  Using `useEffect` would add an additional render cycle that would break expected
  behavior of e.g. `@hello-pangea/dnd` which handles keyboard focus and doesn't expect
  a rerender. This falls back to `useEffect` for SSR to avoid console errors. `useEffect` will
  be a no-op, same as `componentDidMount` */
  usePortalEffect(function () {
    var node = document.createElement('div');
    node.dataset.euiportal = 'true';
    if (insert == null) {
      // no insertion defined, append to body
      document.body.appendChild(node);
    } else {
      // inserting before or after an element
      var sibling = insert.sibling,
        position = insert.position;
      sibling.insertAdjacentElement(insertPositions[position], node);
    }
    setThemeColor(node);
    updatePortalRef(node);

    // Update state with portalNode to intentionally trigger component rerender
    // and call createPortal with the correct root element
    setPortalNode(node);
    return function () {
      if (node !== null && node !== void 0 && node.parentNode) {
        node.parentNode.removeChild(node);
      }
      updatePortalRef(null);
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps -- on mount only
  }, []);
  if (!portalNode) {
    return null;
  }
  return /*#__PURE__*/(0, _reactDom.createPortal)(children, portalNode);
});
EuiPortal.propTypes = {
  /**
     * ReactNode to render as this component's content
     */
  children: _propTypes.default.node.isRequired,
  /**
     * If not specified, `EuiPortal` will insert itself
     * into the end of the `document.body` by default
     */
  insert: _propTypes.default.shape({
    sibling: _propTypes.default.any.isRequired,
    position: _propTypes.default.any.isRequired
  }),
  /**
     * Optional ref callback
     */
  portalRef: _propTypes.default.func
};
EuiPortal.displayName = 'EuiPortal';