'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.EuiContextMenu = exports.EuiContextMenuPanelShape = exports.EuiContextMenuPanelItemShape = undefined;

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _react = require('react');

var _react2 = _interopRequireDefault(_react);

var _propTypes = require('prop-types');

var _propTypes2 = _interopRequireDefault(_propTypes);

var _classnames = require('classnames');

var _classnames2 = _interopRequireDefault(_classnames);

var _context_menu_panel = require('./context_menu_panel');

var _context_menu_item = require('./context_menu_item');

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

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) {
        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 (item.panel) {
          idAndItemIndexToPanelIdMap[panel.id][index] = item.panel;
        }
      });
    }
  });

  return idAndItemIndexToPanelIdMap;
}

var EuiContextMenuPanelItemShape = exports.EuiContextMenuPanelItemShape = _propTypes2.default.shape({
  name: _propTypes2.default.string,
  icon: _propTypes2.default.node,
  onClick: _propTypes2.default.func,
  // If given, shows the panel with this id when clicked:
  panel: _propTypes2.default.oneOfType([_propTypes2.default.string, _propTypes2.default.number]),
  disabled: _propTypes2.default.bool
});

var EuiContextMenuPanelShape = exports.EuiContextMenuPanelShape = _propTypes2.default.shape({
  id: _propTypes2.default.oneOfType([_propTypes2.default.string, _propTypes2.default.number]),
  width: _propTypes2.default.number, // Pixel value to set the panel width to
  content: _propTypes2.default.node, // Either content or items array should be given.
  items: _propTypes2.default.arrayOf(EuiContextMenuPanelItemShape),
  title: _propTypes2.default.string
});

