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 };
    }
};
import React from 'react';
import ReactDOM from 'react-dom';
import { CancelationError, taskWithDelay } from '../../lib/utils.js';
import { CommonWrapper } from '../CommonWrapper/index.js';
import { responsiveLayout } from '../../components/ResponsiveLayout/decorator.js';
import { rootNode } from '../../lib/rootNode/index.js';
import { withSize } from '../../lib/size/SizeDecorator.js';
import { withRenderEnvironment } from '../../lib/renderEnvironment/index.js';
import { ComboBoxRequestStatus } from './CustomComboBoxTypes.js';
import { reducer } from './CustomComboBoxReducer.js';
import { ComboBoxView } from './ComboBoxView.js';
export * from './tids.js';
export var DELAY_BEFORE_SHOW_LOADER = 300;
export var LOADER_SHOW_TIME = 1000;
export var DefaultState = {
    inputChanged: false,
    editing: false,
    items: null,
    loading: false,
    opened: false,
    focused: false,
    textValue: '',
    repeatRequest: function () { return undefined; },
    requestStatus: ComboBoxRequestStatus.Unknown,
};
var CustomComboBox = /** @class */ (function (_super) {
    __extends(CustomComboBox, _super);
    function CustomComboBox() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.state = DefaultState;
        _this.requestId = 0;
        _this.focused = false;
        _this.cancelationToken = null;
        _this.canOpenPopup = true;
        _this.reducer = reducer;
        _this.cancelLoaderDelay = function () { return null; };
        /**
         * @public
         */
        _this.focus = function (opts) {
            if (_this.props.disabled) {
                return;
            }
            if (opts === null || opts === void 0 ? void 0 : opts.withoutOpenDropdown) {
                _this.canOpenPopup = false;
            }
            if (_this.input) {
                _this.input.focus();
            }
            else if (_this.inputLikeText) {
                _this.inputLikeText.focus();
            }
        };
        /**
         * @public
         */
        _this.selectInputText = function () {
            if (_this.props.disabled) {
                return;
            }
            if (_this.input) {
                _this.input.selectAll();
            }
        };
        /**
         * @public
         */
        _this.blur = function () {
            if (_this.props.disabled) {
                return;
            }
            _this.handleBlur();
        };
        _this.dispatch = function (action, sync) {
            if (sync === void 0) { sync = true; }
            var updateState = function (action) {
                var effects;
                var nextState;
                _this.setState(function (state) {
                    var _a;
                    var stateAndEffect = _this.reducer(state, _this.props, action);
                    _a = stateAndEffect instanceof Array ? stateAndEffect : [stateAndEffect, []], nextState = _a[0], effects = _a[1];
                    return nextState;
                }, function () {
                    effects.forEach(_this.handleEffect);
                });
            };
            // Auto-batching React@18 creates problems that are fixed with flushSync
            // https://github.com/skbkontur/retail-ui/pull/3144#issuecomment-1535235366
            if (sync && Number(React.version) >= 18) {
                ReactDOM.flushSync(function () { return updateState(action); });
            }
            else {
                updateState(action);
            }
        };
        _this.handleEffect = function (effect) {
            effect(_this.dispatch, _this.getState, _this.getProps, function () { return _this; }, _this.globalObject);
        };
        _this.getProps = function () { return _this.props; };
        _this.getState = function () { return _this.state; };
        _this.handleValueChange = function (value) {
            _this.dispatch({
                type: 'ValueChange',
                value: value,
                keepFocus: !_this.isMobileLayout,
            });
        };
        _this.handleFocus = function () {
            if (_this.focused) {
                return;
            }
            _this.focused = true;
            _this.dispatch({ type: 'Focus', searchOnFocus: _this.canOpenPopup && _this.props.searchOnFocus });
            if (!_this.canOpenPopup) {
                _this.canOpenPopup = true;
            }
        };
        _this.handleMobileClose = function () {
            _this.handleInputBlur();
        };
        _this.handleClickOutside = function () {
            _this.handleBlur();
        };
        _this.handleBlur = function () {
            if (!_this.focused) {
                if (_this.state.opened) {
                    _this.close();
                }
                return;
            }
            _this.focused = false;
            // workaround for the similar bug with focusout
            // in Firefox, Chrome and IE
            // https://bugzilla.mozilla.org/show_bug.cgi?id=1363964
            setTimeout(function () {
                _this.dispatch({ type: 'Blur' });
            }, 0);
        };
        _this.handleInputBlur = function () {
            // If menu opened, RenderLayer is active and
            // it would call handleFocusOutside
            // In that way handleBlur would be called
            if (_this.state.opened && !_this.isMobileLayout) {
                return;
            }
            _this.handleBlur();
        };
        _this.handleInputClick = function () {
            if (!_this.cancelationToken) {
                _this.dispatch({ type: 'InputClick' });
            }
        };
        return _this;
    }
    /**
     * @public
     */
    CustomComboBox.prototype.search = function () {
        return __awaiter(this, arguments, void 0, function (query) {
            var getItems, cancelPromise, expectingId, items, error_1;
            var _this = this;
            if (query === void 0) { query = this.state.textValue; }
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        getItems = this.props.getItems;
                        cancelPromise = new Promise(function (_, reject) { return (_this.cancelationToken = reject); });
                        this.requestId += 1;
                        expectingId = this.requestId;
                        if (!this.loaderShowDelay) {
                            this.loaderShowDelay = new Promise(function (resolve) {
                                var cancelLoader = taskWithDelay(function () {
                                    _this.dispatch({ type: 'RequestItems' });
                                    setTimeout(resolve, LOADER_SHOW_TIME);
                                }, DELAY_BEFORE_SHOW_LOADER);
                                cancelPromise.catch(function () { return cancelLoader(); });
                                _this.cancelLoaderDelay = function () {
                                    cancelLoader();
                                    resolve();
                                };
                            });
                        }
                        _a.label = 1;
                    case 1:
                        _a.trys.push([1, 5, 6, 7]);
                        return [4 /*yield*/, Promise.race([getItems(query), cancelPromise])];
                    case 2:
                        items = _a.sent();
                        if (!this.state.loading) return [3 /*break*/, 4];
                        return [4 /*yield*/, Promise.race([this.loaderShowDelay, cancelPromise])];
                    case 3:
                        _a.sent();
                        _a.label = 4;
                    case 4:
                        if (expectingId === this.requestId) {
                            this.dispatch({
                                type: 'ReceiveItems',
                                items: items,
                            });
                        }
                        return [3 /*break*/, 7];
                    case 5:
                        error_1 = _a.sent();
                        if (error_1 && error_1.code === 'CancelationError') {
                            this.dispatch({ type: 'CancelRequest' });
                        }
                        else if (expectingId === this.requestId) {
                            this.dispatch({
                                type: 'RequestFailure',
                                repeatRequest: function () {
                                    _this.search(query);
                                    if (_this.input) {
                                        _this.input.focus();
                                    }
                                },
                            });
                        }
                        return [3 /*break*/, 7];
                    case 6:
                        if (expectingId === this.requestId) {
                            if (!this.state.loading) {
                                this.cancelLoaderDelay();
                            }
                            this.cancelationToken = null;
                            this.loaderShowDelay = null;
                        }
                        return [7 /*endfinally*/];
                    case 7: return [2 /*return*/];
                }
            });
        });
    };
    /**
     * @public
     */
    CustomComboBox.prototype.cancelSearch = function () {
        if (this.cancelationToken) {
            this.cancelationToken(new CancelationError());
        }
    };
    /**
     * @public
     */
    CustomComboBox.prototype.open = function () {
        this.dispatch({ type: 'Open' });
    };
    /**
     * @public
     */
    CustomComboBox.prototype.close = function () {
        this.dispatch({ type: 'Close' });
    };
    CustomComboBox.prototype.render = function () {
        var _this = this;
        var viewProps = {
            align: this.props.align,
            borderless: this.props.borderless,
            disabled: this.props.disabled,
            disablePortal: this.props.disablePortal,
            editing: this.state.editing,
            error: this.props.error,
            items: this.state.items,
            loading: this.state.loading,
            opened: this.state.opened,
            drawArrow: this.props.drawArrow,
            menuPos: this.props.menuPos,
            menuAlign: this.props.menuAlign,
            placeholder: this.props.placeholder,
            size: this.size,
            textValue: this.state.textValue,
            totalCount: this.props.totalCount,
            value: this.props.value,
            showClearIcon: this.props.showClearIcon,
            warning: this.props.warning,
            'aria-describedby': this.props['aria-describedby'],
            'aria-label': this.props['aria-label'],
            id: this.props.id,
            width: this.props.width,
            maxLength: this.props.maxLength,
            maxMenuHeight: this.props.maxMenuHeight,
            leftIcon: this.props.leftIcon,
            rightIcon: this.props.rightIcon,
            inputMode: this.props.inputMode,
            mask: this.props.mask,
            maskChar: this.props.maskChar,
            formatChars: this.props.formatChars,
            onBeforePasteInMask: this.props.onBeforePasteInMask,
            onValueChange: this.handleValueChange,
            onClickOutside: this.handleClickOutside,
            onFocus: this.handleFocus,
            onMobileClose: this.handleMobileClose,
            onFocusOutside: this.handleBlur,
            onInputBlur: this.handleInputBlur,
            onInputValueChange: function (value) { return _this.dispatch({ type: 'TextChange', value: value }); },
            onInputFocus: this.handleFocus,
            onInputClick: this.handleInputClick,
            onClearCrossClick: function () { return _this.dispatch({ type: 'ClearCrossClick' }); },
            onInputKeyDown: function (event) {
                event.persist();
                _this.dispatch({ type: 'KeyPress', event: event });
            },
            onMouseEnter: this.props.onMouseEnter,
            onMouseOver: this.props.onMouseOver,
            onMouseLeave: this.props.onMouseLeave,
            renderItem: this.props.renderItem,
            renderNotFound: this.props.renderNotFound,
            itemWrapper: this.props.itemWrapper,
            renderValue: this.props.renderValue,
            renderTotalCount: this.props.renderTotalCount,
            renderAddButton: this.props.renderAddButton,
            repeatRequest: this.state.repeatRequest,
            requestStatus: this.state.requestStatus,
            refInput: function (input) {
                _this.input = input;
            },
            refMenu: function (menu) {
                _this.menu = menu;
            },
            refInputLikeText: function (inputLikeText) {
                _this.inputLikeText = inputLikeText;
            },
            viewMode: this.props.viewMode,
            maxRows: this.props.maxRows,
        };
        return (React.createElement(CommonWrapper, __assign({}, this.props),
            React.createElement(ComboBoxView, __assign({}, viewProps, { size: this.props.size, ref: this.setRootNode }))));
    };
    CustomComboBox.prototype.componentDidMount = function () {
        this.dispatch({ type: 'Mount' }, false);
        if (this.props.autoFocus) {
            this.focus();
        }
    };
    CustomComboBox.prototype.componentDidUpdate = function (prevProps, prevState) {
        if (prevState.editing && !this.state.editing) {
            this.handleBlur();
        }
        this.dispatch({
            type: 'DidUpdate',
            prevProps: prevProps,
            prevState: prevState,
        }, false);
    };
    /**
     * @public
     */
    CustomComboBox.prototype.reset = function () {
        this.dispatch({ type: 'Reset' });
    };
    CustomComboBox.__KONTUR_REACT_UI__ = 'CustomComboBox';
    CustomComboBox.displayName = 'CustomComboBox';
    CustomComboBox = __decorate([
        withRenderEnvironment,
        responsiveLayout,
        rootNode,
        withSize
    ], CustomComboBox);
    return CustomComboBox;
}(React.PureComponent));
export { CustomComboBox };
//# sourceMappingURL=CustomComboBox.js.map