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


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


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

var _rootNode = require("../../lib/rootNode");
var _fixFirefoxModifiedClickOnLabel = require("../../lib/events/fixFirefoxModifiedClickOnLabel");
var _client = require("../../lib/client");

var _RadioGroupContext = require("../RadioGroup/RadioGroupContext");
var _createPropsGetter = require("../../lib/createPropsGetter");

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

var _Radio2 = require("./Radio.styles");var _excluded = ["disabled", "warning", "error", "size", "focused", "onMouseOver", "onMouseEnter", "onMouseLeave", "onValueChange"];var _class, _Radio;











































var RadioDataTids = exports.RadioDataTids = {
  root: 'Radio__root'
};



/** Радиокнопка позволяет выбрать одно значение из нескольких. Подходит при небольшом количестве вариантов — 2–5.
 *
 * Для создания группы радиокнопок используйте специальный контейнер — компонент [RadioGroup](https://tech.skbkontur.ru/kontur-ui/?path=/docs/react-ui_input-data-radiogroup--docs).
 */var


Radio = exports.Radio = (0, _rootNode.rootNode)(_class = (0, _SizeDecorator.withSize)(_class = (_Radio = /*#__PURE__*/function (_React$Component) {function Radio() {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.



    state = {
      focusedByKeyboard: false
    };_this.





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


    context = _this.context;_this.


    inputEl = /*#__PURE__*/_react.default.createRef();_this.






































































    renderMain = function (props) {var _cx, _cx2;
      var _props$disabled =










        props.disabled,disabled = _props$disabled === void 0 ? _this.context.disabled : _props$disabled,_props$warning = props.warning,warning = _props$warning === void 0 ? _this.context.warning : _props$warning,_props$error = props.error,error = _props$error === void 0 ? _this.context.error : _props$error,size = props.size,focused = props.focused,onMouseOver = props.onMouseOver,onMouseEnter = props.onMouseEnter,onMouseLeave = props.onMouseLeave,onValueChange = props.onValueChange,rest = (0, _objectWithoutPropertiesLoose2.default)(props, _excluded);

      var radioProps = {
        className: (0, _Emotion.cx)((_cx = {}, _cx[
        _Radio2.styles.circle(_this.theme)] = true, _cx[
        _this.getCircleSizeClassName()] = true, _cx[
        _Radio2.styles.checked(_this.theme)] = _this.props.checked, _cx[
        _this.getCheckedSizeClassName()] = _this.props.checked, _cx[
        _Radio2.styles.focus(_this.theme)] = _this.getProps().focused || _this.state.focusedByKeyboard, _cx[
        _Radio2.styles.error(_this.theme)] = error, _cx[
        _Radio2.styles.warning(_this.theme)] = warning, _cx[
        _Radio2.styles.disabled(_this.theme)] = disabled, _cx[
        _Radio2.styles.checkedDisabled(_this.theme)] = _this.props.checked && disabled, _cx[
        _Radio2.globalClasses.circle] = true, _cx)
        )
      };

      var value;
      if (typeof _this.props.value === 'string' || typeof _this.props.value === 'number') {
        value = _this.props.value;
      }

      var inputProps = (0, _extends2.default)({},
      rest, {
        type: 'radio',
        className: _Radio2.styles.input(),
        disabled: disabled,
        tabIndex: _this.props.tabIndex,
        value: value,
        ref: _this.inputEl,
        onChange: _this.handleChange,
        onFocus: _this.handleFocus,
        onBlur: _this.handleBlur });


      var labelProps = {
        className: (0, _Emotion.cx)(_Radio2.styles.root(_this.theme), _this.getRootSizeClassName(), (_cx2 = {}, _cx2[
        _Radio2.styles.rootChecked(_this.theme)] = _this.props.checked, _cx2[
        _Radio2.styles.rootIE11()] = _client.isIE11 || _client.isEdge, _cx2)
        ),
        onMouseOver: _this.handleMouseOver,
        onMouseEnter: _this.handleMouseEnter,
        onMouseLeave: _this.handleMouseLeave,
        onClick: (0, _fixFirefoxModifiedClickOnLabel.fixFirefoxModifiedClickOnLabel)(_this.inputEl)
      };

      if (_this._isInRadioGroup()) {var _cx3, _cx4;
        var checked = _this.props.value === _this.context.activeItem;
        inputProps.checked = checked;
        inputProps.name = _this.context.name;
        inputProps.suppressHydrationWarning = true;
        labelProps.className = (0, _Emotion.cx)(_Radio2.styles.root(_this.theme), _this.getRootSizeClassName(), (_cx3 = {}, _cx3[
        _Radio2.styles.rootChecked(_this.theme)] = checked, _cx3[
        _Radio2.styles.rootIE11()] = _client.isIE11 || _client.isEdge, _cx3)
        );
        radioProps.className = (0, _Emotion.cx)(radioProps.className, (_cx4 = {}, _cx4[
        _Radio2.styles.checked(_this.theme)] = checked, _cx4[
        _this.getCheckedSizeClassName()] = checked, _cx4[
        _Radio2.styles.checkedDisabled(_this.theme)] = checked && disabled, _cx4)
        );
      }

      return /*#__PURE__*/(
        _react.default.createElement("label", (0, _extends2.default)({ "data-tid": RadioDataTids.root }, labelProps), /*#__PURE__*/
        _react.default.createElement(_FocusControlWrapper.FocusControlWrapper, { onBlurWhenDisabled: _this.resetFocus }, /*#__PURE__*/
        _react.default.createElement("input", inputProps)
        ), /*#__PURE__*/
        _react.default.createElement("span", radioProps, /*#__PURE__*/
        _react.default.createElement("span", { className: _Radio2.styles.placeholder() })
        ),
        _this.props.children && _this.renderCaption()
        ));

    };_this.

    _isInRadioGroup = function () {return Boolean(_this.context.name);};_this.











    handleChange = function (e) {
      _this.props.onValueChange == null || _this.props.onValueChange(_this.props.value);

      if (_this._isInRadioGroup()) {
        _this.context.onSelect(_this.props.value);
      }

      _this.props.onChange == null || _this.props.onChange(e);
    };_this.

    handleMouseOver = function (e) {
      _this.props.onMouseOver == null || _this.props.onMouseOver(e);
    };_this.

    handleMouseEnter = function (e) {
      _this.props.onMouseEnter == null || _this.props.onMouseEnter(e);
    };_this.

    handleMouseLeave = function (e) {
      _this.props.onMouseLeave == null || _this.props.onMouseLeave(e);
    };_this.

    handleFocus = function (e) {
      if (!_this.context.disabled) {
        // 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.isArrowPressed || _keyListener.keyListener.isTabPressed) {
            _this.setState({ focusedByKeyboard: true });
          }
        });

        if (_this.props.onFocus) {
          _this.props.onFocus(e);
        }
      }
    };_this.

    resetFocus = function () {return _this.setState({ focusedByKeyboard: false });};_this.

    handleBlur = function (e) {
      _this.resetFocus();
      _this.props.onBlur == null || _this.props.onBlur(e);
    };return _this;}(0, _inheritsLoose2.default)(Radio, _React$Component);var _proto = Radio.prototype;_proto.getRootSizeClassName = function getRootSizeClassName() {switch (this.size) {case 'large':return _Radio2.styles.rootLarge(this.theme);case 'medium':return _Radio2.styles.rootMedium(this.theme);case 'small':default:return _Radio2.styles.rootSmall(this.theme);}};_proto.getCircleSizeClassName = function getCircleSizeClassName() {switch (this.size) {case 'large':return _Radio2.styles.circleLarge(this.theme);case 'medium':return _Radio2.styles.circleMedium(this.theme);case 'small':default:return _Radio2.styles.circleSmall(this.theme);}};_proto.getCheckedSizeClassName = function getCheckedSizeClassName() {switch (this.size) {case 'large':return _Radio2.styles.checkedLarge(this.theme);case 'medium':return _Radio2.styles.checkedMedium(this.theme);case 'small':default:return _Radio2.styles.checkedSmall(this.theme);}};_proto.render = function render() {var _this2 = this;return /*#__PURE__*/_react.default.createElement(_ThemeContext.ThemeContext.Consumer, null, function (theme) {_this2.theme = theme;return /*#__PURE__*/_react.default.createElement(_CommonWrapper.CommonWrapper, (0, _extends2.default)({ rootNodeRef: _this2.setRootNode }, _this2.getProps()), _this2.renderMain);});} /** Программно устанавливает фокус на радиокнопку. Появляется фокусная обводка, элемент получает клавиатурные события и воспринимается как текущий элемент для чтения скринридерами.
   * @public
   */;_proto.focus = function focus() {var _this$inputEl$current;_keyListener.keyListener.isTabPressed = true;(_this$inputEl$current = this.inputEl.current) == null || _this$inputEl$current.focus();} /** Программно снимает фокус с радиокнопки.
   * @public
   */;_proto.blur = function blur() {var _this$inputEl$current2;(_this$inputEl$current2 = this.inputEl.current) == null || _this$inputEl$current2.blur();};_proto.renderCaption = function renderCaption() {var _cx5;var captionClassNames = (0, _Emotion.cx)((_cx5 = {}, _cx5[_Radio2.styles.caption(this.theme)] = true, _cx5[_Radio2.styles.captionDisabled(this.theme)] = !!(this.props.disabled || this.context.disabled), _cx5[_Radio2.styles.captionIE11()] = _client.isIE11 || _client.isEdge, _cx5));return /*#__PURE__*/_react.default.createElement("div", { className: captionClassNames }, this.props.children);};return Radio;}(_react.default.Component), _Radio.__KONTUR_REACT_UI__ = 'Radio', _Radio.displayName = 'Radio', _Radio.defaultProps = { focused: false }, _Radio.contextType = _RadioGroupContext.RadioGroupContext, _Radio)) || _class) || _class;