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 __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
    return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (g && (g = 0, op[0] && (_ = 0)), _) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
    if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
        if (ar || !(i in from)) {
            if (!ar) ar = Array.prototype.slice.call(from, 0, i);
            ar[i] = from[i];
        }
    }
    return to.concat(ar || Array.prototype.slice.call(from));
};
import React from 'react';
import lodashIsEqual from 'lodash.isequal';
import logWarning from 'warning';
import { PopupIds } from '../../internal/Popup/index.js';
import { isKeyArrowHorizontal, isKeyArrowLeft, isKeyArrowRight, isKeyArrowUp, isKeyArrowVertical, isKeyBackspace, isKeyComma, isKeyDelete, isKeyEnter, isKeyEscape, isShortcutSelectAll, } from '../../lib/events/keyboard/identifiers.js';
import * as LayoutEvents from '../../lib/LayoutEvents.js';
import { Token } from '../Token/index.js';
import { MenuItem } from '../MenuItem/index.js';
import { isFunction, emptyHandler, getRandomID } from '../../lib/utils.js';
import { ThemeContext } from '../../lib/theming/ThemeContext.js';
import { locale } from '../../lib/locale/decorators.js';
import { CommonWrapper } from '../../internal/CommonWrapper/index.js';
import { getRootNode, rootNode } from '../../lib/rootNode/index.js';
import { createPropsGetter } from '../../lib/createPropsGetter.js';
import { getUid } from '../../lib/uidUtils.js';
import { TokenView } from '../Token/TokenView.js';
import { withSize } from '../../lib/size/SizeDecorator.js';
import { withRenderEnvironment } from '../../lib/renderEnvironment/index.js';
import { blink } from '../../lib/blink.js';
import { ScrollContainer } from '../ScrollContainer/index.js';
import { TokenInputLocaleHelper } from './locale/index.js';
import { getStyles } from './TokenInput.styles.js';
import { tokenInputReducer } from './TokenInputReducer.js';
import { TokenInputMenu } from './TokenInputMenu.js';
import { TextWidthHelper } from './TextWidthHelper.js';
var TEMP_FAKE_FLAG = 'TEMP_FAKE_FLAG';
export var TokenInputType;
(function (TokenInputType) {
    TokenInputType[TokenInputType["WithReference"] = 0] = "WithReference";
    TokenInputType[TokenInputType["WithoutReference"] = 1] = "WithoutReference";
    TokenInputType[TokenInputType["Combined"] = 2] = "Combined";
})(TokenInputType || (TokenInputType = {}));
export var DefaultState = {
    inputValue: '',
    reservedInputValue: undefined,
    autocompleteItems: undefined,
    activeTokens: [],
    editingTokenIndex: -1,
    inFocus: false,
    loading: false,
    preventBlur: false,
    inputValueWidth: 2,
    inputValueHeight: 22,
};
export var TokenInputDataTids = {
    root: 'TokenInput__root',
    tokenInputMenu: 'TokenInputMenu__root',
    label: 'TokenInput__label',
};
// eslint-disable-next-line @typescript-eslint/no-unnecessary-type-constraint
var identity = function (item) { return item; };
var defaultRenderToken = function (item, _a) {
    var isActive = _a.isActive, onClick = _a.onClick, onDoubleClick = _a.onDoubleClick, onRemove = _a.onRemove, disabled = _a.disabled, size = _a.size;
    return (React.createElement(Token, { key: item.toString(), isActive: isActive, onClick: onClick, onDoubleClick: onDoubleClick, onRemove: onRemove, disabled: disabled, size: size }, item.toString()));
};
/** Поле с токенами — это поле ввода со списком подсказок. Значения в поле отображаются в виде отдельных токенов — компонент [Token](https://tech.skbkontur.ru/kontur-ui/?path=/docs/react-ui_input-data-tokeninput-token--docs).
 */
