var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var __assign = (this && this.__assign) || function () {
    __assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return __assign.apply(this, arguments);
};
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __rest = (this && this.__rest) || function (s, e) {
    var t = {};
    for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
        t[p] = s[p];
    if (s != null && typeof Object.getOwnPropertySymbols === "function")
        for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
            if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
                t[p[i]] = s[p[i]];
        }
    return t;
};
import React from 'react';
import { ThemeContext } from '../../lib/theming/ThemeContext.js';
import { CommonWrapper } from '../../internal/CommonWrapper/index.js';
import { KeyListener } from '../../lib/events/keyListener.js';
import { rootNode } from '../../lib/rootNode/index.js';
import { fixFirefoxModifiedClickOnLabel } from '../../lib/events/fixFirefoxModifiedClickOnLabel.js';
import { RadioGroupContext } from '../RadioGroup/RadioGroupContext.js';
import { createPropsGetter } from '../../lib/createPropsGetter.js';
import { FocusControlWrapper } from '../../internal/FocusControlWrapper/index.js';
import { withSize } from '../../lib/size/SizeDecorator.js';
import { withRenderEnvironment } from '../../lib/renderEnvironment/index.js';
import { getStyles, globalClasses } from './Radio.styles.js';
export var RadioDataTids = {
    root: 'Radio__root',
};
/** Радиокнопка позволяет выбрать одно значение из нескольких. Подходит при небольшом количестве вариантов — 2–5.
 *
 * Для создания группы радиокнопок используйте специальный контейнер — компонент [RadioGroup](https://tech.skbkontur.ru/kontur-ui/?path=/docs/react-ui_input-data-radiogroup--docs).
 */
