"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 __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
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 __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;
};
var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
    if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
        if (ar || !(i in from)) {
            if (!ar) ar = Array.prototype.slice.call(from, 0, i);
            ar[i] = from[i];
        }
    }
    return to.concat(ar || Array.prototype.slice.call(from));
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
var react_1 = __importStar(require("react"));
var classnames_1 = __importDefault(require("classnames"));
var jsdom_testing_mocks_1 = require("jsdom-testing-mocks");
var react_2 = require("@testing-library/react");
var user_event_1 = __importDefault(require("@testing-library/user-event"));
var ReltioGridLayout_1 = __importDefault(require("./ReltioGridLayout"));
Object.defineProperty(HTMLElement.prototype, 'offsetParent', {
    get: function () {
        return this.parentNode;
    }
});
describe('ReactGridLayout tests', function () {
    var resizeObserver = (0, jsdom_testing_mocks_1.mockResizeObserver)();
    var DefaultLayoutItem = (0, react_1.forwardRef)(function (_a, ref) {
        var _b;
        var children = _a.children, layoutItemConfig = _a.layoutItemConfig, views = _a.views, className = _a.className, AutosizeComponent = _a.AutosizeComponent, onRemove = _a.onRemove, isFullscreen = _a.isFullscreen, onToggleFullscreen = _a.onToggleFullscreen, props = __rest(_a, ["children", "layoutItemConfig", "views", "className", "AutosizeComponent", "onRemove", "isFullscreen", "onToggleFullscreen"]);
        var itemId = layoutItemConfig.i;
        return (react_1.default.createElement("div", __assign({}, props, { ref: ref, "data-reltio-id": "layout-item-".concat(itemId), className: (0, classnames_1.default)(className, { isFullscreen: isFullscreen }) }),
            AutosizeComponent,
            react_1.default.createElement("button", { onClick: function () { return onToggleFullscreen(itemId); }, "data-reltio-id": "fullscreen-button" }),
            react_1.default.createElement("button", { onClick: function () { return onRemove(itemId); }, "data-reltio-id": "remove-button" }),
            react_1.default.createElement("span", null, (_b = views.find(function (_a) {
                var id = _a.id;
                return id === itemId;
            })) === null || _b === void 0 ? void 0 : _b.title),
            children));
    });
    DefaultLayoutItem.displayName = 'DefaultLayoutItem';
    var defaultProps = {
        views: [
            { id: 'MyDashboard', component: 'DashboardFacet', text: '123', title: 'My Title' },
            { id: 'MyProfiles', component: 'ProfilesFacet', text: '234', title: 'Profiles Title' }
        ],
        layout: [
            { x: 0, y: 0, width: 2, height: 5, minWidth: 2, id: 'MyDashboard' },
            { x: 0, y: 5, width: 2, height: 5, minWidth: 2, id: 'MyProfile', autosizing: true }
        ],
        LayoutItem: DefaultLayoutItem
    };
    var setUp = function () {
        var args_1 = [];
        for (var _i = 0; _i < arguments.length; _i++) {
            args_1[_i] = arguments[_i];
        }
        return __awaiter(void 0, __spreadArray([], args_1, true), void 0, function (props) {
            var user, Providers, renderer, grid;
            if (props === void 0) { props = {}; }
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        user = user_event_1.default.setup();
                        Providers = function (_a) {
                            var children = _a.children;
                            return (react_1.default.createElement("div", null,
                                react_1.default.createElement("span", { "data-reltio-id": "draggable-element", draggable: "true" }),
                                react_1.default.createElement("div", { "data-reltio-id": "grid-wrapper" }, children)));
                        };
                        renderer = (0, react_2.render)(react_1.default.createElement(ReltioGridLayout_1.default, __assign({}, defaultProps, props)), { wrapper: Providers });
                        grid = react_2.screen.getByTestId('grid-wrapper');
                        resizeObserver.mockElementSize(grid, {
                            contentBoxSize: { inlineSize: 400, blockSize: 300 }
                        });
                        (0, react_2.act)(function () {
                            resizeObserver.resize();
                        });
                        return [4 /*yield*/, (0, react_2.waitFor)(function () { return expect(renderer.container.querySelector('.react-grid-layout')).toBeInTheDocument(); })];
                    case 1:
                        _a.sent();
                        return [2 /*return*/, __assign(__assign({}, renderer), { user: user, grid: grid })];
                }
            });
        });
    };
    it('should add isResizing className to current resizing item', function () { return __awaiter(void 0, void 0, void 0, function () {
        var _a, container, user, resizableHandle;
        return __generator(this, function (_b) {
            switch (_b.label) {
                case 0: return [4 /*yield*/, setUp({
                        views: __spreadArray(__spreadArray([], defaultProps.views, true), [{ id: 'ProfileStats', component: 'ProfileStatsFacet', title: 'Stats' }], false),
                        layout: __spreadArray(__spreadArray([], defaultProps.layout, true), [{ x: 0, y: 5, width: 2, height: 5, minWidth: 2, id: 'ProfileStats' }], false)
                    })];
                case 1:
                    _a = _b.sent(), container = _a.container, user = _a.user;
                    resizableHandle = container.querySelector('.react-resizable-handle');
                    return [4 /*yield*/, user.pointer({ target: resizableHandle, keys: '[MouseLeft>]' })];
                case 2:
                    _b.sent();
                    expect(react_2.screen.getByTestId('layout-item-MyDashboard')).toHaveClass('isResizing');
                    expect(react_2.screen.getByTestId('layout-item-ProfileStats')).not.toHaveClass('isResizing');
                    return [4 /*yield*/, user.pointer({ target: resizableHandle, keys: '[/MouseLeft]' })];
                case 3:
                    _b.sent();
                    expect(react_2.screen.getByTestId('layout-item-MyDashboard')).not.toHaveClass('isResizing');
                    expect(react_2.screen.getByTestId('layout-item-ProfileStats')).not.toHaveClass('isResizing');
                    return [2 /*return*/];
            }
        });
    }); });
    it('should render items correctly', function () { return __awaiter(void 0, void 0, void 0, function () {
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0: return [4 /*yield*/, setUp()];
                case 1:
                    _a.sent();
                    expect(react_2.screen.getByTestId('layout-item-MyDashboard')).toBeInTheDocument();
                    expect(react_2.screen.getByText('My Title')).toBeInTheDocument();
                    return [2 /*return*/];
            }
        });
    }); });
    it('should call onLayoutChanged with layout items', function () { return __awaiter(void 0, void 0, void 0, function () {
        var onLayoutChangedSpy, _a, user, container, resizableHandle;
        return __generator(this, function (_b) {
            switch (_b.label) {
                case 0:
                    onLayoutChangedSpy = jest.fn();
                    return [4 /*yield*/, setUp({ onLayoutChanged: onLayoutChangedSpy })];
                case 1:
                    _a = _b.sent(), user = _a.user, container = _a.container;
                    resizableHandle = container.querySelector('.react-resizable-handle');
                    return [4 /*yield*/, user.pointer([
                            { target: resizableHandle, keys: '[MouseLeft>]' },
                            { coords: { x: 100, y: 100 } },
                            { target: resizableHandle, keys: '[/MouseLeft]' }
                        ])];
                case 2:
                    _b.sent();
                    expect(onLayoutChangedSpy).toHaveBeenCalledTimes(2);
                    expect(onLayoutChangedSpy).toHaveBeenLastCalledWith([
                        __assign(__assign({}, defaultProps.layout[0]), { height: 7, width: 3, isStatic: false }),
                        __assign(__assign({}, defaultProps.layout[1]), { y: 7, height: 5, width: 2, isStatic: false, autosizing: true })
                    ]);
                    return [2 /*return*/];
            }
        });
    }); });
    it('should call onDrop with correctly args', function () { return __awaiter(void 0, void 0, void 0, function () {
        var onDropSpy, draggableElement, dropTarget, dragOverEvent;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    onDropSpy = jest.fn();
                    return [4 /*yield*/, setUp({ onDrop: onDropSpy, isDroppable: true })];
                case 1:
                    _a.sent();
                    draggableElement = react_2.screen.getByTestId('draggable-element');
                    dropTarget = react_2.screen.getByTestId('layout-item-MyDashboard');
                    dragOverEvent = react_2.createEvent.dragOver(dropTarget);
                    Object.defineProperty(dragOverEvent, 'layerX', { get: function () { return 0; } });
                    Object.defineProperty(dragOverEvent, 'layerY', { get: function () { return 50; } });
                    react_2.fireEvent.dragStart(draggableElement);
                    (0, react_2.fireEvent)(dropTarget, dragOverEvent);
                    react_2.fireEvent.drop(dropTarget);
                    expect(onDropSpy).toHaveBeenCalledWith([
                        { height: 5, id: 'MyDashboard', minWidth: 2, width: 2, x: 0, y: 0, isStatic: false },
                        { height: 5, id: 'MyProfile', minWidth: 2, width: 2, x: 0, y: 5, isStatic: false, autosizing: true },
                        { height: 1, id: '__dropping-elem__', width: 1, x: 0, y: 1, isStatic: false }
                    ], { height: 1, id: '__dropping-elem__', width: 1, x: 0, y: 1, isStatic: false }, expect.any(Object));
                    return [2 /*return*/];
            }
        });
    }); });
    it('should render fullscreen item correctly', function () { return __awaiter(void 0, void 0, void 0, function () {
        var views, layout, user, fullscreenButton;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    views = [
                        { id: 'MyDashboard', component: 'DashboardFacet', text: '123', title: 'My Dashboard' },
                        { id: 'SecondDashboard', component: 'DashboardFacet', text: '321', title: 'Second Dashboard' }
                    ];
                    layout = [
                        { x: 0, y: 0, width: 2, height: 5, minWidth: 2, id: 'MyDashboard' },
                        { x: 3, y: 6, width: 2, height: 5, minWidth: 2, id: 'SecondDashboard' }
                    ];
                    return [4 /*yield*/, setUp({ views: views, layout: layout })];
                case 1:
                    user = (_a.sent()).user;
                    fullscreenButton = react_2.screen.getAllByTestId('fullscreen-button')[0];
                    return [4 /*yield*/, user.click(fullscreenButton)];
                case 2:
                    _a.sent();
                    expect(react_2.screen.getByTestId('layout-item-MyDashboard')).toHaveClass('isFullscreen');
                    expect(react_2.screen.getByTestId('layout-item-SecondDashboard')).not.toHaveClass('isFullscreen');
                    return [2 /*return*/];
            }
        });
    }); });
    it('should call onRemove item correctly', function () { return __awaiter(void 0, void 0, void 0, function () {
        var onRemoveSpy, views, layout, user, removeButton;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    onRemoveSpy = jest.fn();
                    views = [
                        { id: 'MyDashboard', component: 'DashboardFacet', text: '123', title: 'My Dashboard' },
                        { id: 'SecondDashboard', component: 'DashboardFacet', text: '321', title: 'Second Dashboard' }
                    ];
                    layout = [
                        { x: 0, y: 0, width: 2, height: 5, minWidth: 2, id: 'MyDashboard' },
                        { x: 3, y: 6, width: 2, height: 5, minWidth: 2, id: 'SecondDashboard' }
                    ];
                    return [4 /*yield*/, setUp({ views: views, layout: layout, onRemove: onRemoveSpy })];
                case 1:
                    user = (_a.sent()).user;
                    removeButton = react_2.screen.getAllByTestId('remove-button')[0];
                    return [4 /*yield*/, user.click(removeButton)];
                case 2:
                    _a.sent();
                    expect(onRemoveSpy).toHaveBeenCalledWith('MyDashboard');
                    return [2 /*return*/];
            }
        });
    }); });
    describe('autosize behaviour', function () {
        var layout = [{ x: 0, y: 0, width: 2, height: 5, minWidth: 2, id: 'MyDashboard', autosizing: true }];
        it('should provide AutosizeComponent prop', function () { return __awaiter(void 0, void 0, void 0, function () {
            var _a;
            return __generator(this, function (_b) {
                switch (_b.label) {
                    case 0: return [4 /*yield*/, setUp({ layout: layout })];
                    case 1:
                        _b.sent();
                        expect((_a = react_2.screen.getByTestId('layout-item-MyDashboard').firstChild) === null || _a === void 0 ? void 0 : _a.nodeName).toBe('DIV');
                        return [2 /*return*/];
                }
            });
        }); });
        it('should call onLayoutChanged when height is new after resizing', function () { return __awaiter(void 0, void 0, void 0, function () {
            var onLayoutChangedSpy, _a, user, container, resizableHandle;
            return __generator(this, function (_b) {
                switch (_b.label) {
                    case 0:
                        onLayoutChangedSpy = jest.fn();
                        return [4 /*yield*/, setUp({ layout: layout, onLayoutChanged: onLayoutChangedSpy })];
                    case 1:
                        _a = _b.sent(), user = _a.user, container = _a.container;
                        expect(onLayoutChangedSpy).toHaveBeenCalledTimes(1);
                        resizableHandle = container.querySelector('.react-resizable-handle');
                        return [4 /*yield*/, user.pointer([
                                { target: resizableHandle, keys: '[MouseLeft>]' },
                                { coords: { x: 200, y: 200 } },
                                { target: resizableHandle, keys: '[/MouseLeft]' }
                            ])];
                    case 2:
                        _b.sent();
                        expect(onLayoutChangedSpy).toHaveBeenCalledWith([
                            { id: 'MyDashboard', minWidth: 2, width: 4, x: 0, y: 0, height: 9, autosizing: true, isStatic: false }
                        ]);
                        return [2 /*return*/];
                }
            });
        }); });
        it('should not call onLayoutChanged when height is the same after resizing', function () { return __awaiter(void 0, void 0, void 0, function () {
            var onLayoutChangedSpy, _a, user, container, resizableHandle;
            return __generator(this, function (_b) {
                switch (_b.label) {
                    case 0:
                        onLayoutChangedSpy = jest.fn();
                        return [4 /*yield*/, setUp({ layout: layout, onLayoutChanged: onLayoutChangedSpy })];
                    case 1:
                        _a = _b.sent(), user = _a.user, container = _a.container;
                        expect(onLayoutChangedSpy).toHaveBeenCalledTimes(1);
                        resizableHandle = container.querySelector('.react-resizable-handle');
                        return [4 /*yield*/, user.pointer([
                                { target: resizableHandle, keys: '[MouseLeft>]' },
                                { coords: { x: 200, y: 200 } },
                                { target: resizableHandle, keys: '[/MouseLeft]' }
                            ])];
                    case 2:
                        _b.sent();
                        expect(onLayoutChangedSpy).toHaveBeenCalledTimes(2);
                        return [4 /*yield*/, user.pointer([
                                { target: resizableHandle, keys: '[MouseLeft>]' },
                                { coords: { x: 200, y: 200 } },
                                { target: resizableHandle, keys: '[/MouseLeft]' }
                            ])];
                    case 3:
                        _b.sent();
                        expect(onLayoutChangedSpy).toHaveBeenCalledTimes(2);
                        return [2 /*return*/];
                }
            });
        }); });
        it('should call onLayoutChanged if layout have incorrect sizes in static mode', function () { return __awaiter(void 0, void 0, void 0, function () {
            var onLayoutChangedSpy, props, rerender, layoutItem, newLayout;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        onLayoutChangedSpy = jest.fn();
                        props = { layout: layout, onLayoutChanged: onLayoutChangedSpy, isStatic: true };
                        return [4 /*yield*/, setUp(props)];
                    case 1:
                        rerender = (_a.sent()).rerender;
                        expect(onLayoutChangedSpy).not.toHaveBeenCalled();
                        layoutItem = react_2.screen.getByTestId('layout-item-MyDashboard');
                        expect(layoutItem.style.height).toBe('210px');
                        resizeObserver.mockElementSize(react_2.screen.getByTestId('layout-item-MyDashboard'), {
                            contentBoxSize: { blockSize: 300 }
                        });
                        (0, react_2.act)(function () {
                            resizeObserver.resize(react_2.screen.getByTestId('layout-item-MyDashboard'));
                        });
                        return [4 /*yield*/, (0, react_2.waitFor)(function () { return expect(onLayoutChangedSpy).toHaveBeenCalledTimes(1); })];
                    case 2:
                        _a.sent();
                        newLayout = onLayoutChangedSpy.mock.calls[0][0];
                        rerender(react_1.default.createElement(ReltioGridLayout_1.default, __assign({}, defaultProps, props, { layout: newLayout })));
                        expect(react_2.screen.getByTestId('layout-item-MyDashboard').style.height).toBe('300px');
                        rerender(react_1.default.createElement(ReltioGridLayout_1.default, __assign({}, defaultProps, props, { layout: [] })));
                        onLayoutChangedSpy.mockClear();
                        rerender(react_1.default.createElement(ReltioGridLayout_1.default, __assign({}, defaultProps, props)));
                        expect(onLayoutChangedSpy).toHaveBeenCalledTimes(1);
                        expect(onLayoutChangedSpy).toHaveBeenCalledWith(newLayout);
                        return [2 /*return*/];
                }
            });
        }); });
    });
    it('should add classes.root to GridLayout', function () { return __awaiter(void 0, void 0, void 0, function () {
        var classes, container;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    classes = { root: 'root123' };
                    return [4 /*yield*/, setUp({ classes: classes })];
                case 1:
                    container = (_a.sent()).container;
                    expect(container.querySelector('.gridLayout')).toHaveClass(classes.root);
                    return [2 /*return*/];
            }
        });
    }); });
});
