"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.EmbeddablePanelContextMenu = void 0;
var _i18n = require("@kbn/i18n");
var _classnames = _interopRequireDefault(require("classnames"));
var _react = _interopRequireWildcard(require("react"));
var _eui = require("@elastic/eui");
var _public = require("@kbn/ui-actions-plugin/public");
var _kibana_services = require("../../kibana_services");
var _embeddable_panel_strings = require("../embeddable_panel_strings");
var _use_select_from_embeddable = require("../use_select_from_embeddable");
var _ = require("../..");
function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
/*
 * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
 * or more contributor license agreements. Licensed under the Elastic License
 * 2.0 and the Server Side Public License, v 1; you may not use this file except
 * in compliance with, at your election, the Elastic License 2.0 or the Server
 * Side Public License, v 1.
 */

const sortByOrderField = ({
  order: orderA
}, {
  order: orderB
}) => (orderB || 0) - (orderA || 0);
const removeById = disabledActions => ({
  id
}) => disabledActions.indexOf(id) === -1;
const EmbeddablePanelContextMenu = ({
  index,
  embeddable,
  getActions,
  actionPredicate,
  universalActions
}) => {
  const [menuPanelsLoading, setMenuPanelsLoading] = (0, _react.useState)(false);
  const [contextMenuActions, setContextMenuActions] = (0, _react.useState)([]);
  const [isContextMenuOpen, setIsContextMenuOpen] = (0, _react.useState)(undefined);
  const [contextMenuPanels, setContextMenuPanels] = (0, _react.useState)([]);
  const title = (0, _use_select_from_embeddable.useSelectFromEmbeddableInput)('title', embeddable);
  (0, _react.useEffect)(() => {
    /**
     * isContextMenuOpen starts as undefined which allows this use effect to run on mount. This
     * is required so that showNotification is calculated on mount.
     */
    if (isContextMenuOpen === false) return;
    setMenuPanelsLoading(true);
    let canceled = false;
    (async () => {
      /**
       * Build and update all actions
       */
      const regularActions = await (async _await$uiActions$getT => {
        if (getActions) return await getActions(_.CONTEXT_MENU_TRIGGER, {
          embeddable
        });
        return (_await$uiActions$getT = await _kibana_services.uiActions.getTriggerCompatibleActions(_.CONTEXT_MENU_TRIGGER, {
          embeddable
        })) !== null && _await$uiActions$getT !== void 0 ? _await$uiActions$getT : [];
      })();
      if (canceled) return;
      let allActions = regularActions.concat(Object.values(universalActions !== null && universalActions !== void 0 ? universalActions : {}));
      const {
        disabledActions
      } = embeddable.getInput();
      if (disabledActions) {
        const removeDisabledActions = removeById(disabledActions);
        allActions = allActions.filter(removeDisabledActions);
      }
      allActions.sort(sortByOrderField);
      if (actionPredicate) {
        allActions = allActions.filter(({
          id
        }) => actionPredicate(id));
      }

      /**
       * Build context menu panel from actions
       */
      const panels = await (0, _public.buildContextMenuForActions)({
        actions: allActions.map(action => ({
          action,
          context: {
            embeddable
          },
          trigger: _.contextMenuTrigger
        })),
        closeMenu: () => setIsContextMenuOpen(false)
      });
      if (canceled) return;
      setMenuPanelsLoading(false);
      setContextMenuActions(allActions);
      setContextMenuPanels(panels);
    })();
    return () => {
      canceled = true;
    };
  }, [actionPredicate, embeddable, getActions, isContextMenuOpen, universalActions]);
  const showNotification = (0, _react.useMemo)(() => contextMenuActions.some(action => action.showNotification), [contextMenuActions]);
  const contextMenuClasses = (0, _classnames.default)({
    // eslint-disable-next-line @typescript-eslint/naming-convention
    embPanel__optionsMenuPopover: true,
    'embPanel__optionsMenuPopover-notification': showNotification
  });
  const ContextMenuButton = /*#__PURE__*/_react.default.createElement(_eui.EuiButtonIcon, {
    color: "text",
    className: "embPanel__optionsMenuButton",
    "data-test-subj": "embeddablePanelToggleMenuIcon",
    "aria-label": (0, _embeddable_panel_strings.getContextMenuAriaLabel)(title, index),
    onClick: () => setIsContextMenuOpen(isOpen => !isOpen),
    iconType: 'boxesHorizontal'
  });
  return /*#__PURE__*/_react.default.createElement(_eui.EuiPopover, {
    repositionOnScroll: true,
    panelPaddingSize: "none",
    anchorPosition: "downRight",
    button: ContextMenuButton,
    isOpen: isContextMenuOpen,
    className: contextMenuClasses,
    closePopover: () => setIsContextMenuOpen(false),
    "data-test-subj": isContextMenuOpen ? 'embeddablePanelContextMenuOpen' : 'embeddablePanelContextMenuClosed'
  }, menuPanelsLoading ? /*#__PURE__*/_react.default.createElement(_eui.EuiContextMenuPanel, {
    className: "embPanel__optionsMenuPopover-loading",
    title: _i18n.i18n.translate('embeddableApi.panel.contextMenu.loadingTitle', {
      defaultMessage: 'Options'
    })
  }, /*#__PURE__*/_react.default.createElement(_eui.EuiContextMenuItem, null, /*#__PURE__*/_react.default.createElement(_eui.EuiSkeletonText, null))) : /*#__PURE__*/_react.default.createElement(_eui.EuiContextMenu, {
    initialPanelId: "mainMenu",
    panels: contextMenuPanels
  }));
};
exports.EmbeddablePanelContextMenu = EmbeddablePanelContextMenu;