var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var __assign = (this && this.__assign) || function () {
    __assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return __assign.apply(this, arguments);
};
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __rest = (this && this.__rest) || function (s, e) {
    var t = {};
    for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
        t[p] = s[p];
    if (s != null && typeof Object.getOwnPropertySymbols === "function")
        for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
            if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
                t[p[i]] = s[p[i]];
        }
    return t;
};
import React from 'react';
import { MenuMessage } from '../../internal/MenuMessage/index.js';
import { locale } from '../../lib/locale/decorators.js';
import { getRandomID, isNullable } from '../../lib/utils.js';
import { ThemeContext } from '../../lib/theming/ThemeContext.js';
import { isKeyArrowDown, isKeyArrowUp, isKeyEnter, isKeyEscape } from '../../lib/events/keyboard/identifiers.js';
import { Input } from '../Input/index.js';
import { Menu } from '../../internal/Menu/index.js';
import { MenuItem } from '../MenuItem/index.js';
import { RenderLayer } from '../../internal/RenderLayer/index.js';
import { createPropsGetter } from '../../lib/createPropsGetter.js';
import { CommonWrapper } from '../../internal/CommonWrapper/index.js';
import { MobilePopup } from '../../internal/MobilePopup/index.js';
import { responsiveLayout } from '../ResponsiveLayout/decorator.js';
import { getRootNode, rootNode } from '../../lib/rootNode/index.js';
import { getDOMRect } from '../../lib/dom/getDOMRect.js';
import { Popup } from '../../internal/Popup/index.js';
import { getMenuPositions } from '../../lib/getMenuPositions.js';
import { ZIndex } from '../../internal/ZIndex/index.js';
import { getSafeMaskInputType, MaskedInput } from '../MaskedInput/index.js';
import { withSize } from '../../lib/size/SizeDecorator.js';
import { withRenderEnvironment } from '../../lib/renderEnvironment/index.js';
import { getStyles } from './Autocomplete.styles.js';
import { AutocompleteLocaleHelper } from './locale/index.js';
import { getAutocompleteTheme } from './getAutocompleteTheme.js';
function match(pattern, items) {
    if (!pattern || !items) {
        return Promise.resolve([]);
    }
    var lowerCasedPattern = pattern.toLowerCase();
    var itemsMatchingPattern = items.filter(function (item) {
        return item.toLowerCase().includes(lowerCasedPattern);
    });
    return Promise.resolve(itemsMatchingPattern);
}
function renderItem(item) {
    return item;
}
export var AutocompleteDataTids = {
    root: 'Autocomplete__root',
    menu: 'Autocomplete__menu',
};
export var AutocompleteIds = {
    menu: AutocompleteDataTids.menu,
};
/**
 * Автокомплит — поле ввода с выпадающим списком подсказок. Подсказки отображаются пользователю, когда он начинает вводить значение в поле. */
