"use strict";
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 __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
    return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (g && (g = 0, op[0] && (_ = 0)), _) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
var react_1 = __importDefault(require("react"));
var react_2 = require("@testing-library/react");
var user_event_1 = __importDefault(require("@testing-library/user-event"));
var test_utils_1 = require("../test-utils");
var mdm_sdk_1 = require("@reltio/mdm-sdk");
var TypeaheadEditor_1 = require("./TypeaheadEditor");
jest.mock('@reltio/mdm-sdk', function () { return (__assign(__assign({}, jest.requireActual('@reltio/mdm-sdk')), { debounce: jest.fn() })); });
var originalDebounce = jest.requireActual('@reltio/mdm-sdk').debounce;
var fakeDebounce = function (func) { return func; };
var setUp = function (props) {
    var user = user_event_1.default.setup();
    return __assign(__assign({}, (0, react_2.render)(react_1.default.createElement(TypeaheadEditor_1.TypeaheadEditor, __assign({}, props)))), { user: user });
};
describe('TypeaheadEditor', function () {
    var triggerKeyDown = function (el, options) {
        // eslint-disable-next-line testing-library/prefer-user-event
        react_2.fireEvent.keyDown(el, options);
    };
    var createGetSuggestions = function (suggestions) {
        var getSuggestions = function (value, pageSize, pageNumber) {
            if (pageNumber === void 0) { pageNumber = 1; }
            var start = (pageNumber - 1) * pageSize;
            var end = start + pageSize;
            return Promise.resolve(suggestions.filter(function (item) { return item.startsWith(value); }).slice(start, end));
        };
        return jest.fn(getSuggestions);
    };
    var defaultSuggestions = ['cat', 'dog', 'turtle', 'elephant'];
    var getSuggestions = createGetSuggestions(defaultSuggestions);
    var defaultMultipleProps = {
        getSuggestions: getSuggestions,
        value: [],
        multiple: true,
        onChange: jest.fn()
    };
    var defaultSingleProps = {
        getSuggestions: getSuggestions,
        value: '',
        multiple: false,
        onChange: jest.fn()
    };
    beforeEach(function () {
        mdm_sdk_1.debounce.mockImplementation(fakeDebounce);
    });
    afterEach(function () {
        jest.clearAllMocks();
    });
    it('suggestions pagination should work correctly', function () { return __awaiter(void 0, void 0, void 0, function () {
        var suggestions, getSuggestions, props, user, input;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    suggestions = [
                        '1',
                        '12',
                        '123',
                        '1234',
                        '12345',
                        '123456',
                        '1234567',
                        '12345678',
                        '123456789',
                        '123456789q',
                        '123456789qw',
                        '123456789qwe',
                        '123456789qwer',
                        '123456789qwert',
                        '123456789qwerty'
                    ];
                    getSuggestions = createGetSuggestions(suggestions);
                    props = __assign(__assign({}, defaultSingleProps), { max: 5, getSuggestions: getSuggestions });
                    user = setUp(props).user;
                    input = react_2.screen.getByRole('textbox');
                    return [4 /*yield*/, user.click(input)];
                case 1:
                    _a.sent();
                    return [4 /*yield*/, (0, react_2.waitFor)(function () { return suggestions.slice(0, 5).forEach(function (item) { return react_2.screen.getByText(item); }); })];
                case 2:
                    _a.sent();
                    expect(react_2.screen.getAllByRole('option')).toHaveLength(5);
                    return [4 /*yield*/, user.click(react_2.screen.getByText('Load more'))];
                case 3:
                    _a.sent();
                    return [4 /*yield*/, (0, react_2.waitFor)(function () { return suggestions.slice(0, 10).forEach(function (item) { return react_2.screen.getByText(item); }); })];
                case 4:
                    _a.sent();
                    expect(react_2.screen.getAllByRole('option')).toHaveLength(10);
                    return [4 /*yield*/, user.click(react_2.screen.getByText('Load more'))];
                case 5:
                    _a.sent();
                    return [4 /*yield*/, (0, react_2.waitFor)(function () { return suggestions.slice(0, 15).forEach(function (item) { return react_2.screen.getByText(item); }); })];
                case 6:
                    _a.sent();
                    expect(react_2.screen.getAllByRole('option')).toHaveLength(15);
                    expect(react_2.screen.queryByText('Load more')).not.toBeInTheDocument();
                    return [4 /*yield*/, user.type(input, '123')];
                case 7:
                    _a.sent();
                    return [4 /*yield*/, (0, react_2.waitFor)(function () { return suggestions.slice(2, 7).forEach(function (item) { return react_2.screen.getByText(item); }); })];
                case 8:
                    _a.sent();
                    expect(react_2.screen.getAllByRole('option')).toHaveLength(5);
                    react_2.screen.getByText('Load more');
                    return [2 /*return*/];
            }
        });
    }); });
    it('should render suggestions correctly', function () { return __awaiter(void 0, void 0, void 0, function () {
        var user;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    user = setUp(defaultSingleProps).user;
                    return [4 /*yield*/, user.click(react_2.screen.getByRole('textbox'))];
                case 1:
                    _a.sent();
                    return [4 /*yield*/, (0, react_2.waitFor)(function () { return expect(react_2.screen.getAllByRole('option')).toHaveLength(4); })];
                case 2:
                    _a.sent();
                    defaultSuggestions.forEach(function (item) { return react_2.screen.getByText(item); });
                    expect(react_2.screen.queryByText('Load more')).not.toBeInTheDocument();
                    return [2 /*return*/];
            }
        });
    }); });
    it('should render placeholder if suggestions is empty if text field is focused', function () { return __awaiter(void 0, void 0, void 0, function () {
        var user, input;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    user = setUp(defaultSingleProps).user;
                    input = react_2.screen.getByRole('textbox');
                    return [4 /*yield*/, user.click(input)];
                case 1:
                    _a.sent();
                    return [4 /*yield*/, user.type(input, '123456789')];
                case 2:
                    _a.sent();
                    return [4 /*yield*/, react_2.screen.findByText('No results found')];
                case 3:
                    _a.sent();
                    react_2.fireEvent.blur(input);
                    expect(react_2.screen.queryByText('No results found')).not.toBeInTheDocument();
                    return [2 /*return*/];
            }
        });
    }); });
    it('should filter suggestions by input value with debounce', function () { return __awaiter(void 0, void 0, void 0, function () {
        var user, input;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    mdm_sdk_1.debounce.mockImplementation(originalDebounce);
                    user = setUp(defaultSingleProps).user;
                    input = react_2.screen.getByRole('textbox');
                    return [4 /*yield*/, user.click(input)];
                case 1:
                    _a.sent();
                    return [4 /*yield*/, user.type(input, 'elepha')];
                case 2:
                    _a.sent();
                    return [4 /*yield*/, (0, react_2.waitFor)(function () { return expect(react_2.screen.getAllByRole('option')).toHaveLength(1); })];
                case 3:
                    _a.sent();
                    react_2.screen.getByText('elephant');
                    expect(getSuggestions).toHaveBeenCalledTimes(2);
                    expect(getSuggestions).toHaveBeenCalledWith('', 51);
                    expect(getSuggestions).toHaveBeenCalledWith('elepha', 51);
                    return [2 /*return*/];
            }
        });
    }); });
    it('should catch error in getSuggestions', function () { return __awaiter(void 0, void 0, void 0, function () {
        var getSuggestions, user, input;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    getSuggestions = function () { return Promise.reject({ errorCode: 403, errorMessage: 'Access is denied' }); };
                    user = setUp(__assign(__assign({}, defaultSingleProps), { getSuggestions: getSuggestions })).user;
                    input = react_2.screen.getByRole('textbox');
                    return [4 /*yield*/, user.click(input)];
                case 1:
                    _a.sent();
                    return [4 /*yield*/, user.type(input, 'e')];
                case 2:
                    _a.sent();
                    return [4 /*yield*/, react_2.screen.findByText('No results found')];
                case 3:
                    _a.sent();
                    return [2 /*return*/];
            }
        });
    }); });
    describe('single mode', function () {
        it('should set input value after click on suggestion item', function () { return __awaiter(void 0, void 0, void 0, function () {
            var user, input;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        user = setUp(defaultSingleProps).user;
                        input = react_2.screen.getByRole('textbox');
                        expect(input).toHaveAttribute('value', '');
                        return [4 /*yield*/, user.click(input)];
                    case 1:
                        _a.sent();
                        return [4 /*yield*/, user.click(react_2.screen.getByText('cat'))];
                    case 2:
                        _a.sent();
                        expect(input).toHaveAttribute('value', 'cat');
                        return [2 /*return*/];
                }
            });
        }); });
        it('should call onChange on "Enter" key press', function () { return __awaiter(void 0, void 0, void 0, function () {
            var onChange, user, input;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        onChange = defaultSingleProps.onChange;
                        user = setUp(defaultSingleProps).user;
                        input = react_2.screen.getByRole('textbox');
                        return [4 /*yield*/, user.click(input)];
                    case 1:
                        _a.sent();
                        return [4 /*yield*/, user.type(input, '123')];
                    case 2:
                        _a.sent();
                        expect(onChange).not.toHaveBeenCalled();
                        return [4 /*yield*/, user.type(input, '456')];
                    case 3:
                        _a.sent();
                        expect(onChange).not.toHaveBeenCalled();
                        return [4 /*yield*/, user.type(input, '789')];
                    case 4:
                        _a.sent();
                        return [4 /*yield*/, user.keyboard('{Enter}')];
                    case 5:
                        _a.sent();
                        expect(onChange).toHaveBeenCalledTimes(1);
                        expect(onChange).toHaveBeenCalledWith('123456789');
                        return [2 /*return*/];
                }
            });
        }); });
        it('should clear input field on "Escape" key press', function () { return __awaiter(void 0, void 0, void 0, function () {
            var user, input;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        user = setUp(defaultSingleProps).user;
                        input = react_2.screen.getByRole('textbox');
                        return [4 /*yield*/, user.click(input)];
                    case 1:
                        _a.sent();
                        return [4 /*yield*/, user.type(input, '123456789')];
                    case 2:
                        _a.sent();
                        return [4 /*yield*/, react_2.screen.findByText('No results found')];
                    case 3:
                        _a.sent();
                        expect(input).toHaveAttribute('value', '123456789');
                        triggerKeyDown(input, { keyCode: 27 });
                        expect(input).toHaveAttribute('value', '');
                        return [4 /*yield*/, (0, react_2.waitFor)(function () { return expect(react_2.screen.getAllByRole('option')).toHaveLength(4); })];
                    case 4:
                        _a.sent();
                        return [2 /*return*/];
                }
            });
        }); });
        it('should set input value after select suggestion item using keyboard', function () { return __awaiter(void 0, void 0, void 0, function () {
            var user, input;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        user = setUp(defaultSingleProps).user;
                        input = react_2.screen.getByRole('textbox');
                        return [4 /*yield*/, user.click(input)];
                    case 1:
                        _a.sent();
                        return [4 /*yield*/, react_2.screen.findByRole('tooltip')];
                    case 2:
                        _a.sent();
                        triggerKeyDown(input, { keyCode: 40 });
                        expect(react_2.screen.getByRole('option', { selected: true })).toHaveTextContent('cat');
                        triggerKeyDown(input, { keyCode: 40 });
                        expect(react_2.screen.getByRole('option', { selected: true })).toHaveTextContent('dog');
                        triggerKeyDown(input, { keyCode: 13 });
                        expect(react_2.screen.queryByRole('tooltip')).not.toBeInTheDocument();
                        expect(input).toHaveAttribute('value', 'dog');
                        return [2 /*return*/];
                }
            });
        }); });
        it('should work correctly if value is undefined', function () { return __awaiter(void 0, void 0, void 0, function () {
            var props;
            return __generator(this, function (_a) {
                props = __assign(__assign({}, defaultSingleProps), { value: undefined });
                setUp(props);
                expect(react_2.screen.getByRole('textbox')).toHaveAttribute('value', '');
                return [2 /*return*/];
            });
        }); });
    });
    describe('multiple mode', function () {
        it('should render chips correctly', function () {
            var values = ['value 1', 'value 2'];
            var props = __assign(__assign({}, defaultMultipleProps), { value: values });
            setUp(props);
            expect(react_2.screen.getByRole('textbox')).toHaveAttribute('value', '');
            values.forEach(function (value) { return react_2.screen.getByText(value); });
        });
        it('should remove chips correctly', function () { return __awaiter(void 0, void 0, void 0, function () {
            var values, props, user, chips;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        values = ['value 1', 'value 2'];
                        props = __assign(__assign({}, defaultMultipleProps), { value: values });
                        user = setUp(props).user;
                        chips = (0, react_2.within)(react_2.screen.getByRole('combobox')).getAllByRole('button');
                        return [4 /*yield*/, user.click((0, test_utils_1.getMuiIconByName)('Cancel', chips[0]))];
                    case 1:
                        _a.sent();
                        expect(props.onChange).toHaveBeenNthCalledWith(1, ['value 2']);
                        return [4 /*yield*/, user.click((0, test_utils_1.getMuiIconByName)('Cancel', chips[1]))];
                    case 2:
                        _a.sent();
                        expect(props.onChange).toHaveBeenNthCalledWith(2, ['value 1']);
                        return [2 /*return*/];
                }
            });
        }); });
        it('should add chips correctly after type value and press "enter"', function () { return __awaiter(void 0, void 0, void 0, function () {
            var values, props, user, input;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        values = ['value 1', 'value 2'];
                        props = __assign(__assign({}, defaultMultipleProps), { value: values });
                        user = setUp(props).user;
                        input = react_2.screen.getByRole('textbox');
                        return [4 /*yield*/, user.type(input, 'value 3')];
                    case 1:
                        _a.sent();
                        expect(input).toHaveAttribute('value', 'value 3');
                        return [4 /*yield*/, user.keyboard('{Enter}')];
                    case 2:
                        _a.sent();
                        expect(input).toHaveAttribute('value', '');
                        expect(props.onChange).toHaveBeenCalledWith(['value 1', 'value 2', 'value 3']);
                        return [2 /*return*/];
                }
            });
        }); });
        it('should add chip correctly after click on suggestion item', function () { return __awaiter(void 0, void 0, void 0, function () {
            var values, props, user, input;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        values = ['value 1', 'value 2'];
                        props = __assign(__assign({}, defaultMultipleProps), { value: values });
                        user = setUp(props).user;
                        input = react_2.screen.getByRole('textbox');
                        return [4 /*yield*/, user.click(input)];
                    case 1:
                        _a.sent();
                        expect(react_2.screen.getByRole('tooltip')).toBeInTheDocument();
                        return [4 /*yield*/, user.click(react_2.screen.getByText('cat'))];
                    case 2:
                        _a.sent();
                        expect(props.onChange).toHaveBeenCalledWith(['value 1', 'value 2', 'cat']);
                        return [2 /*return*/];
                }
            });
        }); });
        it('should add chip correctly on input blur', function () { return __awaiter(void 0, void 0, void 0, function () {
            var values, props, user, input;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        values = ['value 1', 'value 2'];
                        props = __assign(__assign({}, defaultMultipleProps), { value: values });
                        user = setUp(props).user;
                        input = react_2.screen.getByRole('textbox');
                        return [4 /*yield*/, user.type(input, 'value 3')];
                    case 1:
                        _a.sent();
                        expect(input).toHaveAttribute('value', 'value 3');
                        return [4 /*yield*/, user.tab()];
                    case 2:
                        _a.sent(); // simulating input blur
                        expect(input).toHaveAttribute('value', '');
                        expect(props.onChange).toHaveBeenCalledWith(['value 1', 'value 2', 'value 3']);
                        return [2 /*return*/];
                }
            });
        }); });
        it('should add chip correctly after select suggestion item using keyboard', function () { return __awaiter(void 0, void 0, void 0, function () {
            var values, props, user, input;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        values = ['value 1', 'value 2'];
                        props = __assign(__assign({}, defaultMultipleProps), { value: values });
                        user = setUp(props).user;
                        input = react_2.screen.getByRole('textbox');
                        return [4 /*yield*/, user.click(input)];
                    case 1:
                        _a.sent();
                        expect(react_2.screen.getByRole('tooltip')).toBeInTheDocument();
                        triggerKeyDown(input, { keyCode: 40 });
                        expect(react_2.screen.getByRole('option', { selected: true })).toHaveTextContent('cat');
                        triggerKeyDown(input, { keyCode: 40 });
                        expect(react_2.screen.getByRole('option', { selected: true })).toHaveTextContent('dog');
                        triggerKeyDown(input, { keyCode: 13 });
                        expect(react_2.screen.queryByRole('tooltip')).not.toBeInTheDocument();
                        expect(props.onChange).toHaveBeenCalledWith(['value 1', 'value 2', 'dog']);
                        return [2 /*return*/];
                }
            });
        }); });
        it('should clear input value on press "Escape" key', function () { return __awaiter(void 0, void 0, void 0, function () {
            var user, input;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        user = setUp(defaultMultipleProps).user;
                        input = react_2.screen.getByRole('textbox');
                        return [4 /*yield*/, user.click(input)];
                    case 1:
                        _a.sent();
                        return [4 /*yield*/, user.type(input, '123456789')];
                    case 2:
                        _a.sent();
                        return [4 /*yield*/, react_2.screen.findByText('No results found')];
                    case 3:
                        _a.sent();
                        expect(input).toHaveAttribute('value', '123456789');
                        triggerKeyDown(input, { keyCode: 27 });
                        expect(input).toHaveAttribute('value', '');
                        return [4 /*yield*/, (0, react_2.waitFor)(function () { return expect(react_2.screen.getAllByRole('option')).toHaveLength(4); })];
                    case 4:
                        _a.sent();
                        return [2 /*return*/];
                }
            });
        }); });
        it('should work correctly if value is undefined', function () { return __awaiter(void 0, void 0, void 0, function () {
            var props, user, input;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        props = __assign(__assign({}, defaultMultipleProps), { value: undefined });
                        user = setUp(props).user;
                        expect(react_2.screen.queryByRole('button')).not.toBeInTheDocument();
                        input = react_2.screen.getByRole('textbox');
                        expect(input).toHaveAttribute('value', '');
                        return [4 /*yield*/, user.type(input, 'new role{Enter}')];
                    case 1:
                        _a.sent();
                        expect(props.onChange).toHaveBeenCalledWith(['new role']);
                        return [2 /*return*/];
                }
            });
        }); });
        it('should work correctly if value is not array', function () { return __awaiter(void 0, void 0, void 0, function () {
            var props, user;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        props = __assign(__assign({}, defaultMultipleProps), { value: 'value 1' });
                        user = setUp(props).user;
                        react_2.screen.getByText('value 1');
                        return [4 /*yield*/, user.type(react_2.screen.getByRole('textbox'), 'value 2{Enter}')];
                    case 1:
                        _a.sent();
                        expect(props.onChange).toHaveBeenCalledWith(['value 1', 'value 2']);
                        return [2 /*return*/];
                }
            });
        }); });
    });
    it('should work correctly after switching between multiple and single mode', function () { return __awaiter(void 0, void 0, void 0, function () {
        var _a, rerender, user, input;
        return __generator(this, function (_b) {
            switch (_b.label) {
                case 0:
                    _a = setUp(defaultMultipleProps), rerender = _a.rerender, user = _a.user;
                    rerender(react_1.default.createElement(TypeaheadEditor_1.TypeaheadEditor, __assign({}, defaultSingleProps)));
                    input = react_2.screen.getByRole('textbox');
                    return [4 /*yield*/, user.click(input)];
                case 1:
                    _b.sent();
                    return [4 /*yield*/, user.click(react_2.screen.getByText('cat'))];
                case 2:
                    _b.sent();
                    expect(input).toHaveAttribute('value', 'cat');
                    expect(input).toHaveFocus();
                    return [2 /*return*/];
            }
        });
    }); });
});
