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 ReactDOM from 'react-dom';
import debounce from 'lodash.debounce';
import { isNonNullable } from '../../lib/utils.js';
import { MouseDrag } from '../../lib/events/MouseDrag.js';
import { isMobile } from '../../lib/client.js';
import { removeAllSelections, selectNodeContents } from '../../lib/dom/selectionHelpers.js';
import { calculateClearCrossShowedState, InputDataTids } from '../../components/Input/index.js';
import { getStyles as getJsInputStyles } from '../../components/Input/Input.styles.js';
import { ThemeContext } from '../../lib/theming/ThemeContext.js';
import { CommonWrapper } from '../CommonWrapper/index.js';
import { rootNode } from '../../lib/rootNode/index.js';
import { createPropsGetter } from '../../lib/createPropsGetter.js';
import { InputLayoutAside } from '../../components/Input/InputLayout/InputLayoutAside.js';
import { InputLayoutContext, InputLayoutContextDefault, } from '../../components/Input/InputLayout/InputLayoutContext.js';
import { FocusControlWrapper } from '../FocusControlWrapper/index.js';
import { ClearCrossIcon } from '../ClearCrossIcon/ClearCrossIcon.js';
import { blink } from '../../lib/blink.js';
import { withSize } from '../../lib/size/SizeDecorator.js';
import { withRenderEnvironment } from '../../lib/renderEnvironment/index.js';
import { getStyles } from './InputLikeText.styles.js';
export var InputLikeTextDataTids = {
    root: 'InputLikeText__root',
    input: 'InputLikeText__input',
    nativeInput: 'InputLikeText__nativeInput',
};
var InputLikeText = /** @class */ (function (_super) {
    __extends(InputLikeText, _super);
    function InputLikeText() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.getProps = createPropsGetter(InputLikeText_1.defaultProps);
        _this.getClearCrossShowed = function (_a) {
            var focused = _a.focused, hovered = _a.hovered;
            if (_this.props.disabled) {
                return false;
            }
            return calculateClearCrossShowedState({
                showClearIcon: _this.getProps().showClearIcon,
                notEmptyValue: Boolean(_this.props.children),
                focused: focused,
                hovered: hovered,
            });
        };
        _this.state = {
            focused: false,
            clearCrossShowed: _this.getClearCrossShowed({
                focused: false,
            }),
        };
        _this.node = null;
        _this.dragging = false;
        // Async call required for Firefox
        _this.selectNodeContentsDebounced = debounce(selectNodeContents, 0);
        _this.selectInnerNode = function (node, start, end) {
            if (start === void 0) { start = 0; }
            if (end === void 0) { end = 1; }
            if (_this.dragging || !node) {
                return;
            }
            _this.selectNodeContentsDebounced(node, start, end);
        };
        _this.renderMain = function (props) {
            var _a, _b, _c;
            var innerRef = props.innerRef, tabIndex = props.tabIndex, placeholder = props.placeholder, align = props.align, borderless = props.borderless, width = props.width, error = props.error, warning = props.warning, onValueChange = props.onValueChange, disabled = props.disabled, prefix = props.prefix, suffix = props.suffix, leftIcon = props.leftIcon, rightIcon = props.rightIcon, value = props.value, onMouseDragStart = props.onMouseDragStart, onMouseDragEnd = props.onMouseDragEnd, takeContentWidth = props.takeContentWidth, ariaDescribedby = props["aria-describedby"], ariaLabel = props["aria-label"], ariaLabelledby = props["aria-labelledby"], showClearIcon = props.showClearIcon, onClearCrossClick = props.onClearCrossClick, rest = __rest(props, ["innerRef", "tabIndex", "placeholder", "align", "borderless", "width", "error", "warning", "onValueChange", "disabled", "prefix", "suffix", "leftIcon", "rightIcon", "value", "onMouseDragStart", "onMouseDragEnd", "takeContentWidth", 'aria-describedby', 'aria-label', 'aria-labelledby', "showClearIcon", "onClearCrossClick"]);
            var focused = _this.state.focused;
            var getRightIcon = function () {
                return _this.state.clearCrossShowed ? (React.createElement(ClearCrossIcon, { "data-tid": InputDataTids.clearCross, size: _this.size, onFocus: function (event) { return event.stopPropagation(); }, onClick: onClearCrossClick })) : (rightIcon);
            };
            var leftSide = React.createElement(InputLayoutAside, { icon: leftIcon, text: prefix, side: "left" });
            var rightSide = React.createElement(InputLayoutAside, { icon: getRightIcon(), text: suffix, side: "right" });
            var className = _this.cx(_this.styles.root(), _this.jsInputStyles.root(_this.theme), _this.getSizeClassName(), (_a = {},
                _a[_this.jsInputStyles.disabled(_this.theme)] = !!disabled,
                _a[_this.jsInputStyles.borderless()] = !!borderless,
                _a[_this.jsInputStyles.focus(_this.theme)] = focused,
                _a[_this.jsInputStyles.hovering(_this.theme)] = !focused && !disabled && !warning && !error && !borderless,
                _a[_this.jsInputStyles.warning(_this.theme)] = !!warning,
                _a[_this.jsInputStyles.error(_this.theme)] = !!error,
                _a[_this.jsInputStyles.hideBlinkingCursor()] = isMobile,
                _a));
            var wrapperClass = _this.cx(_this.jsInputStyles.wrapper(), (_b = {},
                _b[_this.styles.userSelectContain()] = focused,
                _b));
            var size = _this.size;
            var context = InputLayoutContextDefault;
            Object.assign(context, { disabled: disabled, focused: focused, size: size });
            return (React.createElement(FocusControlWrapper, { disabled: disabled, onBlurWhenDisabled: _this.resetFocus },
                React.createElement("span", __assign({ "data-tid": InputLikeTextDataTids.root }, rest, { className: className, style: { width: width, textAlign: align }, tabIndex: disabled ? -1 : 0, onFocus: _this.handleFocus, onMouseEnter: _this.handleHover, onMouseLeave: _this.handleUnhover, onBlur: _this.handleBlur, ref: _this.innerRef, onKeyDown: _this.handleKeyDown, role: "textbox", "aria-disabled": disabled, "aria-describedby": ariaDescribedby, "aria-label": ariaLabel, "aria-labelledby": ariaLabelledby }),
                    React.createElement(InputLayoutContext.Provider, { value: context },
                        React.createElement("input", { type: "hidden", "data-tid": InputLikeTextDataTids.nativeInput, value: value, disabled: disabled }),
                        leftSide,
                        React.createElement("span", { className: wrapperClass },
                            React.createElement("span", { "data-tid": InputLikeTextDataTids.input, className: _this.cx(_this.jsInputStyles.input(_this.theme), (_c = {},
                                    _c[_this.styles.absolute()] = !takeContentWidth,
                                    _c[_this.jsInputStyles.inputFocus(_this.theme)] = focused,
                                    _c[_this.jsInputStyles.inputDisabled(_this.theme)] = disabled,
                                    _c)) }, _this.props.children),
                            _this.renderPlaceholder()),
                        rightSide))));
        };
        _this.renderPlaceholder = function () {
            var _a;
            var _b = _this.props, children = _b.children, placeholder = _b.placeholder, disabled = _b.disabled;
            var focused = _this.state.focused;
            var hasValue = isNonNullable(children) && children !== '';
            if (!hasValue && placeholder) {
                return (React.createElement("span", { className: _this.cx(_this.jsInputStyles.placeholder(_this.theme), (_a = {},
                        _a[_this.jsInputStyles.placeholderDisabled(_this.theme)] = disabled,
                        _a[_this.jsInputStyles.placeholderFocus(_this.theme)] = focused,
                        _a)) }, placeholder));
            }
            return null;
        };
        _this.handleKeyDown = function (e) {
            if (_this.props.disabled) {
                return;
            }
            if (_this.props.onKeyDown) {
                _this.props.onKeyDown(e);
            }
        };
        _this.handleMouseDragStart = function (e) {
            var _a;
            _this.dragging = true;
            (_a = _this.globalObject.document) === null || _a === void 0 ? void 0 : _a.documentElement.classList.add(_this.styles.userSelectNone());
            if (_this.props.onMouseDragStart) {
                _this.props.onMouseDragStart(e);
            }
        };
        _this.handleMouseDragEnd = function (e) {
            var _a;
            // Дожидаемся onMouseUp
            setTimeout(function () {
                _this.dragging = false;
                if (_this.props.onMouseDragEnd) {
                    _this.props.onMouseDragEnd(e);
                }
            }, 0);
            (_a = _this.globalObject.document) === null || _a === void 0 ? void 0 : _a.documentElement.classList.remove(_this.styles.userSelectNone());
        };
        _this.handleFocus = function (e) {
            var _a;
            if (isMobile) {
                (_a = _this.node) === null || _a === void 0 ? void 0 : _a.setAttribute('contenteditable', 'true');
            }
            if (_this.props.disabled) {
                return;
            }
            // Auto-batching React@18 creates problems that are fixed with flushSync
            // https://github.com/skbkontur/retail-ui/pull/3144#issuecomment-1535235366
            if (Number(React.version) >= 18) {
                ReactDOM.flushSync(function () { return _this.setState({ focused: true }); });
            }
            else {
                _this.setState({ focused: true });
            }
            if (_this.props.onFocus) {
                _this.props.onFocus(e);
            }
        };
        _this.resetFocus = function () {
            var _a;
            _this.selectNodeContentsDebounced.cancel();
            if (isMobile) {
                (_a = _this.node) === null || _a === void 0 ? void 0 : _a.removeAttribute('contenteditable');
            }
            removeAllSelections(_this.globalObject);
            _this.setState({ focused: false });
        };
        _this.handleBlur = function (e) {
            var _a, _b, _c;
            _this.selectNodeContentsDebounced.cancel();
            if (isMobile) {
                (_a = _this.node) === null || _a === void 0 ? void 0 : _a.removeAttribute('contenteditable');
            }
            if (_this.props.disabled) {
                e.stopPropagation();
                return;
            }
            removeAllSelections(_this.globalObject);
            _this.setState({ focused: false });
            (_c = (_b = _this.props).onBlur) === null || _c === void 0 ? void 0 : _c.call(_b, e);
        };
        _this.handleHover = function () {
            _this.setState({ clearCrossShowed: _this.getClearCrossShowed({ focused: _this.state.focused, hovered: true }) });
        };
        _this.handleUnhover = function () {
            _this.setState({ clearCrossShowed: _this.getClearCrossShowed({ focused: _this.state.focused, hovered: false }) });
        };
        _this.innerRef = function (el) {
            if (_this.props.innerRef) {
                _this.props.innerRef(el);
            }
            _this.node = el;
        };
        _this.getSizeClassName = function () {
            var _a, _b, _c;
            switch (_this.size) {
                case 'large':
                    return _this.cx((_a = {},
                        _a[_this.jsInputStyles.sizeLarge(_this.theme)] = true,
                        _a));
                case 'medium':
                    return _this.cx((_b = {},
                        _b[_this.jsInputStyles.sizeMedium(_this.theme)] = true,
                        _b));
                case 'small':
                default:
                    return _this.cx((_c = {},
                        _c[_this.jsInputStyles.sizeSmall(_this.theme)] = true,
                        _c));
            }
        };
        return _this;
    }
    InputLikeText_1 = InputLikeText;
    /**
     * @public
     */
    InputLikeText.prototype.focus = function () {
        if (this.node) {
            this.node.focus();
        }
    };
    /**
     * @public
     */
    InputLikeText.prototype.blur = function () {
        if (this.node) {
            this.node.blur();
        }
    };
    /**
     * @public
     */
    InputLikeText.prototype.blink = function () {
        if (this.props.disabled) {
            return;
        }
        blink({
            el: this.node,
            blinkColor: this.theme.inputBlinkColor,
        });
    };
    InputLikeText.prototype.getNode = function () {
        return this.node;
    };
    InputLikeText.prototype.componentDidMount = function () {
        if (this.node) {
            MouseDrag.listen(this.node).onMouseDragStart(this.handleMouseDragStart).onMouseDragEnd(this.handleMouseDragEnd);
        }
    };
    InputLikeText.prototype.componentWillUnmount = function () {
        MouseDrag.stop(this.node);
    };
    InputLikeText.prototype.render = function () {
        var _this = this;
        this.jsInputStyles = getJsInputStyles(this.emotion);
        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));
        }));
    };
    var InputLikeText_1;
    InputLikeText.__KONTUR_REACT_UI__ = 'InputLikeText';
    InputLikeText.displayName = 'InputLikeText';
    InputLikeText.defaultProps = {
        showClearIcon: 'never',
    };
    InputLikeText = InputLikeText_1 = __decorate([
        withRenderEnvironment,
        withSize,
        rootNode
    ], InputLikeText);
    return InputLikeText;
}(React.Component));
export { InputLikeText };
//# sourceMappingURL=InputLikeText.js.map