"use strict";var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard").default;exports.__esModule = true;exports.TokenInputType = exports.TokenInputDataTids = exports.TokenInput = exports.DefaultState = void 0;var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator"));var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator"));var _createClass2 = _interopRequireDefault(require("@babel/runtime/helpers/createClass"));var _inheritsLoose2 = _interopRequireDefault(require("@babel/runtime/helpers/inheritsLoose"));










var _react = _interopRequireDefault(require("react"));
var _lodash = _interopRequireDefault(require("lodash.isequal"));
var _globalObject = require("@skbkontur/global-object");

var _Popup = require("../../internal/Popup");
var _identifiers = require("../../lib/events/keyboard/identifiers");












var LayoutEvents = _interopRequireWildcard(require("../../lib/LayoutEvents"));


var _Token = require("../Token");

var _MenuItem = require("../MenuItem");

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

var _decorators = require("../../lib/locale/decorators");

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

var _rootNode = require("../../lib/rootNode");
var _createPropsGetter = require("../../lib/createPropsGetter");
var _uidUtils = require("../../lib/uidUtils");
var _TokenView = require("../Token/TokenView");

var _featureFlagsContext = require("../../lib/featureFlagsContext");
var _SizeDecorator = require("../../lib/size/SizeDecorator");

var _blink2 = require("../../lib/blink");
var _ScrollContainer = require("../ScrollContainer");


var _locale = require("./locale");
var _TokenInput2 = require("./TokenInput.styles");

var _TokenInputReducer = require("./TokenInputReducer");
var _TokenInputMenu = require("./TokenInputMenu");
var _TextWidthHelper = require("./TextWidthHelper");var _dec, _class, _TokenInput;

var TEMP_FAKE_FLAG = 'TEMP_FAKE_FLAG';var

TokenInputType = exports.TokenInputType = /*#__PURE__*/function (TokenInputType) {TokenInputType[TokenInputType["WithReference"] = 0] = "WithReference";TokenInputType[TokenInputType["WithoutReference"] = 1] = "WithoutReference";TokenInputType[TokenInputType["Combined"] = 2] = "Combined";return TokenInputType;}({});


























































































































































var DefaultState = exports.DefaultState = {
  inputValue: '',
  reservedInputValue: undefined,
  autocompleteItems: undefined,
  activeTokens: [],
  editingTokenIndex: -1,
  inFocus: false,
  loading: false,
  preventBlur: false,
  inputValueWidth: 2,
  inputValueHeight: 22
};

var TokenInputDataTids = exports.TokenInputDataTids = {
  root: 'TokenInput__root',
  tokenInputMenu: 'TokenInputMenu__root',
  label: 'TokenInput__label'
};























