import { forwardRef as N, isValidElement as fn, cloneElement as sn, createPortal as j } from '../../../preact/compat/dist/compat.module.mjs';
import useForkRef from '../../utils/esm/useForkRef/useForkRef.mjs';
import getReactElementRef from '../../utils/esm/getReactElementRef/getReactElementRef.mjs';
import useEnhancedEffect from '../../utils/esm/useEnhancedEffect/useEnhancedEffect.mjs';
import setRef from '../../utils/esm/setRef/setRef.mjs';
import { useState as h } from '../../../preact/hooks/dist/hooks.module.mjs';

function getContainer$1(container) {
  return typeof container === 'function' ? container() : container;
}

/**
 * Portals provide a first-class way to render children into a DOM node
 * that exists outside the DOM hierarchy of the parent component.
 *
 * Demos:
 *
 * - [Portal](https://mui.com/material-ui/react-portal/)
 *
 * API:
 *
 * - [Portal API](https://mui.com/material-ui/api/portal/)
 */
const Portal = /*#__PURE__*/N(function Portal(props, forwardedRef) {
  const {
    children,
    container,
    disablePortal = false
  } = props;
  const [mountNode, setMountNode] = h(null);
  const handleRef = useForkRef(/*#__PURE__*/fn(children) ? getReactElementRef(children) : null, forwardedRef);
  useEnhancedEffect(() => {
    if (!disablePortal) {
      setMountNode(getContainer$1(container) || document.body);
    }
  }, [container, disablePortal]);
  useEnhancedEffect(() => {
    if (mountNode && !disablePortal) {
      setRef(forwardedRef, mountNode);
      return () => {
        setRef(forwardedRef, null);
      };
    }
    return undefined;
  }, [forwardedRef, mountNode, disablePortal]);
  if (disablePortal) {
    if (/*#__PURE__*/fn(children)) {
      const newProps = {
        ref: handleRef
      };
      return /*#__PURE__*/sn(children, newProps);
    }
    return children;
  }
  return mountNode ? /*#__PURE__*/j(children, mountNode) : mountNode;
});

export { Portal as default };
//# sourceMappingURL=Portal.mjs.map
