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


var _utils = require("../../lib/utils");
var _client = require("../../lib/client");
var _keyListener = require("../../lib/events/keyListener");

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

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

var _rootNode = require("../../lib/rootNode");
var _ThemeFactory = require("../../lib/theming/ThemeFactory");
var _createPropsGetter = require("../../lib/createPropsGetter");
var _Link = require("../Link");


var _SizeDecorator = require("../../lib/size/SizeDecorator");

var _Button2 = require("./Button.styles");

var _ButtonIcon = require("./ButtonIcon");
var _ButtonArrow = require("./ButtonArrow");
var _getInnerLinkTheme = require("./getInnerLinkTheme");
var _LoadingButtonIcon = require("./LoadingButtonIcon");var _class, _Button;var _excluded = ["children"],_excluded2 = ["corners", "active", "disabled", "borderless", "checked", "error", "warning", "loading", "narrow", "arrow", "icon", "rightIcon", "_noPadding", "_noRightPadding", "visuallyFocused", "align", "disableFocus", "width", "tabIndex", "component", "use", "theme"];





























































































var BUTTON_DEFAULT_COMPONENT = exports.BUTTON_DEFAULT_COMPONENT = 'button';








var ButtonDataTids = exports.ButtonDataTids = {
  rootElement: 'Button__rootElement',
  root: 'Button__root',
  spinner: 'Button__spinner'
};



var SpanComponent = function SpanComponent(_ref) {var children = _ref.children,rest = (0, _objectWithoutPropertiesLoose2.default)(_ref, _excluded);
  return /*#__PURE__*/_react.default.createElement("span", rest, children);
};

/** Кнопка запускает действие, сценарий или позволяет перейти на другую страницу. */var


