/*
 * Copyright 2017 Palantir Technologies, Inc. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
import { __assign, __extends, __rest } from "tslib";
import classNames from "classnames";
import * as React from "react";
import { DISPLAYNAME_PREFIX, getRef, InputGroup, isRefObject, Keys, Popover, PopoverInteractionKind, Position, Utils, } from "@blueprintjs/core";
import { Classes } from "../../common";
import { QueryList } from "../query-list/queryList";
var Suggest = /** @class */ (function (_super) {
    __extends(Suggest, _super);
    function Suggest() {
        var _a;
        var _this = _super.apply(this, arguments) || this;
        _this.state = {
            isOpen: (_this.props.popoverProps != null && _this.props.popoverProps.isOpen) || false,
            selectedItem: _this.getInitialSelectedItem(),
        };
        _this.TypedQueryList = QueryList.ofType();
        _this.inputEl = null;
        _this.queryList = null;
        _this.refHandlers = {
            input: isRefObject((_a = _this.props.inputProps) === null || _a === void 0 ? void 0 : _a.inputRef)
                ? (_this.inputEl = _this.props.inputProps.inputRef)
                : function (ref) {
                    var _a, _b;
                    _this.inputEl = ref;
                    (_b = (_a = _this.props.inputProps) === null || _a === void 0 ? void 0 : _a.inputRef) === null || _b === void 0 ? void 0 : _b(ref);
                },
            queryList: function (ref) { return (_this.queryList = ref); },
        };
        _this.renderQueryList = function (listProps) {
            var _a = _this.props, fill = _a.fill, _b = _a.inputProps, inputProps = _b === void 0 ? {} : _b, _c = _a.popoverProps, popoverProps = _c === void 0 ? {} : _c;
            var _d = _this.state, isOpen = _d.isOpen, selectedItem = _d.selectedItem;
            var handleKeyDown = listProps.handleKeyDown, handleKeyUp = listProps.handleKeyUp;
            var _e = inputProps.autoComplete, autoComplete = _e === void 0 ? "off" : _e, _f = inputProps.placeholder, placeholder = _f === void 0 ? "Search..." : _f;
            var selectedItemText = selectedItem ? _this.props.inputValueRenderer(selectedItem) : "";
            // placeholder shows selected item while open.
            var inputPlaceholder = isOpen && selectedItemText ? selectedItemText : placeholder;
            // value shows query when open, and query remains when closed if nothing is selected.
            // if resetOnClose is enabled, then hide query when not open. (see handlePopoverOpening)
            var inputValue = isOpen
                ? listProps.query
                : selectedItemText || (_this.props.resetOnClose ? "" : listProps.query);
            if (fill) {
                popoverProps.fill = true;
                inputProps.fill = true;
            }
            return (React.createElement(Popover, __assign({ autoFocus: false, enforceFocus: false, isOpen: isOpen, position: Position.BOTTOM_LEFT }, popoverProps, { className: classNames(listProps.className, popoverProps.className), interactionKind: PopoverInteractionKind.CLICK, onInteraction: _this.handlePopoverInteraction, popoverClassName: classNames(Classes.SELECT_POPOVER, popoverProps.popoverClassName), onOpening: _this.handlePopoverOpening, onOpened: _this.handlePopoverOpened }),
                React.createElement(InputGroup, __assign({ autoComplete: autoComplete, disabled: _this.props.disabled }, inputProps, { inputRef: _this.refHandlers.input, onChange: listProps.handleQueryChange, onFocus: _this.handleInputFocus, onKeyDown: _this.getTargetKeyDownHandler(handleKeyDown), onKeyUp: _this.getTargetKeyUpHandler(handleKeyUp), placeholder: inputPlaceholder, value: inputValue })),
                React.createElement("div", { onKeyDown: handleKeyDown, onKeyUp: handleKeyUp }, listProps.itemList)));
        };
        _this.selectText = function () {
            // wait until the input is properly focused to select the text inside of it
            requestAnimationFrame(function () {
                if (_this.inputEl != null) {
                    var input = getRef(_this.inputEl);
                    input.setSelectionRange(0, input.value.length);
                }
            });
        };
        _this.handleInputFocus = function (event) {
            _this.selectText();
            // TODO can we leverage Popover.openOnTargetFocus for this?
            if (!_this.props.openOnKeyDown) {
                _this.setState({ isOpen: true });
            }
            Utils.safeInvokeMember(_this.props.inputProps, "onFocus", event);
        };
        _this.handleItemSelect = function (item, event) {
            var nextOpenState;
            if (!_this.props.closeOnSelect) {
                if (_this.inputEl != null) {
                    getRef(_this.inputEl).focus();
                }
                _this.selectText();
                nextOpenState = true;
            }
            else {
                if (_this.inputEl != null) {
                    getRef(_this.inputEl).blur();
                }
                nextOpenState = false;
            }
            // the internal state should only change when uncontrolled.
            if (_this.props.selectedItem === undefined) {
                _this.setState({
                    isOpen: nextOpenState,
                    selectedItem: item,
                });
            }
            else {
                // otherwise just set the next open state.
                _this.setState({ isOpen: nextOpenState });
            }
            Utils.safeInvoke(_this.props.onItemSelect, item, event);
        };
        // Popover interaction kind is CLICK, so this only handles click events.
        // Note that we defer to the next animation frame in order to get the latest document.activeElement
        _this.handlePopoverInteraction = function (nextOpenState) {
            return requestAnimationFrame(function () {
                var isInputFocused = getRef(_this.inputEl) === document.activeElement;
                if (_this.inputEl != null && !isInputFocused) {
                    // the input is no longer focused, we should close the popover
                    _this.setState({ isOpen: false });
                }
                Utils.safeInvokeMember(_this.props.popoverProps, "onInteraction", nextOpenState);
            });
        };
        _this.handlePopoverOpening = function (node) {
            // reset query before opening instead of when closing to prevent flash of unfiltered items.
            // this is a limitation of the interactions between QueryList state and Popover transitions.
            if (_this.props.resetOnClose && _this.queryList) {
                _this.queryList.setQuery("", true);
            }
            Utils.safeInvokeMember(_this.props.popoverProps, "onOpening", node);
        };
        _this.handlePopoverOpened = function (node) {
            // scroll active item into view after popover transition completes and all dimensions are stable.
            if (_this.queryList != null) {
                _this.queryList.scrollActiveItemIntoView();
            }
            Utils.safeInvokeMember(_this.props.popoverProps, "onOpened", node);
        };
        _this.getTargetKeyDownHandler = function (handleQueryListKeyDown) {
            return function (evt) {
                var which = evt.which;
                if (which === Keys.ESCAPE || which === Keys.TAB) {
                    if (_this.inputEl != null) {
                        getRef(_this.inputEl).blur();
                    }
                    _this.setState({ isOpen: false });
                }
                else if (_this.props.openOnKeyDown &&
                    which !== Keys.BACKSPACE &&
                    which !== Keys.ARROW_LEFT &&
                    which !== Keys.ARROW_RIGHT) {
                    _this.setState({ isOpen: true });
                }
                if (_this.state.isOpen) {
                    Utils.safeInvoke(handleQueryListKeyDown, evt);
                }
                Utils.safeInvokeMember(_this.props.inputProps, "onKeyDown", evt);
            };
        };
        _this.getTargetKeyUpHandler = function (handleQueryListKeyUp) {
            return function (evt) {
                if (_this.state.isOpen) {
                    Utils.safeInvoke(handleQueryListKeyUp, evt);
                }
                Utils.safeInvokeMember(_this.props.inputProps, "onKeyUp", evt);
            };
        };
        return _this;
    }
    Suggest.ofType = function () {
        return Suggest;
    };
    Suggest.prototype.render = function () {
        var _a;
        // omit props specific to this component, spread the rest.
        var _b = this.props, disabled = _b.disabled, inputProps = _b.inputProps, popoverProps = _b.popoverProps, restProps = __rest(_b, ["disabled", "inputProps", "popoverProps"]);
        return (React.createElement(this.TypedQueryList, __assign({}, restProps, { initialActiveItem: (_a = this.props.selectedItem) !== null && _a !== void 0 ? _a : undefined, onItemSelect: this.handleItemSelect, ref: this.refHandlers.queryList, renderer: this.renderQueryList })));
    };
    Suggest.prototype.componentDidUpdate = function (_prevProps, prevState) {
        var _this = this;
        var _a, _b;
        // If the selected item prop changes, update the underlying state.
        if (this.props.selectedItem !== undefined && this.props.selectedItem !== this.state.selectedItem) {
            this.setState({ selectedItem: this.props.selectedItem });
        }
        if (this.state.isOpen === false && prevState.isOpen === true) {
            // just closed, likely by keyboard interaction
            // wait until the transition ends so there isn't a flash of content in the popover
            setTimeout(function () {
                _this.maybeResetActiveItemToSelectedItem();
            }, (_b = (_a = this.props.popoverProps) === null || _a === void 0 ? void 0 : _a.transitionDuration) !== null && _b !== void 0 ? _b : Popover.defaultProps.transitionDuration);
        }
        if (this.state.isOpen && !prevState.isOpen && this.queryList != null) {
            this.queryList.scrollActiveItemIntoView();
        }
    };
    Suggest.prototype.getInitialSelectedItem = function () {
        // controlled > uncontrolled > default
        if (this.props.selectedItem !== undefined) {
            return this.props.selectedItem;
        }
        else if (this.props.defaultSelectedItem !== undefined) {
            return this.props.defaultSelectedItem;
        }
        else {
            return null;
        }
    };
    Suggest.prototype.maybeResetActiveItemToSelectedItem = function () {
        var _a;
        var shouldResetActiveItemToSelectedItem = this.props.activeItem === undefined && this.state.selectedItem !== null && !this.props.resetOnSelect;
        if (this.queryList !== null && shouldResetActiveItemToSelectedItem) {
            this.queryList.setActiveItem((_a = this.props.selectedItem) !== null && _a !== void 0 ? _a : this.state.selectedItem);
        }
    };
    Suggest.displayName = DISPLAYNAME_PREFIX + ".Suggest";
    Suggest.defaultProps = {
        closeOnSelect: true,
        fill: false,
        openOnKeyDown: false,
        resetOnClose: false,
    };
    return Suggest;
}(React.PureComponent));
export { Suggest };
//# sourceMappingURL=suggest.js.map