var Autocomplete = /** @class */ (function (_super) {
    __extends(Autocomplete, _super);
    function Autocomplete() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.state = {
            items: null,
            selected: -1,
            focused: false,
            isMobileOpened: false,
        };
        _this.opened = false;
        _this.input = null;
        _this.menuId = AutocompleteIds.menu + getRandomID();
        _this.requestId = 0;
        _this.getProps = createPropsGetter(Autocomplete_1.defaultProps);
        _this.renderMain = function (props) {
            var _a;
            var focused = _this.state.focused;
            var isMobile = _this.isMobileLayout;
            var onValueChange = props.onValueChange, onKeyDown = props.onKeyDown, onFocus = props.onFocus, onBlur = props.onBlur, _renderItem = props.renderItem, disablePortal = props.disablePortal, hasShadow = props.hasShadow, menuAlign = props.menuAlign, menuMaxHeight = props.menuMaxHeight, preventWindowScroll = props.preventWindowScroll, source = props.source, menuPos = props.menuPos, _b = props.width, width = _b === void 0 ? _this.theme.inputWidth : _b, mobileMenuHeaderText = props.mobileMenuHeaderText, type = props.type, rest = __rest(props, ["onValueChange", "onKeyDown", "onFocus", "onBlur", "renderItem", "disablePortal", "hasShadow", "menuAlign", "menuMaxHeight", "preventWindowScroll", "source", "menuPos", "width", "mobileMenuHeaderText", "type"]);
            var inputProps = __assign(__assign({}, rest), { width: '100%', autoComplete: 'off', 'aria-controls': _this.menuId, onValueChange: _this.handleValueChange, onKeyDown: _this.handleKeyDown, onFocus: _this.handleFocus, ref: _this.refInput });
            return (React.createElement(RenderLayer, { onFocusOutside: _this.handleBlur, onClickOutside: _this.handleClickOutside, active: focused },
                React.createElement("span", { "data-tid": AutocompleteDataTids.root, className: _this.cx(_this.styles.root(_this.theme), (_a = {},
                        _a[_this.styles.noPortal()] = disablePortal,
                        _a)), style: { width: width }, ref: _this.refRootSpan },
                    _this.getInput(inputProps),
                    isMobile ? _this.renderMobileMenu() : _this.renderMenu())));
        };
        _this.getInput = function (inputProps) {
            return _this.props.mask ? (React.createElement(MaskedInput, __assign({}, inputProps, { type: getSafeMaskInputType(_this.props.type), mask: _this.props.mask, maskChar: _this.props.maskChar }))) : (React.createElement(Input, __assign({}, inputProps)));
        };
        _this.renderMobileMenu = function () {
            var _a;
            var inputProps = {
                autoComplete: 'off',
                autoFocus: true,
                width: '100%',
                onValueChange: _this.handleValueChange,
                onKeyPress: _this.handleKeyPressMobile,
                value: _this.props.value,
                placeholder: _this.locale.enterValue,
                type: _this.props.type,
                inputMode: _this.props.inputMode,
                'aria-label': _this.props['aria-label'],
                'aria-controls': _this.menuId,
            };
            var items = _this.state.items;
            return (React.createElement(MobilePopup, { id: _this.menuId, headerChildComponent: _this.getInput(inputProps), caption: _this.props.mobileMenuHeaderText, opened: _this.state.isMobileOpened, onCloseRequest: _this.handleCloseMobile, ref: _this.refMobilePopup },
                React.createElement(Menu, { ref: _this.refMenu, onItemClick: (_a = _this.mobilePopup) === null || _a === void 0 ? void 0 : _a.close, disableScrollContainer: true, maxHeight: 'auto' },
                    items && items.length > 0 && _this.getItems(),
                    _this.renderHints())));
        };
        _this.getItems = function () {
            var items = _this.state.items;
            var isMobile = _this.isMobileLayout;
            return items
                ? items.map(function (item, i) {
                    return (React.createElement(MenuItem, { onClick: _this.handleMenuItemClick(i), key: i, isMobile: isMobile, size: _this.size }, _this.getProps().renderItem(item)));
                })
                : null;
        };
        _this.handleValueChange = function (value) {
            _this.opened = true;
            _this.fireChange(value);
        };
        _this.handleCloseMobile = function () {
            _this.setState({
                isMobileOpened: false,
            });
            _this.handleBlur();
        };
        _this.handleKeyPressMobile = function (e) {
            var _a;
            if (e.key === 'Enter') {
                (_a = _this.mobilePopup) === null || _a === void 0 ? void 0 : _a.close();
            }
        };
        _this.handleFocus = function (event) {
            if (_this.isMobileLayout) {
                _this.setState({ isMobileOpened: true });
            }
            if (_this.state.focused) {
                return;
            }
            _this.setState({ focused: true });
            if (_this.props.onFocus) {
                _this.props.onFocus(event);
            }
        };
        _this.handleBlur = function () {
            if (!_this.state.focused) {
                return;
            }
            _this.opened = false;
            _this.setState({ items: null, focused: false });
            if (_this.input) {
                _this.input.blur();
            }
            if (_this.props.onBlur) {
                _this.props.onBlur();
            }
        };
        _this.handleClickOutside = function () {
            _this.handleBlur();
        };
        _this.handleKeyDown = function (e) {
            if (_this.props.onKeyDown) {
                _this.props.onKeyDown(e);
            }
            switch (true) {
                case isKeyEscape(e):
                    e.preventDefault();
                    _this.setState({ items: null });
                    return;
                case isKeyArrowUp(e):
                    e.preventDefault();
                    if (_this.menu) {
                        _this.menu.up();
                    }
                    return;
                case isKeyArrowDown(e):
                    e.preventDefault();
                    if (_this.menu) {
                        _this.menu.down();
                    }
                    return;
                case isKeyEnter(e):
                    e.preventDefault(); // To prevent form submission.
                    if (_this.menu) {
                        _this.menu.enter(e);
                    }
                    return;
            }
        };
        _this.getAnchor = function () {
            return getRootNode(_this);
        };
        _this.refInput = function (el) {
            _this.input = el;
        };
        _this.refMenu = function (menu) {
            _this.menu = menu;
        };
        _this.refRootSpan = function (span) {
            _this.rootSpan = span;
        };
        _this.refMobilePopup = function (mobilePopup) {
            _this.mobilePopup = mobilePopup;
        };
        return _this;
    }
    Autocomplete_1 = Autocomplete;
    /** Программно устанавливает фокус на автокомплит.
     * @public
     * @example
     * <Autocomplete ref={autocompleteRef} />
     * <button onClick={() => autocompleteRef.current?.focus()}>Focus</button>
     */
    Autocomplete.prototype.focus = function () {
        if (this.input) {
            this.input.focus();
        }
    };
    /** Программно снимает фокус с автокомплита.
     * @public
     * @example
     * <Autocomplete ref={autocompleteRef} />
     * <button onClick={() => autocompleteRef.current?.blur()}>Blur</button>
     */
    Autocomplete.prototype.blur = function () {
        this.handleBlur();
    };
    Autocomplete.prototype.componentDidUpdate = function (prevProps) {
        if (prevProps.value !== this.props.value) {
            this.updateItems(this.props.value || '');
        }
    };
    Autocomplete.prototype.render = function () {
        var _this = this;
        this.styles = getStyles(this.emotion);
        return (React.createElement(ThemeContext.Consumer, null, function (theme) {
            _this.theme = getAutocompleteTheme(theme);
            return (React.createElement(ThemeContext.Provider, { value: _this.theme },
                React.createElement(CommonWrapper, __assign({ rootNodeRef: _this.setRootNode }, _this.getProps()), _this.renderMain)));
        }));
    };
    Autocomplete.prototype.renderHints = function () {
        var items = this.state.items;
        if (!this.props.value) {
            return React.createElement(MenuMessage, null, this.locale.enterValue);
        }
        if ((items === null || items === void 0 ? void 0 : items.length) === 0 && this.props.value) {
            return React.createElement(MenuMessage, null, this.locale.notFound);
        }
        if (isNullable(items) && this.props.value) {
            return React.createElement(MenuMessage, null, this.locale.updateValue);
        }
        return null;
    };
    Autocomplete.prototype.renderMenu = function () {
        var items = this.state.items;
        var _a = this.getProps(), menuPos = _a.menuPos, menuAlign = _a.menuAlign, menuMaxHeight = _a.menuMaxHeight, hasShadow = _a.hasShadow, menuWidth = _a.menuWidth, width = _a.width, preventWindowScroll = _a.preventWindowScroll, disablePortal = _a.disablePortal;
        var calculatedMenuWidth = menuWidth ? '100%' : width && getDOMRect(this.rootSpan).width;
        var menuProps = {
            ref: this.refMenu,
            maxHeight: menuMaxHeight,
            hasShadow: false,
            hasMargin: false,
            width: calculatedMenuWidth,
            preventWindowScroll: preventWindowScroll,
        };
        if (!items || items.length === 0) {
            return null;
        }
        return (React.createElement(Popup, { opened: true, hasShadow: hasShadow, id: this.menuId, priority: ZIndex.priorities.PopupMenu, "data-tid": AutocompleteDataTids.menu, anchorElement: this.getAnchor(), disablePortal: disablePortal, width: menuWidth, minWidth: menuWidth === undefined ? '100%' : undefined, positions: getMenuPositions(menuPos, menuAlign), margin: parseInt(this.theme.menuOffsetY) - 1 },
            React.createElement(Menu, __assign({}, menuProps), this.getItems())));
    };
    Autocomplete.prototype.handleMenuItemClick = function (i) {
        var _this = this;
        return function (event) { return _this.handleItemClick(event, i); };
    };
    Autocomplete.prototype.handleItemClick = function (event, index) {
        if (event.button) {
            return;
        }
        event.preventDefault();
        this.choose(index);
    };
    Autocomplete.prototype.choose = function (index) {
        var _this = this;
        if (!this.state.items) {
            return;
        }
        var value = this.state.items[index];
        this.opened = false;
        this.setState({
            selected: -1,
            items: null,
        });
        this.fireChange(value);
        // NOTE: этот таймаут - костыль. Проблема в старом ReactInputMask, он сеттит пустой value при потере фокуса.
        // Можно будет убрать после полного перехода на MaskedInput
        setTimeout(function () {
            _this.blur();
        }, 0);
    };
    Autocomplete.prototype.updateItems = function (value) {
        var _this = this;
        if (!this.opened) {
            return;
        }
        var pattern = value.trim();
        var source = this.props.source;
        if (!source) {
            return;
        }
        var promise;
        this.requestId += 1;
        var expectingId = this.requestId;
        if (typeof source === 'function') {
            promise = source(pattern);
        }
        else {
            promise = match(pattern, source);
        }
        promise.then(function (items) {
            if (_this.opened && expectingId === _this.requestId) {
                _this.setState({
                    items: items,
                    selected: -1,
                });
            }
        });
    };
    Autocomplete.prototype.fireChange = function (value) {
        if (this.props.onValueChange) {
            this.props.onValueChange(value);
        }
    };
    var Autocomplete_1;
    Autocomplete.__KONTUR_REACT_UI__ = 'Autocomplete';
    Autocomplete.displayName = 'Autocomplete';
    Autocomplete.defaultProps = {
        renderItem: renderItem,
        disablePortal: false,
        hasShadow: true,
        menuMaxHeight: 300,
        preventWindowScroll: true,
    };
    Autocomplete = Autocomplete_1 = __decorate([
        withRenderEnvironment,
        responsiveLayout,
        rootNode,
        locale('Autocomplete', AutocompleteLocaleHelper),
        withSize
    ], Autocomplete);
    return Autocomplete;
}(React.Component));
export { Autocomplete };
//# sourceMappingURL=Autocomplete.js.map