import { _ as _slicedToArray } from '../slicedToArray-BB-AwwkK.js';
import { _ as _extends } from '../extends-C4cduGrv.js';
import { _ as _objectWithoutProperties } from '../objectWithoutProperties-TXwlfNxG.js';
import React__default, { createContext, useRef, useState, useEffect, useContext } from 'react';
import { createPortal } from 'react-dom';
import useRerenderOnce from '../use-rerender-once/index.js';
import '../use-force-update/index.js';

var _excluded = ["children"];

var canUseDOM = function canUseDOM() {
  return typeof window !== "undefined" && window.document;
};

var StackingContext = /*#__PURE__*/createContext();
function PortalNode(_ref) {
  var children = _ref.children,
      props = _objectWithoutProperties(_ref, _excluded);

  useRerenderOnce();
  var node = useRef();
  return /*#__PURE__*/React__default.createElement(StackingContext.Provider, {
    value: node.current
  }, /*#__PURE__*/React__default.createElement("div", _extends({}, props, {
    ref: node
  }), " ", children));
} // Each Portal creates a new StackingContext, currently with no way to opt-out
// of this behavior. This means that anything rendered inside a nested portal
// will use the root of the previous portal.

function useRootNode() {
  return useContext(StackingContext) || document.body;
}

function DOMPortal(_ref2) {
  var children = _ref2.children;
  var rootNode = useRootNode();

  var _useState = useState(function () {
    return document.createElement("div");
  }),
      _useState2 = _slicedToArray(_useState, 1),
      node = _useState2[0];

  useEffect(function () {
    rootNode.appendChild(node);
    return function () {
      node.remove();
    };
  }, [rootNode, node]);
  return /*#__PURE__*/React__default.createElement(StackingContext.Provider, {
    value: node
  }, /*#__PURE__*/createPortal(children, node));
}

function ServerPortal() {
  return null;
}

function Portal(_ref3) {
  var children = _ref3.children;
  return canUseDOM() ? /*#__PURE__*/React__default.createElement(DOMPortal, null, children) : /*#__PURE__*/React__default.createElement(ServerPortal, null);
}

export { PortalNode, StackingContext, Portal as default };
