import React, { useContext, useEffect } from "react";
import { EditorContext, RicosContext } from "./../../ricos-context/index.js";
import { useModalService, useModalState } from "./../modal-service-provider.js";
import { logInvariant } from "./../../_shared/log-invariant.js";
import { ModalPopper } from "./modal-popper.js";
const ModalRenderer = () => {
  const openModals = useModalState((s) => s);
  const modalService = useModalService();
  const { getPublicCommands } = useContext(EditorContext);
  const { lastInteraction } = useContext(RicosContext);
  useEffect(() => {
    const modalClosedSubscription = modalService.onModalClosed((modal) => {
      setTimeout(() => {
        if (lastInteraction === "mouse" && !modal.returnFocusToEditor) {
          return;
        }
        const refElement = modal.focusReturnElement || modal.positioning?.referenceElement;
        if (lastInteraction === "keyboard" && refElement && refElement instanceof HTMLElement) {
          try {
            refElement.focus();
            return;
          } catch {
            logInvariant(new Error("Failed to focus on modal return element"));
          }
        }
        getPublicCommands().focus();
      }, 0);
    });
    return () => {
      modalClosedSubscription.cancel();
    };
  }, [lastInteraction]);
  return /* @__PURE__ */ React.createElement(React.Fragment, null, Object.values(openModals).map((modalConfig) => {
    return /* @__PURE__ */ React.createElement(
      ModalPopper,
      {
        key: modalConfig.id,
        modalConfig,
        setModalRef: (ref) => modalService.setModalRef(modalConfig.id, ref)
      }
    );
  }));
};
export {
  ModalRenderer
};
//# sourceMappingURL=modal-renderer.js.map