Button = exports.Button = (0, _SizeDecorator.withSize)(_class = (0, _rootNode.rootNode)(_class = (_Button = /*#__PURE__*/function (_React$Component) {function Button() {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 = (0, _createPropsGetter.createPropsGetter)(Button.defaultProps);_this.

    state = {
      focusedByTab: false
    };_this.


    node = null;_this.































































    renderMain = function (props) {var _cx, _cx4, _cx5;
      var
        corners =






















        props.corners,active = props.active,disabled = props.disabled,borderless = props.borderless,checked = props.checked,error = props.error,warning = props.warning,loading = props.loading,narrow = props.narrow,arrow = props.arrow,icon = props.icon,rightIcon = props.rightIcon,_noPadding = props._noPadding,_noRightPadding = props._noRightPadding,visuallyFocused = props.visuallyFocused,align = props.align,disableFocus = props.disableFocus,width = props.width,tabIndex = props.tabIndex,_component = props.component,useProp = props.use,theme = props.theme,rest = (0, _objectWithoutPropertiesLoose2.default)(props, _excluded2);
      var _this$getProps = _this.getProps(),use = _this$getProps.use,component = _this$getProps.component,children = _this$getProps.children;

      var sizeClass = _this.getSizeClassName();

      var isFocused = _this.state.focusedByTab || visuallyFocused;
      var isLink = use === 'link';

      var _useButtonArrow = (0, _ButtonArrow.useButtonArrow)((0, _extends2.default)({},
        _this.props, { isFocused: Boolean(isFocused), size: _this.size }),
        _this.theme
        ),rootClassNameWithArrow = _useButtonArrow[0],arrowNode = _useButtonArrow[1];
      var isUseStateWithoutOutlineInDisabledState = !['default', 'backless'].includes(use);

      var nonInteractive = disabled || loading;
      var rootClassName = _Emotion.cx.apply(void 0, [
      _Button2.styles.root(_this.theme),
      _Button2.styles[use](_this.theme),
      sizeClass,
      narrow && _Button2.styles.narrow(),
      _noPadding && _Button2.styles.noPadding(),
      _noRightPadding && _Button2.styles.noRightPadding(),
      rootClassNameWithArrow].concat(
        nonInteractive ?
        [
        _Button2.styles.disabled(_this.theme),
        isUseStateWithoutOutlineInDisabledState && _Button2.styles.disabledWithoutOutline(_this.theme),
        checked && _Button2.styles.checkedDisabled(_this.theme),
        borderless && _Button2.styles.borderless(),
        use === 'backless' && _Button2.styles.backlessDisabled(_this.theme),
        use === 'text' && _Button2.styles.textDisabled(),
        _Button2.globalClasses.disabled] :

        [
        active && !checked && _Button2.activeStyles[use](_this.theme),
        isFocused && _Button2.styles.focus(_this.theme),
        checked && _Button2.styles.checked(_this.theme),
        checked && isFocused && _Button2.styles.checkedFocused(_this.theme),
        borderless && !checked && !isFocused && _Button2.styles.borderless()])

      );

      var rootProps = (0, _extends2.default)({},
      rest, {
        className: rootClassName,
        style: (0, _extends2.default)({
          textAlign: align },
        corners),

        onFocus: _this.handleFocus,
        onBlur: _this.handleBlur,
        tabIndex: _this.getTabIndex({ disableFocus: disableFocus, disabled: nonInteractive, tabIndex: tabIndex }) });


      var wrapProps = {
        className: (0, _Emotion.cx)(_Button2.globalClasses.root, (_cx = {}, _cx[
        _Button2.styles.wrap(_this.theme)] = true, _cx[
        _this.getSizeWrapClassName()] = true, _cx)
        ),
        style: {
          width: width
        }
      };

      var buttonOnlyProps = component === 'button' ? { disabled: nonInteractive } : {};

      var innerShadowNode = null;

      var outlineNode = null;
      if ((!isFocused || isLink) && !nonInteractive) {var _cx2;
        outlineNode = /*#__PURE__*/
        _react.default.createElement("div", {
          className: (0, _Emotion.cx)(_Button2.styles.outline(), (_cx2 = {}, _cx2[
          _Button2.styles.outlineWarning(_this.theme)] = warning, _cx2[
          _Button2.styles.outlineError(_this.theme)] = error, _cx2[
          _Button2.styles.outlineLink()] = isLink, _cx2[
          _Button2.styles.outlineLinkWarning(_this.theme)] = isLink && warning, _cx2[
          _Button2.styles.outlineLinkError(_this.theme)] = isLink && error, _cx2)
          ) }
        );

      }

      var iconProps = {
        use: use,
        size: _this.size,
        hasChildren: !!children,
        loading: loading || false
      };
      var leftIconNode = icon && /*#__PURE__*/_react.default.createElement(_ButtonIcon.ButtonIcon, (0, _extends2.default)({}, iconProps, { position: "left", icon: icon }));
      var rightIconNode = rightIcon && /*#__PURE__*/
      _react.default.createElement(_ButtonIcon.ButtonIcon, (0, _extends2.default)({}, iconProps, { hasBothIcons: !!icon && !!rightIcon, position: "right", icon: rightIcon }));


      // Force disable all props and features, that cannot be use with Link
      if (isLink) {var _cx3;
        rootProps.className = (0, _Emotion.cx)((_cx3 = {}, _cx3[
        _Button2.styles.root(_this.theme)] = true, _cx3[
        sizeClass] = true, _cx3[
        _Button2.styles.link(_this.theme)] = true, _cx3[
        _Button2.styles.linkLineHeight()] = !_client.isSafari, _cx3[
        _Button2.styles.linkLineHeightSafariFallback()] = _client.isSafari, _cx3[
        _Button2.styles.linkFocus(_this.theme)] = isFocused, _cx3[
        _Button2.styles.linkDisabled(_this.theme)] = nonInteractive, _cx3)
        );
        Object.assign(wrapProps, {
          className: (0, _Emotion.cx)(_Button2.styles.wrap(_this.theme), _Button2.styles.wrapLink()),
          style: { width: wrapProps.style.width }
        });

        rootProps.style.textAlign = undefined;
      }

      var hasLoadingNode = loading && !icon && !rightIcon;
      var loadingNode = hasLoadingNode && /*#__PURE__*/_react.default.createElement(_LoadingButtonIcon.LoadingButtonIcon, { size: _this.size });

      var captionNode = /*#__PURE__*/
      _react.default.createElement("div", {
        className: (0, _Emotion.cx)(_Button2.styles.caption(), _Button2.globalClasses.caption, (_cx4 = {}, _cx4[
        _Button2.styles.captionLink()] = isLink, _cx4[
        _Button2.styles.captionDisabled()] = !checked && disabled, _cx4)
        ) },

      loadingNode,
      leftIconNode, /*#__PURE__*/
      _react.default.createElement("span", {
        className: (0, _Emotion.cx)(_Button2.globalClasses.text, (_cx5 = {}, _cx5[
        _Button2.styles.visibilityHidden()] = hasLoadingNode, _cx5)
        ) },

      children
      ),
      rightIconNode
      );

      if (isLink && !loading) {
        captionNode = /*#__PURE__*/
        _react.default.createElement(_ThemeContext.ThemeContext.Provider, { value: (0, _getInnerLinkTheme.getInnerLinkTheme)(_this.theme) }, /*#__PURE__*/

        _react.default.createElement(_Link.Link, {
          focused: isFocused,
          disabled: disabled,
          icon: _this.renderIcon2022(icon),
          rightIcon: _this.renderIcon2022(rightIcon),
          tabIndex: -1,
          component: SpanComponent },

        children
        )

        );

      }

      var Root = component;

      return /*#__PURE__*/(
        _react.default.createElement("span", (0, _extends2.default)({}, wrapProps, { "data-tid": ButtonDataTids.root }), /*#__PURE__*/
        _react.default.createElement(Root, (0, _extends2.default)({ "data-tid": ButtonDataTids.rootElement, ref: _this._ref }, rootProps, buttonOnlyProps),
        innerShadowNode,
        outlineNode,
        arrowNode,
        captionNode
        )
        ));

    };_this.








































































    handleFocus = function (e) {
      if (!_this.props.disabled && !_this.props.disableFocus) {
        // focus event fires before keyDown eventlistener
        // so we should check tabPressed in async way
        _globalObject.globalObject.requestAnimationFrame == null || _globalObject.globalObject.requestAnimationFrame(function () {
          if (_keyListener.keyListener.isTabPressed) {
            _this.setState({ focusedByTab: true });
          }
        });
        _this.props.onFocus == null || _this.props.onFocus(e);
      }
    };_this.

    handleBlur = function (e) {
      _this.setState({ focusedByTab: false });
      if (!_this.props.disabled && !_this.props.disableFocus) {
        _this.props.onBlur == null || _this.props.onBlur(e);
      }
    };_this.

    _ref = function (node) {
      _this.node = node;
    };return _this;}(0, _inheritsLoose2.default)(Button, _React$Component);var _proto = Button.prototype;_proto.componentDidMount = function componentDidMount() {if (this.props.autoFocus) {_keyListener.keyListener.isTabPressed = true;this.focus();} // warning(
    //   this.props.use !== 'link',
    //   `[Button]: Use 'Link' has been deprecated. Please, use Link with 'component=button' prop instead.`,
    // );
  };Button.getDerivedStateFromProps = function getDerivedStateFromProps(props) {if (props.loading || props.disabled) {return { focusedByTab: false };}return null;} /** Программно устанавливает фокус на кнопке. Появляется фокусная рамка, элемент получает клавиатурные события и воспринимается как текущий элемент для чтения скринридерами.
   * @public
   */;_proto.focus = function focus() {var _this$node;(_this$node = this.node) == null || _this$node.focus();} /** Программно снимает фокус с кнопки.
   * @public
   */;_proto.blur = function blur() {var _this$node2;(_this$node2 = this.node) == null || _this$node2.blur();};_proto.render = function render() {var _this2 = this;return /*#__PURE__*/_react.default.createElement(_ThemeContext.ThemeContext.Consumer, null, function (theme) {_this2.theme = _this2.props.theme ? _ThemeFactory.ThemeFactory.create(_this2.props.theme, theme) : theme;return /*#__PURE__*/_react.default.createElement(_CommonWrapper.CommonWrapper, (0, _extends2.default)({ rootNodeRef: _this2.setRootNode }, _this2.props), _this2.renderMain);});};_proto.getTabIndex = function getTabIndex(_ref2) {var disableFocus = _ref2.disableFocus,disabled = _ref2.disabled,_ref2$tabIndex = _ref2.tabIndex,tabIndex = _ref2$tabIndex === void 0 ? 0 : _ref2$tabIndex;if (disableFocus || disabled) {return -1;}return tabIndex;};_proto.renderIcon2022 = function renderIcon2022(icon) {if (icon && (0, _utils.isKonturIcon)(icon)) {var _icon$props$size;var sizes = (0, _ButtonIcon.getButtonIconSizes)(this.theme);return /*#__PURE__*/_react.default.cloneElement(icon, { size: (_icon$props$size = icon.props.size) != null ? _icon$props$size : sizes[this.size] });}return icon;};_proto.getSizeClassName = function getSizeClassName() {var _this$getProps2 = this.getProps(),icon = _this$getProps2.icon,rightIcon = _this$getProps2.rightIcon,children = _this$getProps2.children;var isThemeGTE_5_3 = (0, _ThemeHelpers.isThemeGTE)(this.theme, '5.3');switch (this.size) {case 'large':{var _commonClasses, _themeSpecificClasses;var commonClasses = (_commonClasses = {}, _commonClasses[_Button2.styles.sizeLargeIE11(this.theme)] = _client.isIE11 || _client.isEdge, _commonClasses[_Button2.styles.sizeLargeWithIcon(this.theme)] = !!icon, _commonClasses[_Button2.styles.sizeLargeWithIconWithoutText(this.theme)] = !!icon && !children, _commonClasses);var themeSpecificClasses = (_themeSpecificClasses = {}, _themeSpecificClasses[_Button2.styles.sizeLargeWithRightIcon(this.theme)] = !!rightIcon, _themeSpecificClasses[_Button2.styles.sizeLargeWithIconWithoutText5_3(this.theme)] = (!!icon || !!rightIcon) && !children, _themeSpecificClasses);return (0, _Emotion.cx)(_Button2.styles.sizeLarge(this.theme), commonClasses, isThemeGTE_5_3 && themeSpecificClasses);}case 'medium':{var _commonClasses3, _themeSpecificClasses3;var _commonClasses2 = (_commonClasses3 = {}, _commonClasses3[_Button2.styles.sizeMediumIE11(this.theme)] = _client.isIE11 || _client.isEdge, _commonClasses3[_Button2.styles.sizeMediumWithIcon(this.theme)] = !!icon, _commonClasses3[_Button2.styles.sizeMediumWithIconWithoutText(this.theme)] = !!icon && !children, _commonClasses3);var _themeSpecificClasses2 = (_themeSpecificClasses3 = {}, _themeSpecificClasses3[_Button2.styles.sizeMediumWithRightIcon(this.theme)] = !!rightIcon, _themeSpecificClasses3[_Button2.styles.sizeMediumWithIconWithoutText5_3(this.theme)] = (!!icon || !!rightIcon) && !children, _themeSpecificClasses3);return (0, _Emotion.cx)(_Button2.styles.sizeMedium(this.theme), _commonClasses2, isThemeGTE_5_3 && _themeSpecificClasses2);}case 'small':default:{var _commonClasses5, _themeSpecificClasses5;var _commonClasses4 = (_commonClasses5 = {}, _commonClasses5[_Button2.styles.sizeSmallIE11(this.theme)] = _client.isIE11 || _client.isEdge, _commonClasses5[_Button2.styles.sizeSmallWithIcon(this.theme)] = !!icon, _commonClasses5[_Button2.styles.sizeSmallWithIconWithoutText(this.theme)] = !!icon && !children, _commonClasses5);var _themeSpecificClasses4 = (_themeSpecificClasses5 = {}, _themeSpecificClasses5[_Button2.styles.sizeSmallWithRightIcon(this.theme)] = !!rightIcon, _themeSpecificClasses5[_Button2.styles.sizeSmallWithIconWithoutText5_3(this.theme)] = (!!icon || !!rightIcon) && !children, _themeSpecificClasses5);return (0, _Emotion.cx)(_Button2.styles.sizeSmall(this.theme), _commonClasses4, isThemeGTE_5_3 && _themeSpecificClasses4);}}};_proto.getSizeWrapClassName = function getSizeWrapClassName() {switch (this.size) {case 'large':return _Button2.styles.wrapLarge(this.theme);case 'medium':return _Button2.styles.wrapMedium(this.theme);case 'small':default:return _Button2.styles.wrapSmall(this.theme);}};return Button;}(_react.default.Component), _Button.__KONTUR_REACT_UI__ = 'Button', _Button.displayName = 'Button', _Button.__BUTTON__ = true, _Button.defaultProps = { use: 'default', // By default, the type attribute is 'submit'. IE8 will fire a click event
  // on this button if somewhere on the page user presses Enter while some
  // input is focused. So we set type to 'button' by default.
  type: 'button', component: BUTTON_DEFAULT_COMPONENT }, _Button)) || _class) || _class;