import _extends from "@babel/runtime/helpers/esm/extends";
import _inheritsLoose from "@babel/runtime/helpers/esm/inheritsLoose";
var _class, _Kebab;
import React from 'react';
import { isElement } from 'react-is';
import { globalObject } from '@skbkontur/global-object';
import { isKonturIcon } from "../../../lib/utils";
import { isKeyArrowVertical, isKeyEnter, isKeySpace, someKeys } from "../../../lib/events/keyboard/identifiers";
import * as LayoutEvents from "../../../lib/LayoutEvents";
import { keyListener } from "../../../lib/events/keyListener";
import { PopupMenu } from "../../../internal/PopupMenu";
import { ThemeContext } from "../../../lib/theming/ThemeContext";
import { isTestEnv } from "../../../lib/currentEnvironment";
import { ThemeFactory } from "../../../lib/theming/ThemeFactory";
import { CommonWrapper } from "../../../internal/CommonWrapper";
import { cx } from "../../../lib/theming/Emotion";
import { rootNode } from "../../../lib/rootNode";
import { createPropsGetter } from "../../../lib/createPropsGetter";
import { getVisualStateDataAttributes } from "../../../internal/CommonWrapper/utils/getVisualStateDataAttributes";
import { withSize } from "../../../lib/size/SizeDecorator";
import { styles } from "../Kebab.styles";
import { KebabIcon } from "../KebabIcon";
export var KebabDataTids = {
  caption: 'Kebab__caption'
};

/**
 * Кебаб-меню `Kebab` содержит действия с объектом.
 */

export var Kebab = rootNode(_class = withSize(_class = (_Kebab = /*#__PURE__*/function (_React$Component) {
  function Kebab() {
    var _this;
    for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
      args[_key] = arguments[_key];
    }
    _this = _React$Component.call.apply(_React$Component, [this].concat(args)) || this;
    _this.getProps = createPropsGetter(Kebab.defaultProps);
    _this.state = {
      focusedByTab: false,
      anchor: null
    };
    _this.listener = {
      remove: function remove() {
        return undefined;
      }
    };
    _this.renderCaption = function (captionProps) {
      var _this$getProps = _this.getProps(),
        disabled = _this$getProps.disabled;
      var size = _this.size;
      var handleCaptionKeyDown = function handleCaptionKeyDown(event) {
        if (!disabled) {
          _this.handleCaptionKeyDown(event, captionProps.openMenu);
        }
      };
      var handleCaptionClick = function handleCaptionClick() {
        if (!disabled) {
          captionProps.toggleMenu();
        }
      };
      return /*#__PURE__*/(
        React.createElement("span", {
          role: "button",
          "data-tid": KebabDataTids.caption,
          tabIndex: disabled ? -1 : 0,
          onClick: handleCaptionClick,
          onKeyDown: handleCaptionKeyDown,
          onFocus: _this.handleFocus,
          onBlur: _this.handleBlur,
          className: cx(styles.kebab(_this.theme), size === 'small' && styles.kebabSmall(_this.theme), size === 'medium' && styles.kebabMedium(_this.theme), size === 'large' && styles.kebabLarge(_this.theme), captionProps.opened && styles.opened(_this.theme), disabled && styles.disabled(), _this.state.focusedByTab && styles.focused(_this.theme)),
          "aria-describedby": _this.props['aria-describedby']
        }, _this.renderIcon())
      );
    };
    _this.handleCaptionKeyDown = function (e, openMenu) {
      if (someKeys(isKeyEnter, isKeySpace, isKeyArrowVertical)(e)) {
        e.preventDefault();
        openMenu(true);
      }
    };
    _this.handleChangeMenuState = function (isOpened, restoreFocus) {
      _this.setState({
        focusedByTab: !isOpened && restoreFocus
      });
    };
    _this.handleFocus = function () {
      if (!_this.props.disabled) {
        // focus event fires before keyDown eventlistener
        // so we should check tabPressed in async way
        globalObject.requestAnimationFrame == null || globalObject.requestAnimationFrame(function () {
          if (keyListener.isTabPressed) {
            _this.setState({
              focusedByTab: true
            });
          }
        });
      }
    };
    _this.handleBlur = function () {
      _this.setState({
        focusedByTab: false
      });
    };
    return _this;
  }
  _inheritsLoose(Kebab, _React$Component);
  var _proto = Kebab.prototype;
  _proto.componentDidMount = function componentDidMount() {
    /** addListener'у нужен колбэк в аргумент */this.listener = LayoutEvents.addListener(function () {
      return undefined;
    });
  };
  _proto.componentWillUnmount = function componentWillUnmount() {
    this.listener.remove();
  };
  _proto.render = function render() {
    var _this2 = this;
    return /*#__PURE__*/React.createElement(ThemeContext.Consumer, null, function (theme) {
      _this2.theme = theme;
      return /*#__PURE__*/React.createElement(ThemeContext.Provider, {
        value: ThemeFactory.create({
          popupMargin: theme.kebabMargin
        }, theme)
      }, _this2.renderMain());
    });
  };
  _proto.renderMain = function renderMain() {
    var disabled = this.props.disabled;
    var _this$getProps2 = this.getProps(),
      positions = _this$getProps2.positions,
      disableAnimations = _this$getProps2.disableAnimations,
      onOpen = _this$getProps2.onOpen,
      onClose = _this$getProps2.onClose;
    return /*#__PURE__*/React.createElement(CommonWrapper, _extends({
      rootNodeRef: this.setRootNode
    }, this.props, getVisualStateDataAttributes({
      disabled: disabled
    })), /*#__PURE__*/React.createElement(PopupMenu, {
      id: this.props.id,
      popupHasPin: false,
      preventIconsOffset: this.props.preventIconsOffset,
      positions: positions,
      onChangeMenuState: this.handleChangeMenuState,
      caption: this.renderCaption,
      disableAnimations: disableAnimations,
      menuMaxHeight: this.props.menuMaxHeight,
      onOpen: onOpen,
      onClose: onClose,
      popupMenuId: this.props.popupMenuId,
      "aria-label": this.props['aria-label']
    }, !disabled && this.props.children));
  };
  _proto.renderIcon = function renderIcon() {
    var _this$getProps3 = this.getProps(),
      _this$getProps3$icon = _this$getProps3.icon,
      icon = _this$getProps3$icon === void 0 ? /*#__PURE__*/React.createElement(KebabIcon, null) : _this$getProps3$icon;
    if (isElement(icon) && isKonturIcon(icon)) {
      var _icon$props$size, _icon$props$color;
      var sizes = {
        small: parseInt(this.theme.kebabIconSizeSmall),
        medium: parseInt(this.theme.kebabIconSizeMedium),
        large: parseInt(this.theme.kebabIconSizeLarge)
      };
      return /*#__PURE__*/React.cloneElement(icon, {
        size: (_icon$props$size = icon.props.size) != null ? _icon$props$size : sizes[this.size],
        color: (_icon$props$color = icon.props.color) != null ? _icon$props$color : this.theme.kebabIconColor
      });
    }
    return icon;
  };
  return Kebab;
}(React.Component), _Kebab.__KONTUR_REACT_UI__ = 'Kebab', _Kebab.displayName = 'Kebab', _Kebab.defaultProps = {
  onOpen: function onOpen() {
    return undefined;
  },
  onClose: function onClose() {
    return undefined;
  },
  positions: ['bottom left', 'bottom right', 'top left', 'top right'],
  disableAnimations: isTestEnv
}, _Kebab)) || _class) || _class;