"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.ElementMenu = void 0;
var _lodash = require("lodash");
var _react = _interopRequireWildcard(require("react"));
var _propTypes = _interopRequireDefault(require("prop-types"));
var _eui = require("@elastic/eui");
var _sharedUxButtonToolbar = require("@kbn/shared-ux-button-toolbar");
var _i18n = require("@kbn/i18n");
var _get_id = require("../../../lib/get_id");
var _lib = require("../../../../common/lib");
var _flatten_panel_tree = require("../../../lib/flatten_panel_tree");
var _asset_manager = require("../../asset_manager");
var _saved_elements_modal = require("../../saved_elements_modal");
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; you may not use this file except in compliance with the Elastic License
 * 2.0.
 */

const strings = {
  getAssetsMenuItemLabel: () => _i18n.i18n.translate('xpack.canvas.workpadHeaderElementMenu.manageAssetsMenuItemLabel', {
    defaultMessage: 'Manage assets'
  }),
  getChartMenuItemLabel: () => _i18n.i18n.translate('xpack.canvas.workpadHeaderElementMenu.chartMenuItemLabel', {
    defaultMessage: 'Chart'
  }),
  getElementMenuButtonLabel: () => _i18n.i18n.translate('xpack.canvas.workpadHeaderElementMenu.elementMenuButtonLabel', {
    defaultMessage: 'Add element'
  }),
  getElementMenuLabel: () => _i18n.i18n.translate('xpack.canvas.workpadHeaderElementMenu.elementMenuLabel', {
    defaultMessage: 'Add an element'
  }),
  getFilterMenuItemLabel: () => _i18n.i18n.translate('xpack.canvas.workpadHeaderElementMenu.filterMenuItemLabel', {
    defaultMessage: 'Filter'
  }),
  getImageMenuItemLabel: () => _i18n.i18n.translate('xpack.canvas.workpadHeaderElementMenu.imageMenuItemLabel', {
    defaultMessage: 'Image'
  }),
  getMyElementsMenuItemLabel: () => _i18n.i18n.translate('xpack.canvas.workpadHeaderElementMenu.myElementsMenuItemLabel', {
    defaultMessage: 'My elements'
  }),
  getOtherMenuItemLabel: () => _i18n.i18n.translate('xpack.canvas.workpadHeaderElementMenu.otherMenuItemLabel', {
    defaultMessage: 'Other'
  }),
  getProgressMenuItemLabel: () => _i18n.i18n.translate('xpack.canvas.workpadHeaderElementMenu.progressMenuItemLabel', {
    defaultMessage: 'Progress'
  }),
  getShapeMenuItemLabel: () => _i18n.i18n.translate('xpack.canvas.workpadHeaderElementMenu.shapeMenuItemLabel', {
    defaultMessage: 'Shape'
  }),
  getTextMenuItemLabel: () => _i18n.i18n.translate('xpack.canvas.workpadHeaderElementMenu.textMenuItemLabel', {
    defaultMessage: 'Text'
  })
};

