"use strict";var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;exports.__esModule = true;exports.MenuDataTids = exports.Menu = void 0;var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));var _inheritsLoose2 = _interopRequireDefault(require("@babel/runtime/helpers/inheritsLoose"));
var _react = _interopRequireDefault(require("react"));
var _globalObject = require("@skbkontur/global-object");

var _identifiers = require("../../lib/events/keyboard/identifiers");
var _MenuSeparator = require("../../components/MenuSeparator");
var _ThemeFactory = require("../../lib/theming/ThemeFactory");
var _getDOMRect = require("../../lib/dom/getDOMRect");
var _decorator = require("../../components/ResponsiveLayout/decorator");
var _utils = require("../../lib/utils");

var _ScrollContainer = require("../../components/ScrollContainer");

var _MenuItem = require("../../components/MenuItem");

var _ThemeContext = require("../../lib/theming/ThemeContext");

var _Emotion = require("../../lib/theming/Emotion");

var _rootNode2 = require("../../lib/rootNode");
var _client = require("../../lib/client");
var _createPropsGetter = require("../../lib/createPropsGetter");
var _isInstanceOf = require("../../lib/isInstanceOf");

var _CommonWrapper = require("../CommonWrapper");

var _Menu2 = require("./Menu.styles");
var _MenuNavigation = require("./MenuNavigation");
var _MenuContext = require("./MenuContext");var _class, _Menu;









































var MenuDataTids = exports.MenuDataTids = {
  root: 'Menu__root'
};var
