var defaultToKey = function defaultToKey(item) {return item.toString();};
// eslint-disable-next-line @typescript-eslint/no-unnecessary-type-constraint
var identity = function identity(item) {return item;};
var defaultRenderToken = function defaultRenderToken(
item, _ref,


index) {var isActive = _ref.isActive,onClick = _ref.onClick,onDoubleClick = _ref.onDoubleClick,onRemove = _ref.onRemove,disabled = _ref.disabled,size = _ref.size;return /*#__PURE__*/(

    _react.default.createElement(_Token.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 = exports.TokenInput = (_dec = (0, _decorators.locale)('TokenInput', _locale.TokenInputLocaleHelper), (0, _rootNode.rootNode)(_class = _dec(_class = (0, _SizeDecorator.withSize)(_class = (_TokenInput = /*#__PURE__*/function (_React$PureComponent) {function TokenInput() {var _this;for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {args[_key] = arguments[_key];}_this = _React$PureComponent.call.apply(_React$PureComponent, [this].concat(args)) || this;_this.









































    state = DefaultState;_this.

    _textareaId = (0, _uidUtils.getUid)();_this.
    rootId = _Popup.PopupIds.root + (0, _utils.getRandomID)();_this.




    input = null;_this.
    tokensInputMenu = null;_this.
    textHelper = null;_this.
    wrapper = null;_this.
    scrollContainerRef = /*#__PURE__*/_react.default.createRef();_this.


    memoizedTokens = new Map();_this.




































































































































































































































































    isEqual = function (itemA, itemB) {
      var _this$getProps = _this.getProps(),itemToId = _this$getProps.itemToId;
      return (0, _lodash.default)(itemToId(itemA), itemToId(itemB));
    };_this.

    hasValueInItems = function (items, value) {
      var _this$getProps2 = _this.getProps(),valueToString = _this$getProps2.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) {return _this.input = node;};_this.
    tokensInputMenuRef = function (node) {return _this.tokensInputMenu = node;};_this.
    textHelperRef = function (node) {return _this.textHelper = node;};_this.
    wrapperRef = function (node) {return _this.wrapper = node;};_this.

    dispatch = function (action, cb) {
      _this.setState(function (prevState) {return (0, _TokenInputReducer.tokenInputReducer)(prevState, action);}, cb);
    };_this.













    handleInputFocus = function (event) {
      _this.dispatch({ type: 'SET_FOCUS_IN' });
      _this.getProps().onFocus(event);
    };_this.

    handleInputBlur = function (event) {
      var isBlurToMenu = _this.isBlurToMenu(event);

      if (!isBlurToMenu) {
        _this.handleOutsideBlur();
      }

      if (isBlurToMenu || _this.state.preventBlur) {var _this$input;
        event.preventDefault();
        // первый focus нужен для предотвращения/уменьшения моргания в других браузерах
        (_this$input = _this.input) == null || _this$input.focus({ preventScroll: true });
        // в firefox не работает без второго focus
        _globalObject.globalObject.requestAnimationFrame == null || _globalObject.globalObject.requestAnimationFrame(function () {var _this$input2;return (_this$input2 = _this.input) == null ? void 0 : _this$input2.focus({ preventScroll: true });});

        _this.dispatch({ type: 'SET_PREVENT_BLUR', payload: false });
      } else {
        _this.dispatch({ type: 'BLUR' });
        _this.getProps().onBlur(event);
      }
    };_this.

    handleOutsideBlur = function () {
      var _this$state = _this.state,inputValue = _this$state.inputValue,allItems = _this$state.autocompleteItems;
      var autocompleteItems = allItems == null ? 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) {
      if (_this.menuRef && _globalObject.globalObject.document) {var _this$tokensInputMenu;
        var menu = (0, _rootNode.getRootNode)((_this$tokensInputMenu = _this.tokensInputMenu) == null ? void 0 : _this$tokensInputMenu.getMenuRef());
        var relatedTarget = event.relatedTarget || _globalObject.globalObject.document.activeElement;

        if (menu && menu.contains(relatedTarget)) {
          return true;
        }
      }
      return false;
    };_this.

    handleWrapperMouseDown = function (event) {var _this$wrapper;
      _this.dispatch({ type: 'SET_PREVENT_BLUR', payload: true });
      var target = event.target;
      var isClickOnToken = target && ((_this$wrapper = _this.wrapper) == null ? void 0 : _this$wrapper.contains(target)) && target !== _this.wrapper && target !== _this.input;
      if (!isClickOnToken) {
        _this.dispatch({ type: 'REMOVE_ALL_ACTIVE_TOKENS' });
      }
    };_this.

    handleWrapperMouseUp = function (e) {
      // Имитируем поведение label, когда задан maxHeight.
      if (
      _this.props.maxHeight &&
      e.target === _this.scrollContainerRef.current && (
      _this.state.activeTokens.length !== 0 || !_this.state.inFocus))
      {var _this$input3;
        _this.dispatch({ type: 'BLUR' });
        _this.dispatch({ type: 'SET_FOCUS_IN' });
        _this.focusInput();
        (_this$input3 = _this.input) == null || _this$input3.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 _this$getProps3 = _this.getProps(),selectedItems = _this$getProps3.selectedItems,valueToString = _this$getProps3.valueToString,delimiters = _this$getProps3.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 _this$getProps4 = _this.getProps(),delimiters = _this$getProps4.delimiters,selectedItems = _this$getProps4.selectedItems,valueToItem = _this$getProps4.valueToItem,onValueChange = _this$getProps4.onValueChange;
      if (delimiters.some(function (delimiter) {return paste.includes(delimiter);})) {
        event.preventDefault();
        event.stopPropagation();
        var tokens = paste.trim().split(new RegExp("[" + 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 = /*#__PURE__*/function () {var _ref2 = (0, _asyncToGenerator2.default)( /*#__PURE__*/_regenerator.default.mark(function _callee(query) {var autocompleteItems, _this$getProps5, selectedItems, valueToItem, valueToString, isSelectedItem, isEditingItem, autocompleteItemsUnique, autocompleteItemsUniqueSimple, editingItem, selectItemIndex;return _regenerator.default.wrap(function _callee$(_context) {while (1) switch (_context.prev = _context.next) {case 0:if (query === void 0) {query = '';}if (!(
              _this.props.getItems && (_this.isInputValueChanged || !_this.props.hideMenuIfEmptyInputValue))) {_context.next = 16;break;}
              _this.dispatch({ type: 'SET_LOADING', payload: true });_context.next = 5;return (
                _this.props.getItems(query));case 5:autocompleteItems = _context.sent;
              _this.dispatch({ type: 'SET_LOADING', payload: false });_this$getProps5 =

              _this.getProps(), selectedItems = _this$getProps5.selectedItems, valueToItem = _this$getProps5.valueToItem, valueToString = _this$getProps5.valueToString;
              isSelectedItem = function isSelectedItem(item) {return _this.hasValueInItems(selectedItems, item);};
              isEditingItem = function isEditingItem(item) {
                var editingItem = selectedItems[_this.state.editingTokenIndex];
                return !!editingItem && _this.isEqual(item, editingItem);
              };

              autocompleteItemsUnique = autocompleteItems.filter(function (item) {return (
                  isSimpleItem(item) ? !isSelectedItem(item) || isEditingItem(item) : true);}
              );
              autocompleteItemsUniqueSimple = autocompleteItemsUnique.filter(isSimpleItem);

              if (_this.isEditingMode) {
                editingItem = selectedItems[_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 = autocompleteItemsUniqueSimple.findIndex(
                function (item) {return valueToString(item).toLowerCase() === _this.state.inputValue.toLowerCase();}
              );
              setTimeout(function () {var _this$menuRef;return (_this$menuRef = _this.menuRef) == null ? void 0 : _this$menuRef.highlightItem(selectItemIndex < 0 ? 0 : selectItemIndex);}, 0);case 16:case "end":return _context.stop();}}, _callee);}));return function (_x) {return _ref2.apply(this, arguments);};}();_this.



    handleKeyDown = function (event) {
      _this.props.onKeyDown == null || _this.props.onKeyDown(event);

      if (event.defaultPrevented) {
        return;
      }

      if (_this.isCursorVisible) {
        _this.handleInputKeyDown(event);
      } else {
        _this.handleWrapperKeyDown(event);
      }
    };_this.

    handleInputKeyDown = function (e) {var _this$state$autocompl, _this$state$autocompl2, _this$input4, _this$input5;
      e.stopPropagation();

      if (
      _this.type !== TokenInputType.WithReference &&
      _this.getProps().delimiters.some(function (key) {return key === e.key || key === ',' && (0, _identifiers.isKeyComma)(e);}) ||
      (0, _identifiers.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 || ((_this$state$autocompl = (_this$state$autocompl2 = _this.state.autocompleteItems) == null ? void 0 : _this$state$autocompl2.length) != null ? _this$state$autocompl : 0) > 0;

      switch (true) {
        case (0, _identifiers.isKeyEnter)(e):
          if (canSetValueToInput && _this.menuRef) {
            _this.menuRef.enter(e);
          }
          // don't allow textarea
          // became multiline
          e.preventDefault();
          break;
        case (0, _identifiers.isKeyArrowVertical)(e):
          e.preventDefault();
          if (_this.menuRef) {
            if ((0, _identifiers.isKeyArrowUp)(e)) {
              _this.menuRef.up();
            } else {
              _this.menuRef.down();
            }
          }
          break;
        case (0, _identifiers.isKeyEscape)(e):
          (_this$input4 = _this.input) == null || _this$input4.blur();
          break;
        case (0, _identifiers.isKeyBackspace)(e):
          if (!_this.isEditingMode && isRightmostTokenNotDisabled) {
            _this.moveFocusToLastToken();
          }
          break;
        case (0, _identifiers.isKeyArrowLeft)(e):
          if (((_this$input5 = _this.input) == null ? void 0 : _this$input5.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) {
      _globalObject.globalObject.requestAnimationFrame == null || _globalObject.globalObject.requestAnimationFrame(function () {var _this$input6;return (_this$input6 = _this.input) == null ? void 0 : _this$input6.focus(options);});
    };_this.

    selectInputText = function () {
      if (_this.input) {
        _this.input.setSelectionRange(0, _this.state.inputValue.length);
      }
    };_this.

    handleWrapperKeyDown = function (e) {var _this$wrapper2;
      var _this$getProps6 = _this.getProps(),selectedItems = _this$getProps6.selectedItems,onValueChange = _this$getProps6.onValueChange;
      switch (true) {
        case (0, _identifiers.isKeyBackspace)(e):
        case (0, _identifiers.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 _this$input7;
                LayoutEvents.emit();
                (_this$input7 = _this.input) == null || _this$input7.focus();
              });
            }
            break;
          }
        case (0, _identifiers.isKeyArrowHorizontal)(e):
          _this.handleWrapperArrows(e);
          break;
        case (0, _identifiers.isKeyEscape)(e):
          (_this$wrapper2 = _this.wrapper) == null || _this$wrapper2.blur();
          break;
        case (0, _identifiers.isKeyEnter)(e):
          e.preventDefault();
          if (_this.state.activeTokens.length === 1) {
            _this.handleTokenEdit(_this.state.activeTokens[0]);
          }
          break;
        case (0, _identifiers.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, (0, _identifiers.isKeyArrowLeft)(e));
      var isLeftEdge = activeItemIndex === 0 && (0, _identifiers.isKeyArrowLeft)(e);
      var isRightEdge = newItemIndex === selectedItems.length && (0, _identifiers.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 _this$input8;return (_this$input8 = _this.input) == null ? void 0 : _this$input8.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 = _this.getProps().selectedItems[newItemIndex];
        var itemsNew = [itemNew].concat(_this.state.activeTokens.filter(function (item) {return !_this.isEqual(item, itemNew);}));
        _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 _this$getProps7 = _this.getProps(),allItems = _this$getProps7.selectedItems,valueToString = _this$getProps7.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) {
      _this.props.onValueChange == null || _this.props.onValueChange(_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);}) : [].concat(
          items, [itemNew]);
        _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 _this$getProps8 = _this.getProps(),selectedItems = _this$getProps8.selectedItems,valueToString = _this$getProps8.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 _autocompleteItems$fi;
      var _this$getProps9 = _this.getProps(),selectedItems = _this$getProps9.selectedItems,valueToString = _this$getProps9.valueToString;
      var _this$state2 = _this.state,editingTokenIndex = _this$state2.editingTokenIndex,inputValue = _this$state2.inputValue,reservedInputValue = _this$state2.reservedInputValue,autocompleteItems = _this$state2.autocompleteItems;

      var editedItem = (_autocompleteItems$fi =
      autocompleteItems == null ? void 0 : autocompleteItems.find(function (item) {return valueToString(item) === inputValue;})) != null ? _autocompleteItems$fi : _this.getProps().valueToItem(inputValue);

      var newItems = selectedItems.concat([]);

      if (!_this.hasValueInItems(selectedItems, editedItem)) {
        newItems.splice.apply(newItems, [editingTokenIndex, 1].concat(_this.isInputValueChanged ? [editedItem] : []));
        _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 ? void 0 : onUnexpectedInput(inputValue);

      if (returnedValue === undefined) {
        if (
        _this.featureFlags.tokenInputCreateTokenOnBlurInWithoutReferenceMode &&
        _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 _this$props$selectedI;
      var _this$props = _this.props,_this$props$renderTok = _this$props.renderToken,renderToken = _this$props$renderTok === void 0 ? defaultRenderToken : _this$props$renderTok,disabled = _this$props.disabled;

      var isActive = _this.state.activeTokens.includes(item);

      // TODO useCallback
      var handleIconClick = function handleIconClick(event) {
        event.stopPropagation();
        if (!_this.isEditingMode) {
          _this.handleRemoveToken(item);
        }
      };

      // TODO useCallback
      var handleTokenClick = function handleTokenClick(event) {
        event.stopPropagation();
        if (!_this.isEditingMode) {
          _this.handleTokenClick(event, item);
        }
      };

      var handleTokenDoubleClick = function handleTokenDoubleClick(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((_this$props$selectedI = _this.props.selectedItems) == null ? void 0 : _this$props$selectedI.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 _this$locale = _this.locale,addButtonComment = _this$locale.addButtonComment,addButtonTitle = _this$locale.addButtonTitle;

      return /*#__PURE__*/(
        _react.default.createElement(_MenuItem.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 _this$getProps10 = _this.getProps(),selectedItems = _this$getProps10.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;}(0, _inheritsLoose2.default)(TokenInput, _React$PureComponent);var _proto = TokenInput.prototype;_proto.getDelimiters = function getDelimiters() {var _this$props$delimiter;var delimiters = (_this$props$delimiter = this.props.delimiters) != null ? _this$props$delimiter : [];if (delimiters.every(function (delimiter) {return delimiter !== TEMP_FAKE_FLAG;})) {return delimiters;}return delimiters.filter(function (delimiter) {return delimiter !== TEMP_FAKE_FLAG;});};_proto.getProps = function getProps() {var propsGetter = (0, _createPropsGetter.createPropsGetter)(TokenInput.defaultProps);var propsWithOldDelimiters = propsGetter.apply(this);return (0, _extends2.default)({}, propsWithOldDelimiters, { delimiters: this.getDelimiters() });};_proto.componentDidMount = function componentDidMount() {var _globalObject$documen;this.updateInputTextWidth();(_globalObject$documen = _globalObject.globalObject.document) == null || _globalObject$documen.addEventListener('copy', this.handleCopy);if (this.props.autoFocus) {this.focusInput();}};_proto.componentDidUpdate = function componentDidUpdate(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);}};_proto.componentWillUnmount = function componentWillUnmount() {var _globalObject$documen2;(_globalObject$documen2 = _globalObject.globalObject.document) == null || _globalObject$documen2.removeEventListener('copy', this.handleCopy);} /** Программно устанавливает фокус на поле.
   * Появляется фокусная рамка, элемент получает клавиатурные события и воспринимается как текущий элемент для чтения скринридерами.
   * @public
   */;_proto.focus = function focus() {var _this$input9;(_this$input9 = this.input) == null || _this$input9.focus();} /** Программно снимает фокус с поля.
   * @public
   */;_proto.blur = function blur() {var _this$input10;(_this$input10 = this.input) == null || _this$input10.blur();} /** Кратковременно визуально подсвечивает поле ввода, чтобы привлечь внимание пользователя.
   * @public
   */;_proto.blink = function blink() {(0, _blink2.blink)({ el: this.wrapper, blinkColor: this.theme.inputBlinkColor });};_proto.render = function render() {var _this2 = this;return /*#__PURE__*/_react.default.createElement(_featureFlagsContext.ReactUIFeatureFlagsContext.Consumer, null, function (flags) {_this2.featureFlags = (0, _featureFlagsContext.getFullReactUIFlagsContext)(flags);return /*#__PURE__*/_react.default.createElement(_ThemeContext.ThemeContext.Consumer, null, function (theme) {_this2.theme = theme;return _this2.renderMain();});});};_proto.getLabelSizeClassName = function getLabelSizeClassName() {switch (this.size) {case 'large':return _TokenInput2.styles.labelLarge(this.theme);case 'medium':return _TokenInput2.styles.labelMedium(this.theme);case 'small':default:return _TokenInput2.styles.labelSmall(this.theme);}};_proto.getInputSizeClassName = function getInputSizeClassName() {switch (this.size) {case 'large':return _TokenInput2.styles.inputLarge(this.theme);case 'medium':return _TokenInput2.styles.inputMedium(this.theme);case 'small':default:return _TokenInput2.styles.inputSmall(this.theme);}};_proto.renderMain = function renderMain() {var _cx, _cx2, _cx3;if (this.type !== TokenInputType.WithoutReference && !this.props.getItems) {throw Error('Missed getItems for type ' + this.type);}var _this$props2 = this.props,maxMenuHeight = _this$props2.maxMenuHeight,error = _this$props2.error,warning = _this$props2.warning,disabled = _this$props2.disabled,renderNotFound = _this$props2.renderNotFound,hideMenuIfEmptyInputValue = _this$props2.hideMenuIfEmptyInputValue,inputMode = _this$props2.inputMode,renderTotalCount = _this$props2.renderTotalCount,totalCount = _this$props2.totalCount,ariaDescribedby = _this$props2['aria-describedby'],ariaLabel = _this$props2['aria-label'],maxHeight = _this$props2.maxHeight;var _this$getProps11 = this.getProps(),selectedItems = _this$getProps11.selectedItems,width = _this$getProps11.width,onMouseEnter = _this$getProps11.onMouseEnter,onMouseLeave = _this$getProps11.onMouseLeave,menuWidth = _this$getProps11.menuWidth,menuAlign = _this$getProps11.menuAlign,renderItem = _this$getProps11.renderItem;var _this$state3 = this.state,activeTokens = _this$state3.activeTokens,inFocus = _this$state3.inFocus,inputValueWidth = _this$state3.inputValueWidth,inputValueHeight = _this$state3.inputValueHeight,inputValue = _this$state3.inputValue,reservedInputValue = _this$state3.reservedInputValue,autocompleteItems = _this$state3.autocompleteItems,loading = _this$state3.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 = (0, _Emotion.cx)(_TokenInput2.styles.label(theme), this.getLabelSizeClassName(), (_cx = {}, _cx[_TokenInput2.styles.hovering(this.theme)] = !inFocus && !disabled && !warning && !error, _cx[_TokenInput2.styles.labelDisabled(theme)] = !!disabled, _cx[_TokenInput2.styles.labelFocused(theme)] = !!inFocus, _cx[_TokenInput2.styles.error(theme)] = !!error, _cx[_TokenInput2.styles.warning(theme)] = !!warning, _cx));var inputClassName = (0, _Emotion.cx)(_TokenInput2.styles.input(theme), this.getInputSizeClassName(), (_cx2 = {}, _cx2[_TokenInput2.styles.inputDisabled(theme)] = !!disabled, _cx2));var placeholder = selectedItems.length === 0 && !inputValue ? this.props.placeholder : '';var inputNode = /*#__PURE__*/_react.default.createElement(_TokenView.TokenView, { size: this.size, className: (0, _Emotion.cx)((_cx3 = {}, _cx3[_TokenInput2.styles.inputPlaceholderWrapper()] = Boolean(placeholder), _cx3)), hideCloseButton: Boolean(placeholder) }, /*#__PURE__*/_react.default.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 = /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, /*#__PURE__*/_react.default.createElement(_TextWidthHelper.TextWidthHelper, { ref: this.textHelperRef, text: inputValue, theme: this.theme, size: this.size }), this.renderTokensStart(), inputNode, showMenu && /*#__PURE__*/_react.default.createElement(_TokenInputMenu.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 ? /*#__PURE__*/_react.default.createElement(_TokenView.TokenView, { size: this.size }, /*#__PURE__*/_react.default.createElement("span", { className: _TokenInput2.styles.reservedInput(theme) }, reservedInputValue)) : null);var container = maxHeight ? /*#__PURE__*/_react.default.createElement(_ScrollContainer.ScrollContainer, { scrollRef: this.scrollContainerRef, maxHeight: maxHeight, showScrollBar: "always" }, inner) : inner;return /*#__PURE__*/_react.default.createElement(_CommonWrapper.CommonWrapper, (0, _extends2.default)({ rootNodeRef: this.setRootNode }, this.props), /*#__PURE__*/_react.default.createElement("div", { "data-tid": TokenInputDataTids.root, onMouseEnter: onMouseEnter, onMouseLeave: onMouseLeave }, /*#__PURE__*/_react.default.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
   */;_proto.reset = function reset() {this.dispatch({ type: 'RESET' });};_proto.isCursorVisibleForState = function isCursorVisibleForState(state) {return state.inFocus && (this.isInputValueChanged || state.activeTokens.length === 0);};_proto.updateInputTextWidth = function updateInputTextWidth() {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);}};_proto.moveFocusToLastToken = function moveFocusToLastToken() {var items = this.getProps().selectedItems;if (this.state.inputValue === '' && items && items.length > 0) {this.dispatch({ type: 'SET_ACTIVE_TOKENS', payload: items.slice(-1) });}};return (0, _createClass2.default)(TokenInput, [{ key: "textareaId", get: function get() {var _this$props$id;return (_this$props$id = this.props.id) != null ? _this$props$id : this._textareaId;} }, { key: "showAddItemHint", get: function get() {var _this$state$autocompl3;var items = (_this$state$autocompl3 = this.state.autocompleteItems) == null ? void 0 : _this$state$autocompl3.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;}} }, { key: "type", get: function get() {return this.props.type ? this.props.type : TokenInputType.WithReference;} }, { key: "menuRef", get: function get() {return this.tokensInputMenu && this.tokensInputMenu.getMenuRef();} }, { key: "isCursorVisible", get: function get() {return this.isCursorVisibleForState(this.state);} }, { key: "isEditingMode", get: function get() {return this.state.editingTokenIndex > -1;} }, { key: "isInputChanged", get: function get() {if (this.isEditingMode) {return this.isTokenValueChanged;}return this.isInputValueChanged;} }, { key: "isInputValueChanged", get: function get() {var inputValue = this.state.inputValue;return inputValue !== '';} }, { key: "isTokenValueChanged", get: function get() {var _this$state4 = this.state,inputValue = _this$state4.inputValue,editingTokenIndex = _this$state4.editingTokenIndex;var _this$getProps12 = this.getProps(),valueToString = _this$getProps12.valueToString,selectedItems = _this$getProps12.selectedItems;if (this.isEditingMode) {return valueToString(selectedItems[editingTokenIndex]) !== inputValue;}return false;} }]);}(_react.default.PureComponent), _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 valueToItem(item) {return item;}, toKey: defaultToKey, itemToId: identity, onValueChange: function onValueChange() {return void 0;}, width: 250, onBlur: _utils.emptyHandler, onFocus: _utils.emptyHandler, onMouseEnter: _utils.emptyHandler, onMouseLeave: _utils.emptyHandler, menuWidth: 'auto', menuAlign: 'cursor' }, _TokenInput)) || _class) || _class) || _class);function isSimpleItem(item) {return !(0, _utils.isFunction)(item) && ! /*#__PURE__*/_react.default.isValidElement(item);}