"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
var _typeof = require("@babel/runtime/helpers/typeof");
Object.defineProperty(exports, "__esModule", {
  value: true
});
Object.defineProperty(exports, "EuiContextMenu", {
  enumerable: true,
  get: function get() {
    return _context_menu.EuiContextMenu;
  }
});
exports.OuiContextMenu = exports.SIZES = void 0;
var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));
var _objectWithoutProperties2 = _interopRequireDefault(require("@babel/runtime/helpers/objectWithoutProperties"));
var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime/helpers/classCallCheck"));
var _assertThisInitialized2 = _interopRequireDefault(require("@babel/runtime/helpers/assertThisInitialized"));
var _createClass2 = _interopRequireDefault(require("@babel/runtime/helpers/createClass"));
var _inherits2 = _interopRequireDefault(require("@babel/runtime/helpers/inherits"));
var _possibleConstructorReturn2 = _interopRequireDefault(require("@babel/runtime/helpers/possibleConstructorReturn"));
var _getPrototypeOf2 = _interopRequireDefault(require("@babel/runtime/helpers/getPrototypeOf"));
var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
var _react = _interopRequireWildcard(require("react"));
var _propTypes = _interopRequireDefault(require("prop-types"));
var _classnames = _interopRequireDefault(require("classnames"));
var _common = require("../common");
var _context_menu_panel = require("./context_menu_panel");
var _context_menu_item = require("./context_menu_item");
var _horizontal_rule = require("../horizontal_rule");
var _context_menu = require("../../eui_components/context_menu/context_menu");
function _interopRequireWildcard(e, t) { if ("function" == typeof WeakMap) var r = new WeakMap(), n = new WeakMap(); return (_interopRequireWildcard = function _interopRequireWildcard(e, t) { if (!t && e && e.__esModule) return e; var o, i, f = { __proto__: null, default: e }; if (null === e || "object" != _typeof(e) && "function" != typeof e) return f; if (o = t ? n : r) { if (o.has(e)) return o.get(e); o.set(e, f); } for (var _t in e) { "default" !== _t && {}.hasOwnProperty.call(e, _t) && ((i = (o = Object.defineProperty) && Object.getOwnPropertyDescriptor(e, _t)) && (i.get || i.set) ? o(f, _t, i) : f[_t] = e[_t]); } return f; })(e, t); }
function _createSuper(t) { var r = _isNativeReflectConstruct(); return function () { var e, o = (0, _getPrototypeOf2.default)(t); if (r) { var s = (0, _getPrototypeOf2.default)(this).constructor; e = Reflect.construct(o, arguments, s); } else e = o.apply(this, arguments); return (0, _possibleConstructorReturn2.default)(this, e); }; }
function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } /*
 * SPDX-License-Identifier: Apache-2.0
 *
 * The OpenSearch Contributors require contributions made to
 * this file be licensed under the Apache-2.0 license or a
 * compatible open source license.
 *
 * Modifications Copyright OpenSearch Contributors. See
 * GitHub history for details.
 */ /*
 * Licensed to Elasticsearch B.V. under one or more contributor
 * license agreements. See the NOTICE file distributed with
 * this work for additional information regarding copyright
 * ownership. Elasticsearch B.V. licenses this file to you under
 * the Apache License, Version 2.0 (the "License"); you may
 * not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
var sizeToClassNameMap = {
  s: 'ouiContextMenu--small',
  m: null
};
var SIZES = (0, _common.keysOf)(sizeToClassNameMap);
exports.SIZES = SIZES;
var isItemSeparator = function isItemSeparator(item) {
  return item.isSeparator === true;
};
function mapIdsToPanels(panels) {
  var map = {};
  panels.forEach(function (panel) {
    map[panel.id] = panel;
  });
  return map;
}
function mapIdsToPreviousPanels(panels) {
  var idToPreviousPanelIdMap = {};
  panels.forEach(function (panel) {
    if (Array.isArray(panel.items)) {
      panel.items.forEach(function (item) {
        if (isItemSeparator(item)) return;
        var isCloseable = item.panel !== undefined;
        if (isCloseable) {
          idToPreviousPanelIdMap[item.panel] = panel.id;
        }
      });
    }
  });
  return idToPreviousPanelIdMap;
}
function mapPanelItemsToPanels(panels) {
  var idAndItemIndexToPanelIdMap = {};
  panels.forEach(function (panel) {
    idAndItemIndexToPanelIdMap[panel.id] = {};
    if (panel.items) {
      panel.items.forEach(function (item, index) {
        if (isItemSeparator(item)) return;
        if (item.panel) {
          idAndItemIndexToPanelIdMap[panel.id][index] = item.panel;
        }
      });
    }
  });
  return idAndItemIndexToPanelIdMap;
}
var OuiContextMenu = /*#__PURE__*/function (_Component) {
  (0, _inherits2.default)(OuiContextMenu, _Component);
  var _super = _createSuper(OuiContextMenu);
  (0, _createClass2.default)(OuiContextMenu, null, [{
    key: "getDerivedStateFromProps",
    value: function getDerivedStateFromProps(nextProps, prevState) {
      var panels = nextProps.panels;
      if (panels && prevState.prevProps.panels !== panels) {
        return {
          prevProps: {
            panels: panels
          },
          idToPanelMap: mapIdsToPanels(panels),
          idToPreviousPanelIdMap: mapIdsToPreviousPanels(panels),
          idAndItemIndexToPanelIdMap: mapPanelItemsToPanels(panels)
        };
      }
      return null;
    }
  }]);
  function OuiContextMenu(props) {
    var _this;
    (0, _classCallCheck2.default)(this, OuiContextMenu);
    _this = _super.call(this, props);
    (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "hasPreviousPanel", function (panelId) {
      var previousPanelId = _this.state.idToPreviousPanelIdMap[panelId];
      return typeof previousPanelId !== 'undefined';
    });
    (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "showNextPanel", function (itemIndex) {
      if (itemIndex == null) {
        return;
      }
      var nextPanelId = _this.state.idAndItemIndexToPanelIdMap[_this.state.incomingPanelId][itemIndex];
      if (nextPanelId) {
        if (_this.state.isUsingKeyboardToNavigate) {
          _this.setState(function (_ref) {
            var _idToPanelMap$nextPan;
            var idToPanelMap = _ref.idToPanelMap;
            return {
              focusedItemIndex: (_idToPanelMap$nextPan = idToPanelMap[nextPanelId].initialFocusedItemIndex) !== null && _idToPanelMap$nextPan !== void 0 ? _idToPanelMap$nextPan : 0
            };
          });
        }
        _this.showPanel(nextPanelId, 'next');
      }
    });
    (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "showPreviousPanel", function () {
      // If there's a previous panel, then we can close the current panel to go back to it.
      if (_this.hasPreviousPanel(_this.state.incomingPanelId)) {
        var previousPanelId = _this.state.idToPreviousPanelIdMap[_this.state.incomingPanelId];

        // Set focus on the item which shows the panel we're leaving.
        var previousPanel = _this.state.idToPanelMap[previousPanelId];
        var focusedItemIndex = previousPanel.items.findIndex(function (item) {
          return !isItemSeparator(item) && item.panel === _this.state.incomingPanelId;
        });
        if (focusedItemIndex !== -1) {
          _this.setState({
            focusedItemIndex: focusedItemIndex
          });
        }
        _this.showPanel(previousPanelId, 'previous');
      }
    });
    (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "onIncomingPanelHeightChange", function (height) {
      _this.setState(function (_ref2) {
        var prevHeight = _ref2.height;
        if (height === prevHeight) {
          return null;
        }
        return {
          height: height
        };
      });
    });
    (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "onOutGoingPanelTransitionComplete", function () {
      _this.setState({
        isOutgoingPanelVisible: false
      });
    });
    (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "onUseKeyboardToNavigate", function () {
      if (!_this.state.isUsingKeyboardToNavigate) {
        _this.setState({
          isUsingKeyboardToNavigate: true
        });
      }
    });
    (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "mapIdsToRenderedItems", function () {
      var panels = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
      var idToRenderedItemsMap = {};

      // Pre-rendering the items lets us check reference equality inside of OuiContextMenuPanel.
      panels.forEach(function (panel) {
        idToRenderedItemsMap[panel.id] = _this.renderItems(panel.items);
      });
      return idToRenderedItemsMap;
    });
    _this.state = {
      prevProps: {},
      idToPanelMap: {},
      idToPreviousPanelIdMap: {},
      idAndItemIndexToPanelIdMap: {},
      idToRenderedItemsMap: _this.mapIdsToRenderedItems(_this.props.panels),
      height: undefined,
      outgoingPanelId: undefined,
      incomingPanelId: props.initialPanelId,
      transitionDirection: undefined,
      isOutgoingPanelVisible: false,
      focusedItemIndex: undefined,
      isUsingKeyboardToNavigate: false
    };
    return _this;
  }
  (0, _createClass2.default)(OuiContextMenu, [{
    key: "componentDidUpdate",
    value: function componentDidUpdate(prevProps) {
      if (prevProps.panels !== this.props.panels) {
        // eslint-disable-next-line react/no-did-update-set-state
        this.setState({
          idToRenderedItemsMap: this.mapIdsToRenderedItems(this.props.panels)
        });
      }
    }
  }, {
    key: "showPanel",
    value: function showPanel(panelId, direction) {
      this.setState({
        outgoingPanelId: this.state.incomingPanelId,
        incomingPanelId: panelId,
        transitionDirection: direction,
        isOutgoingPanelVisible: true
      });
    }
  }, {
    key: "renderItems",
    value: function renderItems() {
      var _this2 = this;
      var items = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
      return items.map(function (item, index) {
        if (isItemSeparator(item)) {
          var omit = item.isSeparator,
            _item$key = item.key,
            _key = _item$key === void 0 ? index : _item$key,
            _rest = (0, _objectWithoutProperties2.default)(item, ["isSeparator", "key"]);
          return /*#__PURE__*/_react.default.createElement(_horizontal_rule.OuiHorizontalRule, (0, _extends2.default)({
            key: _key,
            margin: "none"
          }, _rest));
        }
        var panel = item.panel,
          name = item.name,
          key = item.key,
          icon = item.icon,
          onClick = item.onClick,
          toolTipTitle = item.toolTipTitle,
          toolTipContent = item.toolTipContent,
          rest = (0, _objectWithoutProperties2.default)(item, ["panel", "name", "key", "icon", "onClick", "toolTipTitle", "toolTipContent"]);
        var onClickHandler = panel ? function (event) {
          if (onClick && event) {
            event.persist();
          }
          // This component is commonly wrapped in a OuiOutsideClickDetector, which means we'll
          // need to wait for that logic to complete before re-rendering the DOM via showPanel.
          window.requestAnimationFrame(function () {
            if (onClick) {
              onClick(event);
            }
            _this2.showNextPanel(index);
          });
        } : onClick;
        return /*#__PURE__*/_react.default.createElement(_context_menu_item.OuiContextMenuItem, (0, _extends2.default)({
          key: key || (typeof name === 'string' ? name : undefined) || index,
          icon: icon,
          onClick: onClickHandler,
          hasPanel: Boolean(panel),
          toolTipTitle: toolTipTitle,
          toolTipContent: toolTipContent
        }, rest), name);
      });
    }
  }, {
    key: "renderPanel",
    value: function renderPanel(panelId, transitionType) {
      var _this3 = this;
      var panel = this.state.idToPanelMap[panelId];
      if (!panel) {
        return;
      }

      // As above, we need to wait for OuiOutsideClickDetector to complete its logic before
      // re-rendering via showPanel.
      var onClose;
      if (this.hasPreviousPanel(panelId)) {
        onClose = function onClose() {
          return window.requestAnimationFrame(_this3.showPreviousPanel);
        };
      }
      return /*#__PURE__*/_react.default.createElement(_context_menu_panel.OuiContextMenuPanel, {
        key: panelId,
        size: this.props.size,
        className: "ouiContextMenu__panel",
        onHeightChange: transitionType === 'in' ? this.onIncomingPanelHeightChange : undefined,
        onTransitionComplete: transitionType === 'out' ? this.onOutGoingPanelTransitionComplete : undefined,
        title: panel.title,
        onClose: onClose,
        transitionType: this.state.isOutgoingPanelVisible ? transitionType : undefined,
        transitionDirection: this.state.isOutgoingPanelVisible ? this.state.transitionDirection : undefined,
        hasFocus: transitionType === 'in',
        items: this.state.idToRenderedItemsMap[panelId],
        initialFocusedItemIndex: this.state.isUsingKeyboardToNavigate ? this.state.focusedItemIndex : panel.initialFocusedItemIndex,
        onUseKeyboardToNavigate: this.onUseKeyboardToNavigate,
        showNextPanel: this.showNextPanel,
        showPreviousPanel: this.showPreviousPanel
      }, panel.content);
    }
  }, {
    key: "render",
    value: function render() {
      var _this$props = this.props,
        panels = _this$props.panels,
        className = _this$props.className,
        initialPanelId = _this$props.initialPanelId,
        size = _this$props.size,
        rest = (0, _objectWithoutProperties2.default)(_this$props, ["panels", "className", "initialPanelId", "size"]);
      var incomingPanel = this.renderPanel(this.state.incomingPanelId, 'in');
      var outgoingPanel;
      if (this.state.isOutgoingPanelVisible) {
        outgoingPanel = this.renderPanel(this.state.outgoingPanelId, 'out');
      }
      var width = this.state.idToPanelMap[this.state.incomingPanelId] && this.state.idToPanelMap[this.state.incomingPanelId].width ? this.state.idToPanelMap[this.state.incomingPanelId].width : undefined;
      var classes = (0, _classnames.default)('ouiContextMenu', size && sizeToClassNameMap[size], className);
      return /*#__PURE__*/_react.default.createElement("div", (0, _extends2.default)({
        className: classes,
        style: {
          height: this.state.height,
          width: width
        }
      }, rest), outgoingPanel, incomingPanel);
    }
  }]);
  return OuiContextMenu;
}(_react.Component);
/* OUI -> EUI Aliases: Build-Time */
exports.OuiContextMenu = OuiContextMenu;
(0, _defineProperty2.default)(OuiContextMenu, "defaultProps", {
  panels: [],
  size: 'm'
});
OuiContextMenu.propTypes = {
  className: _propTypes.default.string,
  "aria-label": _propTypes.default.string,
  "data-test-subj": _propTypes.default.string,
  panels: _propTypes.default.arrayOf(_propTypes.default.shape({
    id: _propTypes.default.oneOfType([_propTypes.default.string.isRequired, _propTypes.default.number.isRequired]).isRequired,
    title: _propTypes.default.node,
    items: _propTypes.default.arrayOf(_propTypes.default.shape({
      name: _propTypes.default.node,
      key: _propTypes.default.string,
      panel: _propTypes.default.oneOfType([_propTypes.default.string.isRequired, _propTypes.default.number.isRequired]),
      isSeparator: _propTypes.default.oneOf([true]),
      /**
         * Defines the width of the HR.
         */
      size: _propTypes.default.oneOf(["full", "half", "quarter"]),
      margin: _propTypes.default.oneOf(["none", "xs", "s", "m", "l", "xl", "xxl"]),
      className: _propTypes.default.string,
      "aria-label": _propTypes.default.string,
      "data-test-subj": _propTypes.default.string
    }).isRequired),
    content: _propTypes.default.node,
    width: _propTypes.default.number,
    initialFocusedItemIndex: _propTypes.default.number,
    /**
       * Alters the size of the items and the title
       */
    size: _propTypes.default.oneOf(["s", "m"])
  }).isRequired),
  initialPanelId: _propTypes.default.oneOfType([_propTypes.default.string.isRequired, _propTypes.default.number.isRequired]),
  /**
       * Alters the size of the items and the title
       */
  size: _propTypes.default.oneOf(["s", "m"])
};
/* OUI -> EUI Aliases: Build-Time */