"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.useContextMenu = void 0;
var _react = require("react");
/*
 * Copyright OpenSearch Contributors
 * SPDX-License-Identifier: Apache-2.0
 */

const useContextMenu = ({
  id,
  nodeRef,
  activeMenuNodeId,
  setActiveMenuNodeId
}) => {
  const [menuPosition, setMenuPosition] = (0, _react.useState)(null);
  const menuRef = (0, _react.useRef)(null);
  const isMenuOpen = activeMenuNodeId === id;
  const onClose = (0, _react.useCallback)(() => {
    setActiveMenuNodeId === null || setActiveMenuNodeId === void 0 || setActiveMenuNodeId(null);
  }, [setActiveMenuNodeId]);
  const onToggleMenu = (0, _react.useCallback)(event => {
    event.stopPropagation();
    setActiveMenuNodeId === null || setActiveMenuNodeId === void 0 || setActiveMenuNodeId(isMenuOpen ? null : id);
  }, [id, isMenuOpen, setActiveMenuNodeId]);
  (0, _react.useEffect)(() => {
    if (isMenuOpen && nodeRef.current) {
      const rect = nodeRef.current.getBoundingClientRect();
      setMenuPosition({
        top: rect.top,
        left: rect.right + 4
      });
    }
  }, [isMenuOpen, nodeRef]);
  return {
    isMenuOpen,
    menuPosition,
    menuRef,
    onToggleMenu,
    onClose
  };
};
exports.useContextMenu = useContextMenu;