var EuiContextMenu = exports.EuiContextMenu = function (_Component) {
  _inherits(EuiContextMenu, _Component);

  _createClass(EuiContextMenu, null, [{
    key: 'getDerivedStateFromProps',
    value: function getDerivedStateFromProps(nextProps, prevState) {
      var panels = nextProps.panels;


      if (prevState.prevProps.panels !== panels) {
        return {
          prevProps: { panels: panels },
          idToPanelMap: mapIdsToPanels(panels),
          idToPreviousPanelIdMap: mapIdsToPreviousPanels(panels),
          idAndItemIndexToPanelIdMap: mapPanelItemsToPanels(panels)
        };
      }

      return null;
    }
  }]);

  function EuiContextMenu(props) {
    _classCallCheck(this, EuiContextMenu);

    var _this = _possibleConstructorReturn(this, (EuiContextMenu.__proto__ || Object.getPrototypeOf(EuiContextMenu)).call(this, props));

    _this.hasPreviousPanel = function (panelId) {
      var previousPanelId = _this.state.idToPreviousPanelIdMap[panelId];
      return typeof previousPanelId !== 'undefined';
    };

    _this.showNextPanel = function (itemIndex) {
      var nextPanelId = _this.state.idAndItemIndexToPanelIdMap[_this.state.incomingPanelId][itemIndex];
      if (nextPanelId) {
        if (_this.state.isUsingKeyboardToNavigate) {
          _this.setState({
            focusedItemIndex: 0
          });
        }

        _this.showPanel(nextPanelId, 'next');
      }
    };

    _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 item.panel === _this.state.incomingPanelId;
        });

        if (focusedItemIndex !== -1) {
          _this.setState({
            focusedItemIndex: focusedItemIndex
          });
        }

        _this.showPanel(previousPanelId, 'previous');
      }
    };

    _this.onIncomingPanelHeightChange = function (height) {
      _this.setState(function (_ref) {
        var prevHeight = _ref.height;

        if (height === prevHeight) {
          return null;
        } else {
          return { height: height };
        }
      });
    };

    _this.onOutGoingPanelTransitionComplete = function () {
      _this.setState({
        isOutgoingPanelVisible: false
      });
    };

    _this.onUseKeyboardToNavigate = function () {
      if (!_this.state.isUsingKeyboardToNavigate) {
        _this.setState({
          isUsingKeyboardToNavigate: true
        });
      }
    };

    _this.mapIdsToRenderedItems = function (panels) {
      var idToRenderedItemsMap = {};

      // Pre-rendering the items lets us check reference equality inside of EuiContextMenuPanel.
      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;
  }

  _createClass(EuiContextMenu, [{
    key: 'componentDidUpdate',
    value: function componentDidUpdate(prevProps) {
      if (prevProps.panels !== this.props.panels) {
        this.setState({ // eslint-disable-line react/no-did-update-set-state
          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) {
        var panel = item.panel,
            name = item.name,
            icon = item.icon,
            onClick = item.onClick,
            toolTipTitle = item.toolTipTitle,
            toolTipContent = item.toolTipContent,
            rest = _objectWithoutProperties(item, ['panel', 'name', 'icon', 'onClick', 'toolTipTitle', 'toolTipContent']);

        var onClickHandler = panel ? function (event) {
          if (onClick && event) {
            event.persist();
          }
          // This component is commonly wrapped in a EuiOutsideClickDetector, 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 _react2.default.createElement(
          _context_menu_item.EuiContextMenuItem,
          _extends({
            key: name,
            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 EuiOutsideClickDetector to complete its logic before
      // re-rendering via showPanel.
      var onClose = void 0;
      if (this.hasPreviousPanel(panelId)) {
        onClose = function onClose() {
          return window.requestAnimationFrame(_this3.showPreviousPanel);
        };
      }

      return _react2.default.createElement(
        _context_menu_panel.EuiContextMenuPanel,
        {
          key: panelId,
          className: 'euiContextMenu__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 : undefined,
          onUseKeyboardToNavigate: this.onUseKeyboardToNavigate,
          showNextPanel: this.showNextPanel,
          showPreviousPanel: this.showPreviousPanel
        },
        panel.content
      );
    }
  }, {
    key: 'render',
    value: function render() {
      var _props = this.props,
          panels = _props.panels,
          className = _props.className,
          initialPanelId = _props.initialPanelId,
          rest = _objectWithoutProperties(_props, ['panels', 'className', 'initialPanelId']);

      var incomingPanel = this.renderPanel(this.state.incomingPanelId, 'in');
      var outgoingPanel = void 0;

      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, _classnames2.default)('euiContextMenu', className);

      return _react2.default.createElement(
        'div',
        _extends({
          className: classes,
          style: { height: this.state.height, width: width }
        }, rest),
        outgoingPanel,
        incomingPanel
      );
    }
  }]);

  return EuiContextMenu;
}(_react.Component);

EuiContextMenu.propTypes = {
  className: _propTypes2.default.string,
  panels: _propTypes2.default.arrayOf(EuiContextMenuPanelShape),
  initialPanelId: _propTypes2.default.oneOfType([_propTypes2.default.string, _propTypes2.default.number])
};
EuiContextMenu.defaultProps = {
  panels: []
};
EuiContextMenu.__docgenInfo = [{
  'description': '',
  'displayName': 'EuiContextMenu',
  'methods': [{
    'name': 'getDerivedStateFromProps',
    'docblock': null,
    'modifiers': ['static'],
    'params': [{
      'name': 'nextProps',
      'type': null
    }, {
      'name': 'prevState',
      'type': null
    }],
    'returns': null
  }, {
    'name': 'hasPreviousPanel',
    'docblock': null,
    'modifiers': [],
    'params': [{
      'name': 'panelId',
      'type': null
    }],
    'returns': null
  }, {
    'name': 'showPanel',
    'docblock': null,
    'modifiers': [],
    'params': [{
      'name': 'panelId',
      'type': null
    }, {
      'name': 'direction',
      'type': null
    }],
    'returns': null
  }, {
    'name': 'showNextPanel',
    'docblock': null,
    'modifiers': [],
    'params': [{
      'name': 'itemIndex',
      'type': null
    }],
    'returns': null
  }, {
    'name': 'showPreviousPanel',
    'docblock': null,
    'modifiers': [],
    'params': [],
    'returns': null
  }, {
    'name': 'onIncomingPanelHeightChange',
    'docblock': null,
    'modifiers': [],
    'params': [{
      'name': 'height',
      'type': null
    }],
    'returns': null
  }, {
    'name': 'onOutGoingPanelTransitionComplete',
    'docblock': null,
    'modifiers': [],
    'params': [],
    'returns': null
  }, {
    'name': 'onUseKeyboardToNavigate',
    'docblock': null,
    'modifiers': [],
    'params': [],
    'returns': null
  }, {
    'name': 'mapIdsToRenderedItems',
    'docblock': null,
    'modifiers': [],
    'params': [{
      'name': 'panels',
      'type': null
    }],
    'returns': null
  }, {
    'name': 'renderItems',
    'docblock': null,
    'modifiers': [],
    'params': [{
      'name': 'items',
      'type': null
    }],
    'returns': null
  }, {
    'name': 'renderPanel',
    'docblock': null,
    'modifiers': [],
    'params': [{
      'name': 'panelId',
      'type': null
    }, {
      'name': 'transitionType',
      'type': null
    }],
    'returns': null
  }],
  'props': {
    'className': {
      'type': {
        'name': 'string'
      },
      'required': false,
      'description': ''
    },
    'panels': {
      'type': {
        'name': 'arrayOf',
        'value': {
          'name': 'custom',
          'raw': 'EuiContextMenuPanelShape'
        }
      },
      'required': false,
      'description': '',
      'defaultValue': {
        'value': '[]',
        'computed': false
      }
    },
    'initialPanelId': {
      'type': {
        'name': 'union',
        'value': [{
          'name': 'string'
        }, {
          'name': 'number'
        }]
      },
      'required': false,
      'description': ''
    }
  }
}];