var TokenInput = /** @class */ (function (_super) {
    __extends(TokenInput, _super);
    function TokenInput() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.state = DefaultState;
        _this._textareaId = getUid();
        _this.rootId = PopupIds.root + getRandomID();
        _this.input = null;
        _this.tokensInputMenu = null;
        _this.textHelper = null;
        _this.wrapper = null;
        _this.scrollContainerRef = React.createRef();
        _this.memoizedTokens = new Map();
        _this.isEqual = function (itemA, itemB) {
            var itemToId = _this.getProps().itemToId;
            return lodashIsEqual(itemToId(itemA), itemToId(itemB));
        };
        _this.hasValueInItems = function (items, value) {
            var valueToString = _this.getProps().valueToString;
            if (typeof value === 'string') {
                return items.map(function (item) { return valueToString(item); }).includes(value);
            }
            return items.some(function (item) { return _this.isEqual(item, value); });
        };
        _this.inputRef = function (node) {
            _this.input = node;
        };
        _this.tokensInputMenuRef = function (node) {
            _this.tokensInputMenu = node;
        };
        _this.textHelperRef = function (node) {
            _this.textHelper = node;
        };
        _this.wrapperRef = function (node) {
            _this.wrapper = node;
        };
        _this.dispatch = function (action, cb) {
            _this.setState(function (prevState) { return tokenInputReducer(prevState, action); }, cb);
        };
        _this.handleInputFocus = function (event) {
            _this.dispatch({ type: 'SET_FOCUS_IN' });
            _this.getProps().onFocus(event);
        };
        _this.handleInputBlur = function (event) {
            var _a, _b, _c;
            var isBlurToMenu = _this.isBlurToMenu(event);
            if (!isBlurToMenu) {
                _this.handleOutsideBlur();
            }
            if (isBlurToMenu || _this.state.preventBlur) {
                event.preventDefault();
                // первый focus нужен для предотвращения/уменьшения моргания в других браузерах
                (_a = _this.input) === null || _a === void 0 ? void 0 : _a.focus({ preventScroll: true });
                // в firefox не работает без второго focus
                (_c = (_b = _this.globalObject).requestAnimationFrame) === null || _c === void 0 ? void 0 : _c.call(_b, function () { var _a; return (_a = _this.input) === null || _a === void 0 ? void 0 : _a.focus({ preventScroll: true }); });
                _this.dispatch({ type: 'SET_PREVENT_BLUR', payload: false });
            }
            else {
                _this.dispatch({ type: 'BLUR' });
                _this.getProps().onBlur(event);
            }
        };
        _this.handleOutsideBlur = function () {
            var _a = _this.state, inputValue = _a.inputValue, allItems = _a.autocompleteItems;
            var autocompleteItems = allItems === null || allItems === void 0 ? void 0 : allItems.filter(isSimpleItem);
            if (inputValue === '') {
                // если стерли содержимое токена в режиме редактирования, то удаляем токен
                if (_this.isEditingMode) {
                    _this.finishTokenEdit();
                }
                return;
            }
            // если не изменилось значение токена при редактировании
            if (_this.isEditingMode && !_this.isTokenValueChanged) {
                _this.finishTokenEdit();
                return;
            }
            // чекаем автокомплит на совпадение с введенным значением в инпут
            if (autocompleteItems && autocompleteItems.length === 1) {
                var item = autocompleteItems[0];
                if (_this.getProps().valueToString(item) === inputValue) {
                    _this.isEditingMode ? _this.finishTokenEdit() : _this.selectItem(item);
                    return;
                }
            }
            if (_this.isInputChanged) {
                _this.checkForUnexpectedInput();
            }
        };
        _this.isBlurToMenu = function (event) {
            var _a;
            if (_this.menuRef && _this.globalObject.document) {
                var menu = getRootNode((_a = _this.tokensInputMenu) === null || _a === void 0 ? void 0 : _a.getMenuRef());
                var relatedTarget = event.relatedTarget || _this.globalObject.document.activeElement;
                if (menu && menu.contains(relatedTarget)) {
                    return true;
                }
            }
            return false;
        };
        _this.handleWrapperMouseDown = function (event) {
            var _a;
            _this.dispatch({ type: 'SET_PREVENT_BLUR', payload: true });
            var target = event.target;
            var isClickOnToken = target && ((_a = _this.wrapper) === null || _a === void 0 ? void 0 : _a.contains(target)) && target !== _this.wrapper && target !== _this.input;
            if (!isClickOnToken) {
                _this.dispatch({ type: 'REMOVE_ALL_ACTIVE_TOKENS' });
            }
        };
        _this.handleWrapperMouseUp = function (e) {
            var _a;
            // Имитируем поведение label, когда задан maxHeight.
            if (_this.props.maxHeight &&
                e.target === _this.scrollContainerRef.current &&
                (_this.state.activeTokens.length !== 0 || !_this.state.inFocus)) {
                _this.dispatch({ type: 'BLUR' });
                _this.dispatch({ type: 'SET_FOCUS_IN' });
                _this.focusInput();
                (_a = _this.input) === null || _a === void 0 ? void 0 : _a.scrollIntoView({ behavior: 'auto', block: 'center' });
            }
            _this.dispatch({ type: 'SET_PREVENT_BLUR', payload: false });
        };
        _this.handleCopy = function (event) {
            if (!_this.state.inFocus || _this.state.activeTokens.length === 0 || _this.isCursorVisible) {
                return;
            }
            event.preventDefault();
            var _a = _this.getProps(), selectedItems = _a.selectedItems, valueToString = _a.valueToString, delimiters = _a.delimiters;
            // упорядочивание токенов по индексу
            var tokens = _this.state.activeTokens
                .map(function (token) { return selectedItems.indexOf(token); })
                .sort()
                .map(function (index) { return selectedItems[index]; })
                .map(function (item) { return valueToString(item); });
            event.clipboardData.setData('text/plain', tokens.join(delimiters[0]));
        };
        _this.handleInputPaste = function (event) {
            if (_this.type === TokenInputType.WithReference || !event.clipboardData) {
                return;
            }
            var paste = event.clipboardData.getData('text');
            var _a = _this.getProps(), delimiters = _a.delimiters, selectedItems = _a.selectedItems, valueToItem = _a.valueToItem, onValueChange = _a.onValueChange;
            if (delimiters.some(function (delimiter) { return paste.includes(delimiter); })) {
                event.preventDefault();
                event.stopPropagation();
                var tokens = paste.trim().split(new RegExp("[".concat(delimiters.join(''), "]+")));
                var items = tokens
                    .filter(Boolean)
                    .map(function (token) { return valueToItem(token); })
                    .filter(function (item) { return item && !_this.hasValueInItems(selectedItems, item); });
                var newItems = selectedItems.concat(items);
                onValueChange(newItems);
                _this.dispatch({ type: 'SET_AUTOCOMPLETE_ITEMS', payload: undefined });
                _this.tryGetItems();
            }
        };
        _this.tryGetItems = function () {
            var args_1 = [];
            for (var _i = 0; _i < arguments.length; _i++) {
                args_1[_i] = arguments[_i];
            }
            return __awaiter(_this, __spreadArray([], args_1, true), void 0, function (query) {
                var autocompleteItems, _a, selectedItems_1, valueToItem, valueToString_1, isSelectedItem_1, isEditingItem_1, autocompleteItemsUnique, autocompleteItemsUniqueSimple, editingItem, selectItemIndex_1;
                var _this = this;
                if (query === void 0) { query = ''; }
                return __generator(this, function (_b) {
                    switch (_b.label) {
                        case 0:
                            if (!(this.props.getItems && (this.isInputValueChanged || !this.props.hideMenuIfEmptyInputValue))) return [3 /*break*/, 2];
                            this.dispatch({ type: 'SET_LOADING', payload: true });
                            return [4 /*yield*/, this.props.getItems(query)];
                        case 1:
                            autocompleteItems = _b.sent();
                            this.dispatch({ type: 'SET_LOADING', payload: false });
                            _a = this.getProps(), selectedItems_1 = _a.selectedItems, valueToItem = _a.valueToItem, valueToString_1 = _a.valueToString;
                            isSelectedItem_1 = function (item) { return _this.hasValueInItems(selectedItems_1, item); };
                            isEditingItem_1 = function (item) {
                                var editingItem = selectedItems_1[_this.state.editingTokenIndex];
                                return !!editingItem && _this.isEqual(item, editingItem);
                            };
                            autocompleteItemsUnique = autocompleteItems.filter(function (item) {
                                return isSimpleItem(item) ? !isSelectedItem_1(item) || isEditingItem_1(item) : true;
                            });
                            autocompleteItemsUniqueSimple = autocompleteItemsUnique.filter(isSimpleItem);
                            if (this.isEditingMode) {
                                editingItem = selectedItems_1[this.state.editingTokenIndex];
                                if (this.isEqual(editingItem, valueToItem(this.state.inputValue)) &&
                                    !this.hasValueInItems(autocompleteItemsUniqueSimple, editingItem)) {
                                    autocompleteItemsUnique.unshift(editingItem);
                                }
                            }
                            if (query === '' || this.isInputValueChanged) {
                                this.dispatch({ type: 'SET_AUTOCOMPLETE_ITEMS', payload: autocompleteItemsUnique }, function () {
                                    LayoutEvents.emit();
                                    _this.highlightMenuItem();
                                });
                            }
                            selectItemIndex_1 = autocompleteItemsUniqueSimple.findIndex(function (item) { return valueToString_1(item).toLowerCase() === _this.state.inputValue.toLowerCase(); });
                            setTimeout(function () { var _a; return (_a = _this.menuRef) === null || _a === void 0 ? void 0 : _a.highlightItem(selectItemIndex_1 < 0 ? 0 : selectItemIndex_1); }, 0);
                            _b.label = 2;
                        case 2: return [2 /*return*/];
                    }
                });
            });
        };
        _this.handleKeyDown = function (event) {
            var _a, _b;
            (_b = (_a = _this.props).onKeyDown) === null || _b === void 0 ? void 0 : _b.call(_a, event);
            if (event.defaultPrevented) {
                return;
            }
            if (_this.isCursorVisible) {
                _this.handleInputKeyDown(event);
            }
            else {
                _this.handleWrapperKeyDown(event);
            }
        };
        _this.handleInputKeyDown = function (e) {
            var _a, _b, _c, _d;
            e.stopPropagation();
            if ((_this.type !== TokenInputType.WithReference &&
                _this.getProps().delimiters.some(function (key) { return key === e.key || (key === ',' && isKeyComma(e)); })) ||
                (isKeyEnter(e) && _this.type === TokenInputType.WithoutReference)) {
                e.preventDefault();
                var newValue = _this.state.inputValue;
                if (newValue !== '') {
                    if (_this.isEditingMode) {
                        _this.finishTokenEdit();
                    }
                    else {
                        _this.handleAddItem();
                    }
                }
            }
            var isRightmostTokenNotDisabled = !_this.isTokenDisabled(_this.getProps().selectedItems.length - 1);
            var canSetValueToInput = _this.showAddItemHint || ((_b = (_a = _this.state.autocompleteItems) === null || _a === void 0 ? void 0 : _a.length) !== null && _b !== void 0 ? _b : 0) > 0;
            switch (true) {
                case isKeyEnter(e):
                    if (canSetValueToInput && _this.menuRef) {
                        _this.menuRef.enter(e);
                    }
                    // don't allow textarea
                    // became multiline
                    e.preventDefault();
                    break;
                case isKeyArrowVertical(e):
                    e.preventDefault();
                    if (_this.menuRef) {
                        if (isKeyArrowUp(e)) {
                            _this.menuRef.up();
                        }
                        else {
                            _this.menuRef.down();
                        }
                    }
                    break;
                case isKeyEscape(e):
                    (_c = _this.input) === null || _c === void 0 ? void 0 : _c.blur();
                    break;
                case isKeyBackspace(e):
                    if (!_this.isEditingMode && isRightmostTokenNotDisabled) {
                        _this.moveFocusToLastToken();
                    }
                    break;
                case isKeyArrowLeft(e):
                    if (((_d = _this.input) === null || _d === void 0 ? void 0 : _d.selectionStart) === 0) {
                        var index = _this.getAvailableTokenIndex(_this.getProps().selectedItems.length);
                        var itemNew = _this.getProps().selectedItems[index];
                        if (itemNew) {
                            _this.dispatch({ type: 'SET_ACTIVE_TOKENS', payload: [itemNew] });
                        }
                    }
                    break;
            }
        };
        _this.focusInput = function (options) {
            var _a, _b;
            (_b = (_a = _this.globalObject).requestAnimationFrame) === null || _b === void 0 ? void 0 : _b.call(_a, function () { var _a; return (_a = _this.input) === null || _a === void 0 ? void 0 : _a.focus(options); });
        };
        _this.selectInputText = function () {
            if (_this.input) {
                _this.input.setSelectionRange(0, _this.state.inputValue.length);
            }
        };
        _this.handleWrapperKeyDown = function (e) {
            var _a;
            var _b = _this.getProps(), selectedItems = _b.selectedItems, onValueChange = _b.onValueChange;
            switch (true) {
                case isKeyBackspace(e):
                case isKeyDelete(e): {
                    var indexOfActiveToken = _this.getProps().selectedItems.indexOf(_this.state.activeTokens[_this.state.activeTokens.length - 1]);
                    if (!_this.isEditingMode && !_this.isTokenDisabled(indexOfActiveToken)) {
                        var itemsNew = selectedItems.filter(function (item) { return !_this.hasValueInItems(_this.state.activeTokens, item); });
                        onValueChange(itemsNew);
                        _this.dispatch({ type: 'REMOVE_ALL_ACTIVE_TOKENS' }, function () {
                            var _a;
                            LayoutEvents.emit();
                            (_a = _this.input) === null || _a === void 0 ? void 0 : _a.focus();
                        });
                    }
                    break;
                }
                case isKeyArrowHorizontal(e):
                    _this.handleWrapperArrows(e);
                    break;
                case isKeyEscape(e):
                    (_a = _this.wrapper) === null || _a === void 0 ? void 0 : _a.blur();
                    break;
                case isKeyEnter(e):
                    e.preventDefault();
                    if (_this.state.activeTokens.length === 1) {
                        _this.handleTokenEdit(_this.state.activeTokens[0]);
                    }
                    break;
                case isShortcutSelectAll(e):
                    e.preventDefault();
                    _this.dispatch({
                        type: 'SET_ACTIVE_TOKENS',
                        payload: selectedItems.filter(function (item) { return !_this.isTokenDisabled(selectedItems.indexOf(item)); }),
                    });
                    break;
            }
        };
        _this.handleWrapperArrows = function (e) {
            e.preventDefault();
            var selectedItems = _this.getProps().selectedItems;
            var activeTokens = _this.state.activeTokens;
            var activeItemIndex = selectedItems.indexOf(activeTokens[0]);
            var newItemIndex = _this.getAvailableTokenIndex(activeItemIndex, isKeyArrowLeft(e));
            var isLeftEdge = activeItemIndex === 0 && isKeyArrowLeft(e);
            var isRightEdge = newItemIndex === selectedItems.length && isKeyArrowRight(e);
            if (!e.shiftKey && activeTokens.length === 1) {
                _this.handleWrapperArrowsWithoutShift(isLeftEdge, isRightEdge, newItemIndex);
            }
            else {
                _this.handleWrapperArrowsWithShift(isLeftEdge, isRightEdge, newItemIndex);
            }
        };
        _this.handleWrapperArrowsWithoutShift = function (isLeftEdge, isRightEdge, newItemIndex) {
            if (isRightEdge) {
                _this.dispatch({ type: 'REMOVE_ALL_ACTIVE_TOKENS' }, function () { var _a; return (_a = _this.input) === null || _a === void 0 ? void 0 : _a.focus(); });
            }
            else if (!isLeftEdge) {
                _this.dispatch({
                    type: 'SET_ACTIVE_TOKENS',
                    payload: [_this.getProps().selectedItems[newItemIndex]],
                });
            }
        };
        _this.handleWrapperArrowsWithShift = function (isLeftEdge, isRightEdge, newItemIndex) {
            if (!isLeftEdge && !isRightEdge) {
                var itemNew_1 = _this.getProps().selectedItems[newItemIndex];
                var itemsNew = __spreadArray([itemNew_1], _this.state.activeTokens.filter(function (item) { return !_this.isEqual(item, itemNew_1); }), true);
                _this.dispatch({ type: 'SET_ACTIVE_TOKENS', payload: itemsNew });
            }
        };
        _this.handleValueChange = function (items) {
            _this.getProps().onValueChange(items);
        };
        _this.handleAddItem = function () {
            var item = _this.getProps().valueToItem(_this.state.inputValue);
            if (item) {
                _this.selectItem(item);
            }
        };
        _this.selectItem = function (item) {
            var _a = _this.getProps(), allItems = _a.selectedItems, valueToString = _a.valueToString;
            var selectedItems = allItems.filter(isSimpleItem);
            if (_this.isEditingMode) {
                _this.dispatch({ type: 'UPDATE_QUERY', payload: valueToString(item) }, _this.finishTokenEdit);
            }
            else if (!_this.hasValueInItems(selectedItems, item)) {
                _this.handleValueChange(selectedItems.concat([item]));
                _this.dispatch({ type: 'CLEAR_INPUT' });
                _this.tryGetItems();
            }
        };
        _this.handleRemoveToken = function (item) {
            var _a, _b;
            (_b = (_a = _this.props).onValueChange) === null || _b === void 0 ? void 0 : _b.call(_a, _this.getProps().selectedItems.filter(function (_) { return !_this.isEqual(_, item); }));
            var filteredActiveTokens = _this.state.activeTokens.filter(function (_) { return !_this.isEqual(_, item); });
            _this.dispatch({ type: 'SET_ACTIVE_TOKENS', payload: filteredActiveTokens });
            if (filteredActiveTokens.length === 0) {
                _this.focusInput({ preventScroll: true });
            }
            _this.tryGetItems();
        };
        _this.handleTokenClick = function (event, itemNew) {
            var items = _this.state.activeTokens;
            if (event.ctrlKey) {
                var newItems = _this.hasValueInItems(_this.state.activeTokens, itemNew)
                    ? items.filter(function (item) { return !_this.isEqual(item, itemNew); })
                    : __spreadArray(__spreadArray([], items, true), [itemNew], false);
                _this.dispatch({ type: 'SET_ACTIVE_TOKENS', payload: newItems });
            }
            else {
                _this.dispatch({ type: 'SET_ACTIVE_TOKENS', payload: [itemNew] });
            }
            _this.focusInput({ preventScroll: true });
        };
        _this.handleTokenEdit = function (itemNew) {
            var _a = _this.getProps(), selectedItems = _a.selectedItems, valueToString = _a.valueToString;
            var editingTokenIndex = selectedItems.findIndex(function (item) { return item === itemNew; });
            _this.dispatch({ type: 'SET_EDITING_TOKEN_INDEX', payload: editingTokenIndex });
            if (_this.isInputValueChanged) {
                if (_this.state.reservedInputValue === undefined) {
                    _this.dispatch({ type: 'SET_TEMPORARY_QUERY', payload: _this.state.inputValue });
                }
            }
            _this.dispatch({ type: 'UPDATE_QUERY', payload: valueToString(itemNew) }, _this.selectInputText);
            _this.dispatch({ type: 'REMOVE_ALL_ACTIVE_TOKENS' });
            _this.tryGetItems();
        };
        _this.finishTokenEdit = function () {
            var _a;
            var _b = _this.getProps(), selectedItems = _b.selectedItems, valueToString = _b.valueToString;
            var _c = _this.state, editingTokenIndex = _c.editingTokenIndex, inputValue = _c.inputValue, reservedInputValue = _c.reservedInputValue, autocompleteItems = _c.autocompleteItems;
            var editedItem = (_a = autocompleteItems === null || autocompleteItems === void 0 ? void 0 : autocompleteItems.find(function (item) { return valueToString(item) === inputValue; })) !== null && _a !== void 0 ? _a : _this.getProps().valueToItem(inputValue);
            var newItems = selectedItems.concat([]);
            if (!_this.hasValueInItems(selectedItems, editedItem)) {
                newItems.splice.apply(newItems, __spreadArray([editingTokenIndex, 1], (_this.isInputValueChanged ? [editedItem] : []), false));
                _this.handleValueChange(newItems);
            }
            _this.dispatch({ type: 'REMOVE_EDITING_TOKEN_INDEX' });
            if (reservedInputValue) {
                _this.dispatch({ type: 'UPDATE_QUERY', payload: reservedInputValue });
                _this.dispatch({ type: 'REMOVE_TEMPORARY_QUERY' });
            }
            else {
                _this.dispatch({ type: 'CLEAR_INPUT' });
            }
            if (newItems.length === selectedItems.length) {
                _this.dispatch({ type: 'SET_ACTIVE_TOKENS', payload: [newItems[editingTokenIndex]] });
            }
        };
        _this.checkForUnexpectedInput = function () {
            var inputValue = _this.state.inputValue;
            var onUnexpectedInput = _this.props.onUnexpectedInput;
            // чекаем не возвращает ли что-нибудь обработчик
            var returnedValue = onUnexpectedInput === null || onUnexpectedInput === void 0 ? void 0 : onUnexpectedInput(inputValue);
            if (returnedValue === undefined) {
                if (_this.type === TokenInputType.WithoutReference) {
                    _this.handleAddItem();
                }
                return;
            }
            if (returnedValue === null) {
                _this.dispatch({ type: 'CLEAR_INPUT' }, function () {
                    if (_this.isEditingMode) {
                        _this.finishTokenEdit();
                    }
                });
                return;
            }
            if (returnedValue) {
                _this.selectItem(returnedValue);
            }
        };
        _this.handleChangeInputValue = function (event) {
            _this.dispatch({ type: 'REMOVE_ALL_ACTIVE_TOKENS' });
            var query = event.target.value.trimLeft();
            if (query.endsWith(' ')) {
                query = query.trimRight() + ' ';
            }
            if (_this.isInputValueChanged && query === '') {
                _this.dispatch({ type: 'SET_AUTOCOMPLETE_ITEMS', payload: undefined });
            }
            _this.dispatch({ type: 'UPDATE_QUERY', payload: query }, function () {
                _this.tryGetItems(query);
            });
            if (_this.props.onInputValueChange) {
                _this.props.onInputValueChange(query);
            }
        };
        _this.highlightMenuItem = function () {
            if (_this.menuRef &&
                _this.state.autocompleteItems &&
                _this.state.autocompleteItems.length > 0 &&
                _this.type !== TokenInputType.Combined) {
                _this.menuRef.highlightItem(0);
            }
        };
        _this.renderTokensStart = function () {
            var editingTokenIndex = _this.state.editingTokenIndex;
            var selectedItems = _this.getProps().selectedItems;
            var delimiter = editingTokenIndex >= 0 ? editingTokenIndex : selectedItems.length;
            return selectedItems.slice(0, delimiter).map(_this.renderToken);
        };
        _this.renderTokensEnd = function () {
            if (_this.state.editingTokenIndex >= 0) {
                return _this.getProps()
                    .selectedItems.slice(_this.state.editingTokenIndex + 1)
                    .map(_this.renderToken);
            }
        };
        _this.renderToken = function (item, index) {
            var _a;
            var _b = _this.props, _c = _b.renderToken, renderToken = _c === void 0 ? defaultRenderToken : _c, disabled = _b.disabled;
            var isActive = _this.state.activeTokens.includes(item);
            // TODO useCallback
            var handleIconClick = function (event) {
                event.stopPropagation();
                if (!_this.isEditingMode) {
                    _this.handleRemoveToken(item);
                }
            };
            // TODO useCallback
            var handleTokenClick = function (event) {
                event.stopPropagation();
                if (!_this.isEditingMode) {
                    _this.handleTokenClick(event, item);
                }
            };
            var handleTokenDoubleClick = function (event) {
                event.stopPropagation();
                if (!_this.isEditingMode && !disabled) {
                    _this.handleTokenEdit(item);
                }
            };
            var renderedToken = renderToken(item, {
                size: _this.size,
                isActive: isActive,
                onClick: handleTokenClick,
                onDoubleClick: handleTokenDoubleClick,
                onRemove: handleIconClick,
                disabled: disabled,
            }, index);
            _this.memoizedTokens.set((_a = _this.props.selectedItems) === null || _a === void 0 ? void 0 : _a.indexOf(item), renderedToken);
            return renderedToken;
        };
        _this.renderAddButton = function (value) {
            if (value === void 0) { value = _this.state.inputValue; }
            if (!_this.showAddItemHint) {
                return;
            }
            if (_this.props.renderAddButton) {
                return _this.props.renderAddButton(value, _this.handleAddItem);
            }
            var _a = _this.locale, addButtonComment = _a.addButtonComment, addButtonTitle = _a.addButtonTitle;
            return (React.createElement(MenuItem, { onClick: _this.handleAddItem, comment: addButtonComment, key: "renderAddButton" },
                addButtonTitle,
                " ",
                value));
        };
        _this.isTokenDisabled = function (itemIndex) {
            var renderedToken;
            if (_this.memoizedTokens.has(itemIndex)) {
                renderedToken = _this.memoizedTokens.get(itemIndex);
            }
            else if (itemIndex < 0 || itemIndex > _this.getProps().selectedItems.length - 1) {
                return false;
            }
            else {
                renderedToken = _this.renderToken(_this.getProps().selectedItems[itemIndex], itemIndex);
            }
            return renderedToken.props.disabled;
        };
        _this.getAvailableTokenIndex = function (startIndex, isDirectionLeft) {
            if (isDirectionLeft === void 0) { isDirectionLeft = true; }
            var selectedItems = _this.getProps().selectedItems;
            var step = isDirectionLeft ? -1 : +1;
            var availableIndex = startIndex + step;
            while (_this.isTokenDisabled(availableIndex)) {
                availableIndex += step;
                if (availableIndex === selectedItems.length) {
                    return availableIndex;
                }
                else if (availableIndex === -1) {
                    return startIndex;
                }
            }
            return availableIndex;
        };
        return _this;
    }
    TokenInput_1 = TokenInput;
    TokenInput.prototype.getDelimiters = function () {
        var _a;
        var delimiters = (_a = this.props.delimiters) !== null && _a !== void 0 ? _a : [];
        if (delimiters.every(function (delimiter) { return delimiter !== TEMP_FAKE_FLAG; })) {
            return delimiters;
        }
        return delimiters.filter(function (delimiter) { return delimiter !== TEMP_FAKE_FLAG; });
    };
    TokenInput.prototype.getProps = function () {
        var propsGetter = createPropsGetter(TokenInput_1.defaultProps);
        var propsWithOldDelimiters = propsGetter.apply(this);
        return __assign(__assign({}, propsWithOldDelimiters), { delimiters: this.getDelimiters() });
    };
    Object.defineProperty(TokenInput.prototype, "textareaId", {
        get: function () {
            var _a;
            return (_a = this.props.id) !== null && _a !== void 0 ? _a : this._textareaId;
        },
        enumerable: false,
        configurable: true
    });
    TokenInput.prototype.componentDidMount = function () {
        var _a;
        this.updateInputTextWidth();
        (_a = this.globalObject.document) === null || _a === void 0 ? void 0 : _a.addEventListener('copy', this.handleCopy);
        if (this.props.autoFocus) {
            this.focusInput();
        }
    };
    TokenInput.prototype.componentDidUpdate = function (prevProps, prevState) {
        if (prevState.inputValue !== this.state.inputValue) {
            this.updateInputTextWidth();
        }
        if (prevState.activeTokens.length === 0 && this.state.activeTokens.length > 0) {
            this.dispatch({
                type: 'SET_AUTOCOMPLETE_ITEMS',
                payload: undefined,
            });
        }
        if (prevProps.selectedItems.length !== this.getProps().selectedItems.length) {
            LayoutEvents.emit();
            this.memoizedTokens.clear();
        }
        if (!this.isCursorVisibleForState(prevState) && this.isCursorVisible) {
            this.tryGetItems(this.isEditingMode ? '' : this.state.inputValue);
        }
    };
    TokenInput.prototype.componentWillUnmount = function () {
        var _a;
        (_a = this.globalObject.document) === null || _a === void 0 ? void 0 : _a.removeEventListener('copy', this.handleCopy);
    };
    /** Программно устанавливает фокус на поле.
     * Появляется фокусная рамка, элемент получает клавиатурные события и воспринимается как текущий элемент для чтения скринридерами.
     * @public
     */
    TokenInput.prototype.focus = function () {
        var _a;
        (_a = this.input) === null || _a === void 0 ? void 0 : _a.focus();
    };
    /** Программно снимает фокус с поля.
     * @public
     */
    TokenInput.prototype.blur = function () {
        var _a;
        (_a = this.input) === null || _a === void 0 ? void 0 : _a.blur();
    };
    /** Кратковременно визуально подсвечивает поле ввода, чтобы привлечь внимание пользователя.
     * @public
     */
    TokenInput.prototype.blink = function () {
        blink({ el: this.wrapper, blinkColor: this.theme.inputBlinkColor });
    };
    TokenInput.prototype.render = function () {
        var _this = this;
        this.styles = getStyles(this.emotion);
        return (React.createElement(ThemeContext.Consumer, null, function (theme) {
            _this.theme = theme;
            return _this.renderMain();
        }));
    };
    TokenInput.prototype.getLabelSizeClassName = function () {
        switch (this.size) {
            case 'large':
                return this.styles.labelLarge(this.theme);
            case 'medium':
                return this.styles.labelMedium(this.theme);
            case 'small':
            default:
                return this.styles.labelSmall(this.theme);
        }
    };
    TokenInput.prototype.getInputSizeClassName = function () {
        switch (this.size) {
            case 'large':
                return this.styles.inputLarge(this.theme);
            case 'medium':
                return this.styles.inputMedium(this.theme);
            case 'small':
            default:
                return this.styles.inputSmall(this.theme);
        }
    };
    TokenInput.prototype.renderMain = function () {
        var _a, _b, _c;
        if (this.type !== TokenInputType.WithoutReference && !this.props.getItems) {
            logWarning(false, "getItems is required for \"Combined\" and \"WithReference\" modes.");
        }
        var _d = this.props, maxMenuHeight = _d.maxMenuHeight, error = _d.error, warning = _d.warning, disabled = _d.disabled, renderNotFound = _d.renderNotFound, hideMenuIfEmptyInputValue = _d.hideMenuIfEmptyInputValue, inputMode = _d.inputMode, renderTotalCount = _d.renderTotalCount, totalCount = _d.totalCount, ariaDescribedby = _d["aria-describedby"], ariaLabel = _d["aria-label"], maxHeight = _d.maxHeight;
        var _e = this.getProps(), selectedItems = _e.selectedItems, width = _e.width, onMouseEnter = _e.onMouseEnter, onMouseLeave = _e.onMouseLeave, menuWidth = _e.menuWidth, menuAlign = _e.menuAlign, renderItem = _e.renderItem;
        var _f = this.state, activeTokens = _f.activeTokens, inFocus = _f.inFocus, inputValueWidth = _f.inputValueWidth, inputValueHeight = _f.inputValueHeight, inputValue = _f.inputValue, reservedInputValue = _f.reservedInputValue, autocompleteItems = _f.autocompleteItems, loading = _f.loading;
        var showMenu = this.type !== TokenInputType.WithoutReference &&
            this.isCursorVisible &&
            activeTokens.length === 0 &&
            (this.isInputValueChanged || !hideMenuIfEmptyInputValue);
        var theme = this.theme;
        var inputInlineStyles = {
            // вычисляем ширину чтобы input автоматически перенёсся на следующую строку при необходимости
            width: inputValueWidth,
            height: inputValueHeight,
            // в ie не работает, но альтернативный способ --- дать tabindex для label --- предположительно ещё сложнее
            caretColor: this.isCursorVisible ? undefined : 'transparent',
        };
        var labelClassName = this.cx(this.styles.label(theme), this.getLabelSizeClassName(), (_a = {},
            _a[this.styles.hovering(this.theme)] = !inFocus && !disabled && !warning && !error,
            _a[this.styles.labelDisabled(theme)] = !!disabled,
            _a[this.styles.labelFocused(theme)] = !!inFocus,
            _a[this.styles.error(theme)] = !!error,
            _a[this.styles.warning(theme)] = !!warning,
            _a));
        var inputClassName = this.cx(this.styles.input(theme), this.getInputSizeClassName(), (_b = {},
            _b[this.styles.inputDisabled(theme)] = !!disabled,
            _b));
        var placeholder = selectedItems.length === 0 && !inputValue ? this.props.placeholder : '';
        var inputNode = (React.createElement(TokenView, { size: this.size, className: this.cx((_c = {},
                // input растягивается на всю ширину чтобы placeholder не обрезался
                _c[this.styles.inputPlaceholderWrapper()] = Boolean(placeholder),
                _c)), hideCloseButton: Boolean(placeholder) },
            React.createElement("textarea", { id: this.textareaId, ref: this.inputRef, value: inputValue, style: inputInlineStyles, spellCheck: false, disabled: disabled, className: inputClassName, placeholder: placeholder, onFocus: this.handleInputFocus, onBlur: this.handleInputBlur, onChange: this.handleChangeInputValue, onKeyDown: this.handleKeyDown, onPaste: this.handleInputPaste, inputMode: inputMode, "aria-label": ariaLabel, "aria-describedby": ariaDescribedby })));
        var inner = (React.createElement(React.Fragment, null,
            React.createElement(TextWidthHelper, { ref: this.textHelperRef, text: inputValue, theme: this.theme, size: this.size }),
            this.renderTokensStart(),
            inputNode,
            showMenu && (React.createElement(TokenInputMenu, { popupMenuId: this.rootId, ref: this.tokensInputMenuRef, items: autocompleteItems, loading: loading, opened: showMenu, maxMenuHeight: maxMenuHeight, anchorElementForCursor: this.input, anchorElementRoot: this.wrapper, renderNotFound: renderNotFound, renderItem: renderItem, onValueChange: this.selectItem, renderAddButton: this.renderAddButton, menuWidth: menuWidth, menuAlign: menuAlign, renderTotalCount: renderTotalCount, totalCount: totalCount, size: this.size })),
            this.renderTokensEnd(),
            this.isEditingMode ? (React.createElement(TokenView, { size: this.size },
                React.createElement("span", { className: this.styles.reservedInput(theme) }, reservedInputValue))) : null));
        var container = maxHeight ? (React.createElement(ScrollContainer, { className: this.styles.inputPlaceholderScrollWrapper(), scrollRef: this.scrollContainerRef, maxHeight: maxHeight, showScrollBar: "always", style: { width: '100%' } }, inner)) : (inner);
        return (React.createElement(CommonWrapper, __assign({ rootNodeRef: this.setRootNode }, this.props),
            React.createElement("div", { "data-tid": TokenInputDataTids.root, onMouseEnter: onMouseEnter, onMouseLeave: onMouseLeave },
                React.createElement("label", { ref: this.wrapperRef, style: { width: width }, className: labelClassName, onMouseDown: this.handleWrapperMouseDown, onMouseUp: this.handleWrapperMouseUp, 
                    // Для корректной работы скролла приходится ломать связь label с полем ввода
                    // Иначе любой клик внутри label вызывает фокус и автоскроллинг к полю ввода
                    htmlFor: maxHeight ? 'fake-id' : this.textareaId, "aria-controls": this.rootId, "data-tid": TokenInputDataTids.label }, container))));
    };
    /**
     * Сбрасывает введённое пользователем значение.
     * @public
     */
    TokenInput.prototype.reset = function () {
        this.dispatch({ type: 'RESET' });
    };
    Object.defineProperty(TokenInput.prototype, "showAddItemHint", {
        get: function () {
            var _a;
            var items = (_a = this.state.autocompleteItems) === null || _a === void 0 ? void 0 : _a.filter(isSimpleItem);
            var value = this.getProps().valueToItem(this.state.inputValue);
            if (items && this.hasValueInItems(items, value)) {
                return false;
            }
            var selectedItems = this.getProps().selectedItems;
            if (selectedItems && this.hasValueInItems(selectedItems, value)) {
                return false;
            }
            if (this.type === TokenInputType.Combined && this.isInputValueChanged) {
                return true;
            }
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(TokenInput.prototype, "type", {
        get: function () {
            return this.props.type ? this.props.type : TokenInputType.WithReference;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(TokenInput.prototype, "menuRef", {
        get: function () {
            return this.tokensInputMenu && this.tokensInputMenu.getMenuRef();
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(TokenInput.prototype, "isCursorVisible", {
        get: function () {
            return this.isCursorVisibleForState(this.state);
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(TokenInput.prototype, "isEditingMode", {
        get: function () {
            return this.state.editingTokenIndex > -1;
        },
        enumerable: false,
        configurable: true
    });
    TokenInput.prototype.isCursorVisibleForState = function (state) {
        return state.inFocus && (this.isInputValueChanged || state.activeTokens.length === 0);
    };
    TokenInput.prototype.updateInputTextWidth = function () {
        if (this.textHelper) {
            // в IE текст иногда не помещается в input
            // из-за округления, поэтому округляем явно
            var inputValueWidth = parseFloat(this.textHelper.getTextWidth().toFixed(2));
            var inputValueHeight = parseFloat(this.textHelper.getTextHeight().toFixed(2));
            this.dispatch({ type: 'SET_INPUT_VALUE_WIDTH', payload: inputValueWidth }, LayoutEvents.emit);
            this.dispatch({ type: 'SET_INPUT_VALUE_HEIGHT', payload: inputValueHeight }, LayoutEvents.emit);
        }
    };
    Object.defineProperty(TokenInput.prototype, "isInputChanged", {
        get: function () {
            if (this.isEditingMode) {
                return this.isTokenValueChanged;
            }
            return this.isInputValueChanged;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(TokenInput.prototype, "isInputValueChanged", {
        get: function () {
            var inputValue = this.state.inputValue;
            return inputValue !== '';
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(TokenInput.prototype, "isTokenValueChanged", {
        get: function () {
            var _a = this.state, inputValue = _a.inputValue, editingTokenIndex = _a.editingTokenIndex;
            var _b = this.getProps(), valueToString = _b.valueToString, selectedItems = _b.selectedItems;
            if (this.isEditingMode) {
                return valueToString(selectedItems[editingTokenIndex]) !== inputValue;
            }
            return false;
        },
        enumerable: false,
        configurable: true
    });
    TokenInput.prototype.moveFocusToLastToken = function () {
        var items = this.getProps().selectedItems;
        if (this.state.inputValue === '' && items && items.length > 0) {
            this.dispatch({ type: 'SET_ACTIVE_TOKENS', payload: items.slice(-1) });
        }
    };
    var TokenInput_1;
    TokenInput.__KONTUR_REACT_UI__ = 'TokenInput';
    TokenInput.displayName = 'TokenInput';
    TokenInput.defaultProps = {
        selectedItems: [],
        // TEMP_FAKE_FLAG помогает узнать, остались ли разделители дефолтными или пользователь передал их равными дефолтным.
        delimiters: [',', TEMP_FAKE_FLAG],
        renderItem: identity,
        renderValue: identity,
        valueToString: identity,
        valueToItem: function (item) { return item; },
        itemToId: identity,
        onValueChange: function () { return void 0; },
        width: 250,
        onBlur: emptyHandler,
        onFocus: emptyHandler,
        onMouseEnter: emptyHandler,
        onMouseLeave: emptyHandler,
        menuWidth: 'auto',
        menuAlign: 'cursor',
    };
    TokenInput = TokenInput_1 = __decorate([
        withRenderEnvironment,
        rootNode,
        locale('TokenInput', TokenInputLocaleHelper),
        withSize
    ], TokenInput);
    return TokenInput;
}(React.PureComponent));
export { TokenInput };
function isSimpleItem(item) {
    return !isFunction(item) && !React.isValidElement(item);
}
//# sourceMappingURL=TokenInput.js.map