'use strict';

var AOQQTIBO = require('./AOQQTIBO.cjs');
var W3VI7GFU = require('./W3VI7GFU.cjs');
var LMDWO4NN = require('./LMDWO4NN.cjs');
var ABQUS43J = require('./ABQUS43J.cjs');
var SK3NAZA3 = require('./SK3NAZA3.cjs');
var _3YLGPPWQ = require('./3YLGPPWQ.cjs');
var DTR5TSDJ = require('../../../../../../@ariakit_core@0.4.15/node_modules/@ariakit/core/esm/__chunks/DTR5TSDJ.cjs');
var events = require('../../../../../../@ariakit_core@0.4.15/node_modules/@ariakit/core/esm/utils/events.cjs');
var focus = require('../../../../../../@ariakit_core@0.4.15/node_modules/@ariakit/core/esm/utils/focus.cjs');
var React = require('react');
var ReactDOM = require('react-dom');
var jsxRuntime = require('../../../../../../react@18.2.0/node_modules/react/jsx-runtime.cjs');

var TagName = "div";
function getRootElement(element) {
  return DTR5TSDJ.getDocument(element).body;
}
function getPortalElement(element, portalElement) {
  if (!portalElement) {
    return DTR5TSDJ.getDocument(element).createElement("div");
  }
  if (typeof portalElement === "function") {
    return portalElement(element);
  }
  return portalElement;
}
function getRandomId(prefix = "id") {
  return `${prefix ? `${prefix}-` : ""}${Math.random().toString(36).slice(2, 8)}`;
}
function queueFocus(element) {
  queueMicrotask(() => {
    element == null ? void 0 : element.focus();
  });
}
var usePortal = LMDWO4NN.createHook(function usePortal2(_a) {
  var _b = _a, {
    preserveTabOrder,
    preserveTabOrderAnchor,
    portalElement,
    portalRef,
    portal = true
  } = _b, props = _3YLGPPWQ.__objRest(_b, [
    "preserveTabOrder",
    "preserveTabOrderAnchor",
    "portalElement",
    "portalRef",
    "portal"
  ]);
  const ref = React.useRef(null);
  const refProp = ABQUS43J.useMergeRefs(ref, props.ref);
  const context = React.useContext(AOQQTIBO.PortalContext);
  const [portalNode, setPortalNode] = React.useState(null);
  const [anchorPortalNode, setAnchorPortalNode] = React.useState(
    null
  );
  const outerBeforeRef = React.useRef(null);
  const innerBeforeRef = React.useRef(null);
  const innerAfterRef = React.useRef(null);
  const outerAfterRef = React.useRef(null);
  ABQUS43J.useSafeLayoutEffect(() => {
    const element = ref.current;
    if (!element || !portal) {
      setPortalNode(null);
      return;
    }
    const portalEl = getPortalElement(element, portalElement);
    if (!portalEl) {
      setPortalNode(null);
      return;
    }
    const isPortalInDocument = portalEl.isConnected;
    if (!isPortalInDocument) {
      const rootElement = context || getRootElement(element);
      rootElement.appendChild(portalEl);
    }
    if (!portalEl.id) {
      portalEl.id = element.id ? `portal/${element.id}` : getRandomId();
    }
    setPortalNode(portalEl);
    SK3NAZA3.setRef(portalRef, portalEl);
    if (isPortalInDocument) return;
    return () => {
      portalEl.remove();
      SK3NAZA3.setRef(portalRef, null);
    };
  }, [portal, portalElement, context, portalRef]);
  ABQUS43J.useSafeLayoutEffect(() => {
    if (!portal) return;
    if (!preserveTabOrder) return;
    if (!preserveTabOrderAnchor) return;
    const doc = DTR5TSDJ.getDocument(preserveTabOrderAnchor);
    const element = doc.createElement("span");
    element.style.position = "fixed";
    preserveTabOrderAnchor.insertAdjacentElement("afterend", element);
    setAnchorPortalNode(element);
    return () => {
      element.remove();
      setAnchorPortalNode(null);
    };
  }, [portal, preserveTabOrder, preserveTabOrderAnchor]);
  React.useEffect(() => {
    if (!portalNode) return;
    if (!preserveTabOrder) return;
    let raf = 0;
    const onFocus = (event) => {
      if (!events.isFocusEventOutside(event)) return;
      const focusing = event.type === "focusin";
      cancelAnimationFrame(raf);
      if (focusing) {
        return focus.restoreFocusIn(portalNode);
      }
      raf = requestAnimationFrame(() => {
        focus.disableFocusIn(portalNode, true);
      });
    };
    portalNode.addEventListener("focusin", onFocus, true);
    portalNode.addEventListener("focusout", onFocus, true);
    return () => {
      cancelAnimationFrame(raf);
      portalNode.removeEventListener("focusin", onFocus, true);
      portalNode.removeEventListener("focusout", onFocus, true);
    };
  }, [portalNode, preserveTabOrder]);
  props = ABQUS43J.useWrapElement(
    props,
    (element) => {
      element = // While the portal node is not in the DOM, we need to pass the
      // current context to the portal context, otherwise it's going to
      // reset to the body element on nested portals.
      /* @__PURE__ */ jsxRuntime.jsxRuntimeExports.jsx(AOQQTIBO.PortalContext.Provider, { value: portalNode || context, children: element });
      if (!portal) return element;
      if (!portalNode) {
        return /* @__PURE__ */ jsxRuntime.jsxRuntimeExports.jsx(
          "span",
          {
            ref: refProp,
            id: props.id,
            style: { position: "fixed" },
            hidden: true
          }
        );
      }
      element = /* @__PURE__ */ jsxRuntime.jsxRuntimeExports.jsxs(jsxRuntime.jsxRuntimeExports.Fragment, { children: [
        preserveTabOrder && portalNode && /* @__PURE__ */ jsxRuntime.jsxRuntimeExports.jsx(
          W3VI7GFU.FocusTrap,
          {
            ref: innerBeforeRef,
            "data-focus-trap": props.id,
            className: "__focus-trap-inner-before",
            onFocus: (event) => {
              if (events.isFocusEventOutside(event, portalNode)) {
                queueFocus(focus.getNextTabbable());
              } else {
                queueFocus(outerBeforeRef.current);
              }
            }
          }
        ),
        element,
        preserveTabOrder && portalNode && /* @__PURE__ */ jsxRuntime.jsxRuntimeExports.jsx(
          W3VI7GFU.FocusTrap,
          {
            ref: innerAfterRef,
            "data-focus-trap": props.id,
            className: "__focus-trap-inner-after",
            onFocus: (event) => {
              if (events.isFocusEventOutside(event, portalNode)) {
                queueFocus(focus.getPreviousTabbable());
              } else {
                queueFocus(outerAfterRef.current);
              }
            }
          }
        )
      ] });
      if (portalNode) {
        element = ReactDOM.createPortal(element, portalNode);
      }
      let preserveTabOrderElement = /* @__PURE__ */ jsxRuntime.jsxRuntimeExports.jsxs(jsxRuntime.jsxRuntimeExports.Fragment, { children: [
        preserveTabOrder && portalNode && /* @__PURE__ */ jsxRuntime.jsxRuntimeExports.jsx(
          W3VI7GFU.FocusTrap,
          {
            ref: outerBeforeRef,
            "data-focus-trap": props.id,
            className: "__focus-trap-outer-before",
            onFocus: (event) => {
              const fromOuter = event.relatedTarget === outerAfterRef.current;
              if (!fromOuter && events.isFocusEventOutside(event, portalNode)) {
                queueFocus(innerBeforeRef.current);
              } else {
                queueFocus(focus.getPreviousTabbable());
              }
            }
          }
        ),
        preserveTabOrder && // We're using position: fixed here so that the browser doesn't
        // add margin to the element when setting gap on a parent element.
        /* @__PURE__ */ jsxRuntime.jsxRuntimeExports.jsx("span", { "aria-owns": portalNode == null ? void 0 : portalNode.id, style: { position: "fixed" } }),
        preserveTabOrder && portalNode && /* @__PURE__ */ jsxRuntime.jsxRuntimeExports.jsx(
          W3VI7GFU.FocusTrap,
          {
            ref: outerAfterRef,
            "data-focus-trap": props.id,
            className: "__focus-trap-outer-after",
            onFocus: (event) => {
              if (events.isFocusEventOutside(event, portalNode)) {
                queueFocus(innerAfterRef.current);
              } else {
                const nextTabbable = focus.getNextTabbable();
                if (nextTabbable === innerBeforeRef.current) {
                  requestAnimationFrame(() => {
                    var _a2;
                    return (_a2 = focus.getNextTabbable()) == null ? void 0 : _a2.focus();
                  });
                  return;
                }
                queueFocus(nextTabbable);
              }
            }
          }
        )
      ] });
      if (anchorPortalNode && preserveTabOrder) {
        preserveTabOrderElement = ReactDOM.createPortal(
          preserveTabOrderElement,
          anchorPortalNode
        );
      }
      return /* @__PURE__ */ jsxRuntime.jsxRuntimeExports.jsxs(jsxRuntime.jsxRuntimeExports.Fragment, { children: [
        preserveTabOrderElement,
        element
      ] });
    },
    [portalNode, context, portal, props.id, preserveTabOrder, anchorPortalNode]
  );
  props = _3YLGPPWQ.__spreadProps(_3YLGPPWQ.__spreadValues({}, props), {
    ref: refProp
  });
  return props;
});
LMDWO4NN.forwardRef(function Portal2(props) {
  const htmlProps = usePortal(props);
  return LMDWO4NN.createElement(TagName, htmlProps);
});

exports.usePortal = usePortal;
//# sourceMappingURL=WAGAC6PJ.cjs.map
