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 __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
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;
    return g = { next: verb(0), "throw": verb(1), "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 __read = (this && this.__read) || function (o, n) {
    var m = typeof Symbol === "function" && o[Symbol.iterator];
    if (!m) return o;
    var i = m.call(o), r, ar = [], e;
    try {
        while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
    }
    catch (error) { e = { error: error }; }
    finally {
        try {
            if (r && !r.done && (m = i["return"])) m.call(i);
        }
        finally { if (e) throw e.error; }
    }
    return ar;
};
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 __values = (this && this.__values) || function(o) {
    var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
    if (m) return m.call(o);
    if (o && typeof o.length === "number") return {
        next: function () {
            if (o && i >= o.length) o = void 0;
            return { value: o && o[i++], done: !o };
        }
    };
    throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
};
import { autoinject, bindable, bindingMode, children, customElement, DOM } from "aurelia-framework";
import ResizeObserver from "resize-observer-polyfill";
import { calculateOverflow } from "../../utils/ui-common";
import { UIInternal } from "../../utils/ui-internal";
export var UITabPanel = (function () {
    function UITabPanel(element) {
        this.element = element;
        this.tabs = [];
        this.align = "top";
        this.isDragAndDrop = true;
        this.hasOverflow = false;
        this.isAttached = false;
        if (element.hasAttribute("no-border")) {
            element.classList.add("ui-tab__panel--noborder");
        }
    }
    UITabPanel.prototype.activateTab = function (id) {
        return __awaiter(this, void 0, void 0, function () {
            var result;
            var _this = this;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        result = true;
                        if (!this.composeVm.currentViewModel) return [3, 2];
                        return [4, UIInternal.invokeLifecycle(this.composeVm.currentViewModel, "canDeactivate")];
                    case 1:
                        result = _a.sent();
                        _a.label = 2;
                    case 2:
                        if (result) {
                            return [2, UIInternal.fireCallbackEvent(this, "beforechange", {
                                    activeTab: this.activeTab.id,
                                    activeViewModel: this.composeVm.currentViewModel,
                                    newTab: id
                                }).then(function (b) { return (b ? _this.activate(id) : undefined); })];
                        }
                        else {
                            return [2, Promise.resolve(false)];
                        }
                        return [2];
                }
            });
        });
    };
    UITabPanel.prototype.closeTab = function (id) {
        return __awaiter(this, void 0, void 0, function () {
            var tab, result;
            var _this = this;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        tab = this.tabs.find(function (t) { return t.id === id; });
                        result = true;
                        if (!(this.activeTab.id === id && this.composeVm.currentViewModel)) return [3, 2];
                        return [4, UIInternal.invokeLifecycle(this.composeVm.currentViewModel, "canDeactivate")];
                    case 1:
                        result = _a.sent();
                        _a.label = 2;
                    case 2:
                        if (result) {
                            return [2, UIInternal.fireCallbackEvent(this, "beforeclose", tab.id).then(function (b) {
                                    return b ? _this.remove(id) : false;
                                })];
                        }
                        else {
                            return [2, Promise.resolve(false)];
                        }
                        return [2];
                }
            });
        });
    };
    UITabPanel.prototype.created = function (owningView) {
        this.owningView = owningView;
    };
    UITabPanel.prototype.attached = function () {
        var _this = this;
        this.composeVm.owningView = this.owningView;
        this.composeVm.viewResources = this.owningView.resources;
        this.obResize = new ResizeObserver(function () { return _this.calculateOverflow(); });
        this.obResize.observe(this.element);
        this.isAttached = true;
        this.tabsChanged();
    };
    UITabPanel.prototype.detached = function () {
        this.obResize.disconnect();
    };
    UITabPanel.prototype.innerTabsChanged = function () {
        this.tabs = this.innerTabs || this.tabs;
        this.tabsChanged();
    };
    UITabPanel.prototype.tabsChanged = function () {
        var _this = this;
        if (this.isAttached) {
            this.active = (this.tabs.find(function (tab) { return tab.active; }) || {}).id;
            if (!this.active) {
                this.activeTab = this.tabs.find(function (tab) { return !tab.disabled; }) || {};
                this.active = this.activeTab.id;
                this.activeTab.active = true;
            }
            UIInternal.queueTask(function () { return _this.calculateOverflow(); });
        }
    };
    UITabPanel.prototype.activate = function (id) {
        var newTab = this.tabs.find(function (tab) { return tab.id === id; });
        if (newTab && !newTab.disabled) {
            this.element.dispatchEvent(UIInternal.createEvent("change", id));
            if (this.activeTab) {
                this.activeTab.active = false;
            }
            this.activeTab = newTab;
            this.active = this.activeTab.id;
            this.activeTab.active = true;
            return true;
        }
        return false;
    };
    UITabPanel.prototype.remove = function (id) {
        var _this = this;
        var tab = this.tabs.find(function (t) { return t.id === id; });
        this.element.dispatchEvent(UIInternal.createEvent("close", id));
        this.menuEl.innerHTML = "";
        UIInternal.queueTask(function () {
            _this.tabs = __spreadArray([], __read(_this.tabs.splice(_this.tabs.indexOf(tab), 1)), false);
        });
        if (tab.element) {
            UIInternal.queueTask(function () { return DOM.removeNode(tab.element); });
        }
        return true;
    };
    UITabPanel.prototype.calculateOverflow = function () {
        this.hasOverflow = calculateOverflow(this.wrapperEl, this.menuEl);
    };
    UITabPanel.prototype.drag = function (event, tab) {
        if (this.isDragAndDrop) {
            event.dataTransfer.setData("text", tab.id);
        }
    };
    UITabPanel.prototype.ondragenter = function (event, tab) {
        if (tab === void 0) { tab = null; }
        if (this.isDragAndDrop) {
            event === null || event === void 0 ? void 0 : event.preventDefault();
            event === null || event === void 0 ? void 0 : event.stopImmediatePropagation();
            this.ondragleave(event, tab, true);
            this.lastPreview = document.createElement("div");
            this.lastPreview.className = "ui-tab__preview";
            if (tab != null) {
                this.wrapperEl.insertBefore(this.lastPreview, tab.btnEl);
            }
            else {
                this.wrapperEl.insertBefore(this.lastPreview, this.overflowEl);
            }
        }
    };
    UITabPanel.prototype.ondragleave = function (event, tab, all) {
        var e_1, _a;
        if (tab === void 0) { tab = null; }
        if (all === void 0) { all = false; }
        if (this.isDragAndDrop) {
            event === null || event === void 0 ? void 0 : event.preventDefault();
            event === null || event === void 0 ? void 0 : event.stopImmediatePropagation();
            var previews = this.wrapperEl.getElementsByClassName("ui-tab__preview");
            if (previews.length > 0) {
                try {
                    for (var _b = __values(Array.from(previews)), _c = _b.next(); !_c.done; _c = _b.next()) {
                        var preview = _c.value;
                        if (all || preview != this.lastPreview) {
                            preview.remove();
                        }
                    }
                }
                catch (e_1_1) { e_1 = { error: e_1_1 }; }
                finally {
                    try {
                        if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
                    }
                    finally { if (e_1) throw e_1.error; }
                }
            }
        }
    };
    UITabPanel.prototype.ondragover = function (event, tab) {
        if (tab === void 0) { tab = null; }
        event === null || event === void 0 ? void 0 : event.preventDefault();
        return true;
    };
    UITabPanel.prototype.drop = function (event, tab) {
        if (tab === void 0) { tab = null; }
        return __awaiter(this, void 0, void 0, function () {
            var dataId_1, tabMoving, tabMovingIndex, tabIndex;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        if (!this.isDragAndDrop) return [3, 2];
                        event === null || event === void 0 ? void 0 : event.preventDefault();
                        event === null || event === void 0 ? void 0 : event.stopImmediatePropagation();
                        this.ondragleave(event, tab, true);
                        dataId_1 = event.dataTransfer.getData("text");
                        tabMoving = this.innerTabs.find(function (x) { return x.id == dataId_1; });
                        tabMovingIndex = this.innerTabs.indexOf(tabMoving);
                        tabIndex = 0;
                        if (tab != null) {
                            tabIndex = this.innerTabs.indexOf(tab);
                            if (tabIndex > tabMovingIndex) {
                                tabIndex--;
                            }
                        }
                        else {
                            tabIndex = this.innerTabs.length - 1;
                        }
                        if (!(tabMovingIndex >= 0 && tabIndex >= 0 && tabMovingIndex != tabIndex)) return [3, 2];
                        this.innerTabs.splice(tabMovingIndex, 1);
                        this.innerTabs.splice(tabIndex, 0, tabMoving);
                        if (!(this.dragDropFunction != null)) return [3, 2];
                        return [4, this.dragDropFunction({ record: tabMoving.model, oldVal: tabMovingIndex, newVal: tabIndex })];
                    case 1:
                        _a.sent();
                        _a.label = 2;
                    case 2: return [2];
                }
            });
        });
    };
    __decorate([
        bindable(),
        __metadata("design:type", Array)
    ], UITabPanel.prototype, "tabs", void 0);
    __decorate([
        bindable({ bindingMode: bindingMode.twoWay }),
        __metadata("design:type", String)
    ], UITabPanel.prototype, "active", void 0);
    __decorate([
        bindable(),
        __metadata("design:type", String)
    ], UITabPanel.prototype, "align", void 0);
    __decorate([
        bindable(),
        __metadata("design:type", Function)
    ], UITabPanel.prototype, "beforechange", void 0);
    __decorate([
        bindable(),
        __metadata("design:type", Function)
    ], UITabPanel.prototype, "beforeclose", void 0);
    __decorate([
        children("ui-tab"),
        __metadata("design:type", Array)
    ], UITabPanel.prototype, "innerTabs", void 0);
    __decorate([
        bindable({ bindingMode: bindingMode.toView }),
        __metadata("design:type", Object)
    ], UITabPanel.prototype, "activeTab", void 0);
    __decorate([
        bindable({ bindingMode: bindingMode.oneTime }),
        __metadata("design:type", Boolean)
    ], UITabPanel.prototype, "isDragAndDrop", void 0);
    __decorate([
        bindable(),
        __metadata("design:type", Function)
    ], UITabPanel.prototype, "dragDropFunction", void 0);
    UITabPanel = __decorate([
        autoinject(),
        customElement("ui-tab-panel"),
        __metadata("design:paramtypes", [Element])
    ], UITabPanel);
    return UITabPanel;
}());

//# sourceMappingURL=ui-tab-panel.js.map
