import { useEditor, useValue } from "@cmpd/editor";
import { useCallback, useEffect, useRef } from "react";
import { useUiEvents } from "./useEventsProvider.mjs";
function useMenuIsOpen(id, cb) {
  const editor = useEditor();
  const rIsOpen = useRef(false);
  const trackEvent = useUiEvents();
  const rLastChange = useRef(0);
  const onOpenChange = useCallback(
    (isOpen2) => {
      const now = Date.now();
      if (now - rLastChange.current < 50)
        return;
      rLastChange.current = now;
      rIsOpen.current = isOpen2;
      editor.batch(() => {
        if (isOpen2) {
          editor.complete();
          editor.addOpenMenu(id);
        } else {
          editor.updateInstanceState({
            openMenus: editor.getOpenMenus().filter((m) => !m.startsWith(id))
          });
        }
        cb?.(isOpen2);
      });
    },
    [editor, id, cb]
  );
  const isOpen = useValue("is menu open", () => editor.getOpenMenus().includes(id), [editor, id]);
  useEffect(() => {
    if (rIsOpen.current) {
      trackEvent("open-menu", { source: "unknown", id });
      editor.addOpenMenu(id);
    }
    return () => {
      if (rIsOpen.current) {
        editor.deleteOpenMenu(id);
        editor.getOpenMenus().forEach((menuId) => {
          if (menuId.startsWith(id)) {
            trackEvent("close-menu", { source: "unknown", id });
            editor.deleteOpenMenu(menuId);
          }
        });
        rIsOpen.current = false;
      }
    };
  }, [editor, id, trackEvent]);
  return [isOpen, onOpenChange];
}
export {
  useMenuIsOpen
};
//# sourceMappingURL=useMenuIsOpen.mjs.map
