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 { KeyListener } from '../../lib/events/keyListener.js';
import { ThemeContext } from '../../lib/theming/ThemeContext.js';
import { CommonWrapper } from '../../internal/CommonWrapper/index.js';
import { rootNode } from '../../lib/rootNode/index.js';
import { fixFirefoxModifiedClickOnLabel } from '../../lib/events/fixFirefoxModifiedClickOnLabel.js';
import { FocusControlWrapper } from '../../internal/FocusControlWrapper/index.js';
import { withSize } from '../../lib/size/SizeDecorator.js';
import { createPropsGetter } from '../../lib/createPropsGetter.js';
import { withRenderEnvironment } from '../../lib/renderEnvironment/index.js';
import { getStyles, globalClasses } from './Checkbox.styles.js';
import { CheckedIcon } from './CheckedIcon.js';
import { IndeterminateIcon } from './IndeterminateIcon.js';
export var CheckboxDataTids = {
    root: 'Checkbox__root',
};
/**
 * `Checkbox` используется для управления параметром с двумя состояниями.
 *
 * Чекбокс не запускает действие немедленно. Как правило, для этого нужно нажать подтверждающую кнопку.
 * Для немедленного включения какого-то режима в интерфейсе лучше подходит Toggle.
 */
var Checkbox = /** @class */ (function (_super) {
    __extends(Checkbox, _super);
    function Checkbox() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.state = {
            focusedByTab: false,
            indeterminate: _this.props.initialIndeterminate || false,
            isShiftPressed: false,
        };
        _this.input = React.createRef();
        _this.getProps = createPropsGetter({});
        _this.handleShiftPress = function (e) {
            if (e.key === 'Shift') {
                _this.setState(function () { return ({
                    isShiftPressed: true,
                }); });
            }
        };
        _this.handleShiftRelease = function (e) {
            if (e.key === 'Shift') {
                _this.setState({
                    isShiftPressed: false,
                });
            }
        };
        _this.componentDidMount = function () {
            var _a, _b;
            _this.keyListener = new KeyListener(_this.globalObject);
            if (_this.state.indeterminate && _this.input.current) {
                _this.input.current.indeterminate = true;
            }
            (_a = _this.globalObject.document) === null || _a === void 0 ? void 0 : _a.addEventListener('keydown', _this.handleShiftPress);
            (_b = _this.globalObject.document) === null || _b === void 0 ? void 0 : _b.addEventListener('keyup', _this.handleShiftRelease);
        };
        _this.componentWillUnmount = function () {
            var _a, _b;
            (_a = _this.globalObject.document) === null || _a === void 0 ? void 0 : _a.removeEventListener('keydown', _this.handleShiftPress);
            (_b = _this.globalObject.document) === null || _b === void 0 ? void 0 : _b.removeEventListener('keyup', _this.handleShiftRelease);
        };
        /**
         * Устанавливает чекбокс в HTML-состояние `indeterminate`.
         * @public
         */
        _this.setIndeterminate = function () {
            _this.setState({
                indeterminate: true,
            });
            if (_this.input.current) {
                _this.input.current.indeterminate = true;
            }
        };
        /**
         * Снимает с чекбокса HTML-состояние `indeterminate`.
         * @public
         */
        _this.resetIndeterminate = function () {
            _this.setState({
                indeterminate: false,
            });
            if (_this.input.current) {
                _this.input.current.indeterminate = false;
            }
        };
        _this.renderMain = function (props) {
            var _a, _b, _c, _d;
            var error = props.error, warning = props.warning, size = props.size, onMouseEnter = props.onMouseEnter, onMouseLeave = props.onMouseLeave, onMouseOver = props.onMouseOver, onValueChange = props.onValueChange, onClick = props.onClick, type = props.type, initialIndeterminate = props.initialIndeterminate, ariaDescribedby = props["aria-describedby"], ariaLabel = props["aria-label"], rest = __rest(props, ["error", "warning", "size", "onMouseEnter", "onMouseLeave", "onMouseOver", "onValueChange", "onClick", "type", "initialIndeterminate", 'aria-describedby', 'aria-label']);
            var isIndeterminate = _this.state.indeterminate;
            var iconClass = _this.cx(_this.styles.icon(), !_this.props.checked && !isIndeterminate && _this.styles.iconUnchecked());
            var iconSize = parseInt(_this.getCheckboxBoxSize());
            var IconCheck = (React.createElement("span", { className: iconClass },
                React.createElement(CheckedIcon, { size: iconSize })));
            var IconSquare = (React.createElement("span", { className: iconClass },
                React.createElement(IndeterminateIcon, { size: iconSize })));
            var rootClass = _this.cx(_this.getRootSizeClassName(), (_a = {},
                _a[_this.styles.root(_this.theme)] = true,
                _a[_this.styles.rootChecked(_this.theme)] = props.checked || isIndeterminate,
                _a[_this.styles.rootDisableTextSelect()] = _this.state.isShiftPressed,
                _a[_this.styles.disabled(_this.theme)] = Boolean(_this.props.disabled),
                _a));
            var inputProps = __assign(__assign({}, rest), { type: 'checkbox', className: _this.styles.input(), onChange: _this.handleChange, onFocus: _this.handleFocus, onBlur: _this.handleBlur, onClick: _this.handleInputClick, ref: _this.input });
            var caption = null;
            if (_this.props.children) {
                var captionClass = _this.cx((_b = {},
                    _b[_this.styles.caption(_this.theme)] = true,
                    _b[_this.styles.disabled(_this.theme)] = Boolean(props.disabled),
                    _b));
                caption = React.createElement("span", { className: captionClass }, _this.props.children);
            }
            var box = (React.createElement("div", { className: _this.cx(_this.getBoxWrapperSizeClassName(), (_c = {},
                    _c[_this.styles.boxWrapper(_this.theme)] = true,
                    _c)) },
                React.createElement("div", { className: _this.cx(_this.styles.box(_this.theme), globalClasses.box, (_d = {},
                        _d[_this.styles.boxChecked(_this.theme)] = _this.props.checked || isIndeterminate,
                        _d[_this.styles.boxFocus(_this.theme)] = _this.state.focusedByTab,
                        _d[_this.styles.boxError(_this.theme)] = _this.props.error,
                        _d[_this.styles.boxWarning(_this.theme)] = _this.props.warning,
                        _d[_this.styles.boxDisabled(_this.theme)] = _this.props.disabled,
                        _d)) }, (isIndeterminate && IconSquare) || IconCheck)));
            return (React.createElement("label", { "data-tid": CheckboxDataTids.root, className: rootClass, onMouseEnter: onMouseEnter, onMouseLeave: onMouseLeave, onMouseOver: onMouseOver, onClick: _this.handleLabelClick },
                React.createElement(FocusControlWrapper, { onBlurWhenDisabled: _this.resetFocus },
                    React.createElement("input", __assign({}, inputProps, { "aria-label": ariaLabel, "aria-describedby": ariaDescribedby }))),
                box,
                caption));
        };
        _this.handleFocus = function (e) {
            var _a, _b;
            if (!_this.props.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.isTabPressed) {
                        _this.setState({ focusedByTab: true });
                    }
                });
                if (_this.props.onFocus) {
                    _this.props.onFocus(e);
                }
            }
        };
        _this.resetFocus = function () { return _this.setState({ focusedByTab: 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);
        };
        _this.handleChange = function (event) {
            var _a, _b, _c, _d;
            var checked = event.currentTarget.checked;
            (_b = (_a = _this.props).onValueChange) === null || _b === void 0 ? void 0 : _b.call(_a, checked);
            _this.resetIndeterminate();
            (_d = (_c = _this.props).onChange) === null || _d === void 0 ? void 0 : _d.call(_c, event);
        };
        _this.handleLabelClick = function (e) {
            var handleModifierClickInFirefox = fixFirefoxModifiedClickOnLabel(_this.input);
            handleModifierClickInFirefox(e);
            if (_this.props.onClick && e.target !== _this.input.current) {
                e.stopPropagation();
            }
        };
        _this.handleInputClick = function (e) {
            var _a, _b;
            (_b = (_a = _this.props).onClick) === null || _b === void 0 ? void 0 : _b.call(_a, e);
        };
        return _this;
    }
    Checkbox.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);
        }
    };
    Checkbox.prototype.getBoxWrapperSizeClassName = function () {
        switch (this.size) {
            case 'large':
                return this.styles.boxWrapperLarge(this.theme);
            case 'medium':
                return this.styles.boxWrapperMedium(this.theme);
            case 'small':
            default:
                return this.styles.boxWrapperSmall(this.theme);
        }
    };
    Checkbox.prototype.getCheckboxBoxSize = function () {
        switch (this.size) {
            case 'large':
                return this.theme.checkboxBoxSizeLarge;
            case 'medium':
                return this.theme.checkboxBoxSizeMedium;
            case 'small':
            default:
                return this.theme.checkboxBoxSizeSmall;
        }
    };
    Checkbox.prototype.componentDidUpdate = function (prevProps) {
        if (prevProps.checked !== this.props.checked) {
            this.resetIndeterminate();
        }
    };
    Checkbox.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
     */
    Checkbox.prototype.focus = function () {
        var _a;
        this.keyListener.isTabPressed = true;
        (_a = this.input.current) === null || _a === void 0 ? void 0 : _a.focus();
    };
    /**
     * Программное снятие фокуса с чекбокса.
     * @public
     */
    Checkbox.prototype.blur = function () {
        var _a;
        (_a = this.input.current) === null || _a === void 0 ? void 0 : _a.blur();
    };
    Checkbox.__KONTUR_REACT_UI__ = 'Checkbox';
    Checkbox.displayName = 'Checkbox';
    Checkbox = __decorate([
        withRenderEnvironment,
        rootNode,
        withSize
    ], Checkbox);
    return Checkbox;
}(React.PureComponent));
export { Checkbox };
//# sourceMappingURL=Checkbox.js.map