Menu = exports.Menu = (0, _decorator.responsiveLayout)(_class = (0, _rootNode2.rootNode)(_class = (_Menu = /*#__PURE__*/function (_React$PureComponent) {function Menu() {var _this;for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {args[_key] = arguments[_key];}_this = _React$PureComponent.call.apply(_React$PureComponent, [this].concat(args)) || this;_this.













    getProps = (0, _createPropsGetter.createPropsGetter)(Menu.defaultProps);_this.

    state = {
      highlightedIndex: -1,
      maxHeight: _this.getProps().maxHeight || 'none',
      scrollState: 'top',
      enableIconPadding: false
    };_this.




    unmounted = false;_this.




    contentRef = /*#__PURE__*/_react.default.createRef();_this.
    menuNavigation = new _MenuNavigation.MenuNavigation(_this.contentRef, _MenuItem.MenuItemDataTids.content);_this.



























    focusOnRootElement = function () {
      var rootNode = (0, _rootNode2.getRootNode)(_this);
      if ((0, _isInstanceOf.isInstanceOf)(rootNode, _globalObject.globalObject.HTMLElement)) {
        rootNode == null || rootNode.focus();
      }
    };_this.


















































































































    renderHeader = function () {var _cx;
      return /*#__PURE__*/(
        _react.default.createElement("div", {
          className: (0, _Emotion.cx)((_cx = {}, _cx[
          _Menu2.styles.wrapper()] = true, _cx[
          _Menu2.styles.headerWrapper()] = true, _cx)
          ),
          ref: function ref(el) {return _this.header = el;} }, /*#__PURE__*/

        _react.default.createElement("div", { className: _Menu2.styles.contentWrapper() }, _this.props.header), /*#__PURE__*/
        _react.default.createElement("div", { className: _Menu2.styles.menuSeparatorWrapper(_this.theme) },
        _this.state.scrollState !== 'top' && _this.renderMenuSeparatorWithNoMargin()
        )
        ));

    };_this.

    renderFooter = function () {var _cx2;
      return /*#__PURE__*/(
        _react.default.createElement("div", {
          className: (0, _Emotion.cx)((_cx2 = {}, _cx2[
          _Menu2.styles.wrapper()] = true, _cx2[
          _Menu2.styles.footerWrapper()] = true, _cx2)
          ),
          ref: function ref(el) {return _this.footer = el;} }, /*#__PURE__*/

        _react.default.createElement("div", { className: _Menu2.styles.menuSeparatorWrapper(_this.theme) },
        _this.state.scrollState !== 'bottom' && _this.renderMenuSeparatorWithNoMargin()
        ), /*#__PURE__*/
        _react.default.createElement("div", { className: _Menu2.styles.contentWrapper() }, _this.props.footer)
        ));

    };_this.

    renderMenuSeparatorWithNoMargin = function () {
      return /*#__PURE__*/(
        _react.default.createElement(_ThemeContext.ThemeContext.Provider, { value: _ThemeFactory.ThemeFactory.create({ menuSeparatorMarginY: '0' }, _this.theme) }, /*#__PURE__*/
        _react.default.createElement(_MenuSeparator.MenuSeparator, null)
        ));

    };_this.

    setInitialSelection = function () {
      for (var i = _this.getProps().initialSelectedItemIndex; i > -1; i--) {
        _this.down();
      }
    };_this.

    shouldRecalculateMaxHeight = function (prevProps) {
      var _this$props = _this.props,header = _this$props.header,footer = _this$props.footer,children = _this$props.children;
      var maxHeight = _this.getProps().maxHeight;
      var prevMaxHeight = prevProps.maxHeight;
      var prevHeader = prevProps.header;
      var prevFooter = prevProps.footer;
      var prevChildrenCount = _react.default.Children.count(prevProps.children);

      return (
        maxHeight !== prevMaxHeight ||
        footer !== prevFooter ||
        header !== prevHeader ||
        _react.default.Children.count(children) !== prevChildrenCount);

    };_this.

    calculateMaxHeight = function () {
      var maxHeight = _this.getProps().maxHeight;
      var parsedMaxHeight = maxHeight;
      var rootNode = (0, _rootNode2.getRootNode)(_this);

      if (typeof maxHeight === 'string' && (0, _globalObject.isBrowser)(_globalObject.globalObject) && rootNode) {
        var rootElementMaxHeight = _globalObject.globalObject.getComputedStyle == null ? void 0 : _globalObject.globalObject.getComputedStyle(rootNode).maxHeight;

        if (rootElementMaxHeight) {
          parsedMaxHeight = parseFloat(rootElementMaxHeight);
        }
      }

      var calculatedMaxHeight =
      typeof parsedMaxHeight === 'number' ?
      parsedMaxHeight + (
      _this.header && (0, _getDOMRect.getDOMRect)(_this.header).height || 0) + (
      _this.footer && (0, _getDOMRect.getDOMRect)(_this.footer).height || 0) :
      maxHeight;

      _this.setState({
        maxHeight: calculatedMaxHeight || 'none'
      });
    };_this.

    refScrollContainer = function (scrollContainer) {
      _this.scrollContainer = scrollContainer;
    };_this.

    scrollToSelected = function () {
      var highlightedItem = _this.menuNavigation.highlightedItem;
      if (_this.scrollContainer && highlightedItem) {
        var _rootNode = (0, _rootNode2.getRootNode)(highlightedItem);
        // TODO: Remove this check once IF-647 is resolved
        if ((0, _isInstanceOf.isInstanceOf)(_rootNode, _globalObject.globalObject.HTMLElement)) {
          _this.scrollContainer.scrollTo(_rootNode);
        }
      }
    };_this.

    scrollToTop = function () {
      if (_this.scrollContainer) {
        _this.scrollContainer.scrollToTop();
      }
    };_this.

    scrollToBottom = function () {
      if (_this.scrollContainer) {
        _this.scrollContainer.scrollToBottom();
      }
    };_this.

    scroll = function (nextIndex) {
      switch (nextIndex) {
        case 0:
          _this.scrollToTop == null || _this.scrollToTop();
          break;
        case _this.menuNavigation.items.length - 1:
          _this.scrollToBottom == null || _this.scrollToBottom();
          break;
        default:
          _this.scrollToSelected == null || _this.scrollToSelected();
      }
    };_this.















    handleKeyDown = function (event) {
      if (typeof _this.props.onKeyDown === 'function') {
        _this.props.onKeyDown(event);
      }

      if (event.defaultPrevented) {
        return;
      }

      if ((0, _identifiers.isKeyArrowUp)(event)) {
        event.preventDefault();
        _this.up();
      } else if ((0, _identifiers.isKeyArrowDown)(event)) {
        event.preventDefault();
        _this.down();
      } else if ((0, _identifiers.isKeyEnter)(event)) {
        _this.menuNavigation.select(event);
      }
    };_this.

    getStyle = function (props) {
      if (props.align === 'right') {
        return {
          maxWidth: props.width,
          minWidth: props.width,
          maxHeight: _this.state.maxHeight
        };
      }

      return {
        width: props.width,
        maxHeight: _this.state.maxHeight
      };
    };_this.

    handleScrollStateChange = function (scrollState) {
      if (_this.state.scrollState !== scrollState) {
        _this.setState({ scrollState: scrollState });
      }
    };_this.

    setEnableIconPadding = function (isIconPaddingEnabled) {
      !_this.getProps().preventIconsOffset && _this.setState({ enableIconPadding: isIconPaddingEnabled });
    };return _this;}(0, _inheritsLoose2.default)(Menu, _React$PureComponent);var _proto = Menu.prototype;_proto.componentWillUnmount = function componentWillUnmount() {this.unmounted = true;};_proto.componentDidMount = function componentDidMount() {this.setInitialSelection();this.calculateMaxHeight();this.unmounted = false;};_proto.componentDidUpdate = function componentDidUpdate(prevProps) {if (this.shouldRecalculateMaxHeight(prevProps)) {this.calculateMaxHeight();}if (prevProps.maxHeight !== this.getProps().maxHeight) {this.setState({ maxHeight: this.props.maxHeight || 'none' });}};_proto.focus = function focus() {this.focusOnRootElement();};_proto.render = function render() {var _this2 = this;return /*#__PURE__*/_react.default.createElement(_ThemeContext.ThemeContext.Consumer, null, function (theme) {_this2.theme = theme;return _this2.renderMain();});} /**
   * @public
   */;_proto.up = function up() {this.move(-1);} /**
   * @public
   */;_proto.down = function down() {this.move(1);} /**
   * @public
   */;_proto.enter = function enter(event) {var _this$menuNavigation$;(_this$menuNavigation$ = this.menuNavigation.highlightedItem) == null || _this$menuNavigation$.navigate();return this.menuNavigation.select(event);} /**
   * @public
   */;_proto.reset = function reset() {this.menuNavigation.reset();} /**
   * @public
   */;_proto.hasHighlightedItem = function hasHighlightedItem() {return !!this.menuNavigation.highlightedItem;};_proto.highlightItem = function highlightItem(index) {this.menuNavigation.highlightByIndex(index);};_proto.renderMain = function renderMain() {var _cx3, _cx4;if (this.isEmpty()) {return null;}var _this$getProps = this.getProps(),hasMargin = _this$getProps.hasMargin,maxHeight = _this$getProps.maxHeight,preventWindowScroll = _this$getProps.preventWindowScroll;var offsetY = { top: "" + this.theme.scrollContainerScrollBarOffsetY, right: 0, bottom: "" + this.theme.scrollContainerScrollBarOffsetY };var isMobile = this.isMobileLayout;return /*#__PURE__*/_react.default.createElement(_CommonWrapper.CommonWrapper, (0, _extends2.default)({ rootNodeRef: this.setRootNode }, this.props), /*#__PURE__*/_react.default.createElement("div", { "data-tid": MenuDataTids.root, className: (0, _Emotion.cx)(getAlignRightClass(this.props), (_cx3 = {}, _cx3[_Menu2.styles.root(this.theme)] = true, _cx3[_Menu2.styles.hasMargin(this.theme)] = hasMargin, _cx3[_Menu2.styles.mobileRoot(this.theme)] = isMobile, _cx3[_Menu2.styles.shadow(this.theme)] = !isMobile, _cx3)), style: this.getStyle(this.props), id: this.props.id, onKeyDown: this.handleKeyDown, tabIndex: 0 }, this.props.header && this.renderHeader(), /*#__PURE__*/_react.default.createElement(_ScrollContainer.ScrollContainer, { ref: this.refScrollContainer, maxHeight: maxHeight, preventWindowScroll: preventWindowScroll, onScrollStateChange: this.handleScrollStateChange, disabled: this.props.disableScrollContainer, offsetY: offsetY }, /*#__PURE__*/_react.default.createElement("div", { className: (0, _Emotion.cx)((_cx4 = {}, _cx4[_Menu2.styles.scrollContainer(this.theme)] = true, _cx4[_Menu2.styles.scrollContainerMobile(this.theme)] = isMobile, _cx4)), ref: this.contentRef }, /*#__PURE__*/_react.default.createElement(_MenuContext.MenuContext.Provider, { value: { navigation: this.menuNavigation, onItemClick: this.props.onItemClick, enableIconPadding: this.state.enableIconPadding, setEnableIconPadding: this.setEnableIconPadding } }, this.props.children))), this.props.footer && this.renderFooter()));};_proto.move = function move(step) {if (this.unmounted) {// NOTE workaround, because `ComboBox` call `process.nextTick` in reducer
      return;}var nextIndex = this.menuNavigation.move(step, this.getProps().cyclicSelection);this.scroll(nextIndex);};_proto.isEmpty = function isEmpty() {var children = this.props.children;return !children || !childrenToArray(children).filter(_utils.isNonNullable).length;};return Menu;}(_react.default.PureComponent), _Menu.__KONTUR_REACT_UI__ = 'Menu', _Menu.displayName = 'Menu', _Menu.defaultProps = { align: 'left', width: 'auto', maxHeight: 300, hasMargin: true, preventWindowScroll: true, cyclicSelection: true, initialSelectedItemIndex: -1 }, _Menu)) || _class) || _class;function childrenToArray(children) {var ret = []; // Use forEach instead of map to avoid cloning for key unifying.
  _react.default.Children.forEach(children, function (child) {ret.push(child);});return ret;}var getAlignRightClass = function getAlignRightClass(props) {
  if (props.align === 'right') {var _cx5;
    return (0, _Emotion.cx)((_cx5 = {}, _cx5[
    _Menu2.styles.alignRight()] = !_client.isIE11, _cx5[
    _Menu2.styles.alignRightIE11()] = _client.isIE11, _cx5[
    _Menu2.styles.alignRightIE11FixAutoWidth()] = _client.isIE11 && props.width === 'auto', _cx5)
    );
  }

  return null;
};