var Radio = /** @class */ (function (_super) {
    __extends(Radio, _super);
    function Radio() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.state = {
            focusedByKeyboard: false,
        };
        _this.getProps = createPropsGetter(Radio_1.defaultProps);
        _this.context = _this.context;
        _this.inputEl = React.createRef();
        _this.renderMain = function (props) {
            var _a, _b, _c, _d;
            var _e = props.disabled, disabled = _e === void 0 ? _this.context.disabled : _e, _f = props.warning, warning = _f === void 0 ? _this.context.warning : _f, _g = props.error, error = _g === void 0 ? _this.context.error : _g, size = props.size, focused = props.focused, onMouseOver = props.onMouseOver, onMouseEnter = props.onMouseEnter, onMouseLeave = props.onMouseLeave, onValueChange = props.onValueChange, rest = __rest(props, ["disabled", "warning", "error", "size", "focused", "onMouseOver", "onMouseEnter", "onMouseLeave", "onValueChange"]);
            var radioProps = {
                className: _this.cx((_a = {},
                    _a[_this.styles.circle(_this.theme)] = true,
                    _a[_this.getCircleSizeClassName()] = true,
                    _a[_this.styles.checked(_this.theme)] = _this.props.checked,
                    _a[_this.getCheckedSizeClassName()] = _this.props.checked,
                    _a[_this.styles.focus(_this.theme)] = _this.getProps().focused || _this.state.focusedByKeyboard,
                    _a[_this.styles.error(_this.theme)] = error,
                    _a[_this.styles.warning(_this.theme)] = warning,
                    _a[_this.styles.disabled(_this.theme)] = disabled,
                    _a[_this.styles.checkedDisabled(_this.theme)] = _this.props.checked && disabled,
                    _a[globalClasses.circle] = true,
                    _a)),
            };
            var value;
            if (typeof _this.props.value === 'string' || typeof _this.props.value === 'number') {
                value = _this.props.value;
            }
            var inputProps = __assign(__assign({}, rest), { type: 'radio', className: _this.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: _this.cx(_this.styles.root(_this.theme), _this.getRootSizeClassName(), (_b = {},
                    _b[_this.styles.rootChecked(_this.theme)] = _this.props.checked,
                    _b)),
                onMouseOver: _this.handleMouseOver,
                onMouseEnter: _this.handleMouseEnter,
                onMouseLeave: _this.handleMouseLeave,
                onClick: fixFirefoxModifiedClickOnLabel(_this.inputEl),
            };
            if (_this._isInRadioGroup()) {
                var checked = _this.props.value === _this.context.activeItem;
                inputProps.checked = checked;
                inputProps.name = _this.context.name;
                inputProps.suppressHydrationWarning = true;
                labelProps.className = _this.cx(_this.styles.root(_this.theme), _this.getRootSizeClassName(), (_c = {},
                    _c[_this.styles.rootChecked(_this.theme)] = checked,
                    _c));
                radioProps.className = _this.cx(radioProps.className, (_d = {},
                    _d[_this.styles.checked(_this.theme)] = checked,
                    _d[_this.getCheckedSizeClassName()] = checked,
                    _d[_this.styles.checkedDisabled(_this.theme)] = checked && disabled,
                    _d));
            }
            return (React.createElement("label", __assign({ "data-tid": RadioDataTids.root }, labelProps),
                React.createElement(FocusControlWrapper, { onBlurWhenDisabled: _this.resetFocus },
                    React.createElement("input", __assign({}, inputProps))),
                React.createElement("span", __assign({}, radioProps),
                    React.createElement("span", { className: _this.styles.placeholder() })),
                _this.props.children && _this.renderCaption()));
        };
        _this._isInRadioGroup = function () { return Boolean(_this.context.name); };
        _this.handleChange = function (e) {
            var _a, _b, _c, _d;
            (_b = (_a = _this.props).onValueChange) === null || _b === void 0 ? void 0 : _b.call(_a, _this.props.value);
            if (_this._isInRadioGroup()) {
                _this.context.onSelect(_this.props.value);
            }
            (_d = (_c = _this.props).onChange) === null || _d === void 0 ? void 0 : _d.call(_c, e);
        };
        _this.handleMouseOver = function (e) {
            var _a, _b;
            (_b = (_a = _this.props).onMouseOver) === null || _b === void 0 ? void 0 : _b.call(_a, e);
        };
        _this.handleMouseEnter = function (e) {
            var _a, _b;
            (_b = (_a = _this.props).onMouseEnter) === null || _b === void 0 ? void 0 : _b.call(_a, e);
        };
        _this.handleMouseLeave = function (e) {
            var _a, _b;
            (_b = (_a = _this.props).onMouseLeave) === null || _b === void 0 ? void 0 : _b.call(_a, e);
        };
        _this.handleFocus = function (e) {
            var _a, _b;
            if (!_this.context.disabled) {
                // focus event fires before keyDown eventlistener
                // so we should check tabPressed in async way
                (_b = (_a = _this.globalObject).requestAnimationFrame) === null || _b === void 0 ? void 0 : _b.call(_a, function () {
                    if (_this.keyListener.isArrowPressed || _this.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) {
            var _a, _b;
            _this.resetFocus();
            (_b = (_a = _this.props).onBlur) === null || _b === void 0 ? void 0 : _b.call(_a, e);
        };
        return _this;
    }
    Radio_1 = Radio;
    Radio.prototype.getRootSizeClassName = function () {
        switch (this.size) {
            case 'large':
                return this.styles.rootLarge(this.theme);
            case 'medium':
                return this.styles.rootMedium(this.theme);
            case 'small':
            default:
                return this.styles.rootSmall(this.theme);
        }
    };
    Radio.prototype.getCircleSizeClassName = function () {
        switch (this.size) {
            case 'large':
                return this.styles.circleLarge(this.theme);
            case 'medium':
                return this.styles.circleMedium(this.theme);
            case 'small':
            default:
                return this.styles.circleSmall(this.theme);
        }
    };
    Radio.prototype.getCheckedSizeClassName = function () {
        switch (this.size) {
            case 'large':
                return this.styles.checkedLarge(this.theme);
            case 'medium':
                return this.styles.checkedMedium(this.theme);
            case 'small':
            default:
                return this.styles.checkedSmall(this.theme);
        }
    };
    Radio.prototype.componentDidMount = function () {
        this.keyListener = new KeyListener(this.globalObject);
    };
    Radio.prototype.render = function () {
        var _this = this;
        this.styles = getStyles(this.emotion);
        return (React.createElement(ThemeContext.Consumer, null, function (theme) {
            _this.theme = theme;
            return (React.createElement(CommonWrapper, __assign({ rootNodeRef: _this.setRootNode }, _this.getProps()), _this.renderMain));
        }));
    };
    /** Программно устанавливает фокус на радиокнопку. Появляется фокусная обводка, элемент получает клавиатурные события и воспринимается как текущий элемент для чтения скринридерами.
     * @public
     */
    Radio.prototype.focus = function () {
        var _a;
        this.keyListener.isTabPressed = true;
        (_a = this.inputEl.current) === null || _a === void 0 ? void 0 : _a.focus();
    };
    /** Программно снимает фокус с радиокнопки.
     * @public
     */
    Radio.prototype.blur = function () {
        var _a;
        (_a = this.inputEl.current) === null || _a === void 0 ? void 0 : _a.blur();
    };
    Radio.prototype.renderCaption = function () {
        var _a;
        var captionClassNames = this.cx((_a = {},
            _a[this.styles.caption(this.theme)] = true,
            _a[this.styles.captionDisabled(this.theme)] = !!(this.props.disabled || this.context.disabled),
            _a));
        return React.createElement("div", { className: captionClassNames }, this.props.children);
    };
    var Radio_1;
    Radio.__KONTUR_REACT_UI__ = 'Radio';
    Radio.displayName = 'Radio';
    Radio.defaultProps = {
        focused: false,
    };
    Radio.contextType = RadioGroupContext;
    Radio = Radio_1 = __decorate([
        withRenderEnvironment,
        rootNode,
        withSize
    ], Radio);
    return Radio;
}(React.Component));
export { Radio };
//# sourceMappingURL=Radio.js.map