// label and icon for the context menu item for each element type
const elementTypeMeta = {
  chart: {
    name: strings.getChartMenuItemLabel(),
    icon: 'visArea'
  },
  filter: {
    name: strings.getFilterMenuItemLabel(),
    icon: 'filter'
  },
  image: {
    name: strings.getImageMenuItemLabel(),
    icon: 'image'
  },
  other: {
    name: strings.getOtherMenuItemLabel(),
    icon: 'empty'
  },
  progress: {
    name: strings.getProgressMenuItemLabel(),
    icon: 'visGoal'
  },
  shape: {
    name: strings.getShapeMenuItemLabel(),
    icon: 'node'
  },
  text: {
    name: strings.getTextMenuItemLabel(),
    icon: 'visText'
  }
};
const getElementType = element => element && element.type && Object.keys(elementTypeMeta).includes(element.type) ? element.type : 'other';
const categorizeElementsByType = elements => {
  elements = (0, _lodash.sortBy)(elements, 'displayName');
  const categories = {
    other: []
  };
  elements.forEach(element => {
    const type = getElementType(element);
    if (categories[type]) {
      categories[type].push(element);
    } else {
      categories[type] = [element];
    }
  });
  return categories;
};
const ElementMenu = ({
  elements,
  addElement
}) => {
  const [isAssetModalVisible, setAssetModalVisible] = (0, _react.useState)(false);
  const [isSavedElementsModalVisible, setSavedElementsModalVisible] = (0, _react.useState)(false);
  const hideAssetModal = () => setAssetModalVisible(false);
  const showAssetModal = () => setAssetModalVisible(true);
  const hideSavedElementsModal = () => setSavedElementsModalVisible(false);
  const showSavedElementsModal = () => setSavedElementsModalVisible(true);
  const {
    chart: chartElements,
    filter: filterElements,
    image: imageElements,
    other: otherElements,
    progress: progressElements,
    shape: shapeElements,
    text: textElements
  } = categorizeElementsByType(Object.values(elements));
  const getPanelTree = closePopover => {
    const elementToMenuItem = element => ({
      name: element.displayName || element.name,
      icon: element.icon,
      onClick: () => {
        addElement(element);
        closePopover();
      },
      'data-test-subj': `canvasAddElementMenu__${element.name}`
    });
    const elementListToMenuItems = elementList => {
      const type = getElementType(elementList[0]);
      const {
        name,
        icon
      } = elementTypeMeta[type] || elementTypeMeta.other;
      if (elementList.length > 1) {
        return {
          name,
          icon: /*#__PURE__*/_react.default.createElement(_eui.EuiIcon, {
            type: icon,
            size: "m"
          }),
          panel: {
            id: (0, _get_id.getId)('element-type'),
            title: name,
            items: elementList.map(elementToMenuItem)
          },
          'data-test-subj': `canvasAddElementMenu__${name}`
        };
      }
      return elementToMenuItem(elementList[0]);
    };
    return {
      id: 0,
      items: [elementListToMenuItems(textElements), elementListToMenuItems(shapeElements), elementListToMenuItems(chartElements), elementListToMenuItems(imageElements), elementListToMenuItems(filterElements), elementListToMenuItems(progressElements), elementListToMenuItems(otherElements), {
        name: strings.getMyElementsMenuItemLabel(),
        className: _lib.CONTEXT_MENU_TOP_BORDER_CLASSNAME,
        'data-test-subj': 'saved-elements-menu-option',
        icon: /*#__PURE__*/_react.default.createElement(_eui.EuiIcon, {
          type: "empty",
          size: "m"
        }),
        onClick: () => {
          showSavedElementsModal();
          closePopover();
        }
      }, {
        name: strings.getAssetsMenuItemLabel(),
        icon: /*#__PURE__*/_react.default.createElement(_eui.EuiIcon, {
          type: "empty",
          size: "m"
        }),
        onClick: () => {
          showAssetModal();
          closePopover();
        }
      }]
    };
  };
  return /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, /*#__PURE__*/_react.default.createElement(_sharedUxButtonToolbar.ToolbarPopover, {
    type: "primary",
    panelPaddingSize: "none",
    label: strings.getElementMenuButtonLabel(),
    iconType: "plusInCircle",
    "data-test-subj": "add-element-button"
  }, ({
    closePopover
  }) => /*#__PURE__*/_react.default.createElement(_eui.EuiContextMenu, {
    initialPanelId: 0,
    panels: (0, _flatten_panel_tree.flattenPanelTree)(getPanelTree(closePopover))
  })), isAssetModalVisible ? /*#__PURE__*/_react.default.createElement(_asset_manager.AssetManager, {
    onClose: hideAssetModal
  }) : null, isSavedElementsModalVisible ? /*#__PURE__*/_react.default.createElement(_saved_elements_modal.SavedElementsModal, {
    onClose: hideSavedElementsModal
  }) : null);
};
exports.ElementMenu = ElementMenu;
ElementMenu.propTypes = {
  elements: _propTypes.default.object,
  addElement: _propTypes.default.func.isRequired
};