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 (b.hasOwnProperty(p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
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 (_) 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 };
    }
};
import { h, r as registerInstance, c as createEvent, g as getElement } from './core-15e24a78.js';
import './utils-3aef1637.js';
import { T as TableClasses, E as EditControl, R as RowControl, a as EditControls, b as RowControls, k as keyFromData } from './table.utils-259f424b.js';
import { T as Tunnel } from './i18n.provider-7cafb88f.js';
import { C as ColumnRenderer } from './column.renderer-5d1eab0d.js';
var EditCell = function (_a) {
    var classList = _a.classList, column = _a.column, columnIndex = _a.columnIndex, offset = _a.offset, row = _a.row, rowIndex = _a.rowIndex, renderer = _a.renderer;
    var attrs = ColumnRenderer.columnAttributes(column, columnIndex, row);
    var refFn = function (r) { return column.initCell(r, offset); };
    var allClasses = classList + " " + TableClasses.editCell;
    // TODO: abstract this out better
    if (column.editTemplate) {
        return h("td", Object.assign({}, attrs, { class: allClasses, ref: function (r) { return renderer.cellTemplate(r, offset, column, row, rowIndex, column.editTemplate); } }));
    }
    else if (column.editFormatter) {
        return h("td", Object.assign({}, attrs, { class: allClasses, innerHTML: column.editFormatter(row, column, rowIndex), ref: refFn }));
    }
    else {
        return h("td", Object.assign({}, attrs, { class: allClasses, ref: refFn }), column.editRenderer(row, column));
    }
};
var CONTROL_SELECTOR = 'anj-input, anj-checkbox, anj-select';
var BaseEditingController = /** @class */ (function () {
    function BaseEditingController(control, table) {
        this.control = control;
        this.table = table;
    }
    BaseEditingController.isDirty = function (data, row) {
        var dirty = false;
        for (var prop in data) {
            if (data[prop] !== row[prop]) {
                dirty = true;
                break;
            }
        }
        return dirty;
    };
    BaseEditingController.prototype.onCreateStart = function () {
        return __awaiter(this, void 0, void 0, function () {
            var data, columns;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        data = {};
                        return [4 /*yield*/, this.table.getColumns()];
                    case 1:
                        columns = _a.sent();
                        columns.forEach(function (c) {
                            data[c.field] = typeof c.defaultValue === 'function' ? c.defaultValue(c) : c.defaultValue;
                        });
                        return [2 /*return*/, data];
                }
            });
        });
    };
    BaseEditingController.prototype.onCreateEnd = function (_a) {
        var target = _a.target;
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_b) {
                return [2 /*return*/, this.getData(target)];
            });
        });
    };
    BaseEditingController.prototype.onDelete = function (_a) {
        var target = _a.target;
        return __awaiter(this, void 0, void 0, function () {
            var rows, index;
            return __generator(this, function (_b) {
                switch (_b.label) {
                    case 0: return [4 /*yield*/, this.table.getRows()];
                    case 1:
                        rows = _b.sent();
                        index = this.indexByElement(target);
                        return [2 /*return*/, [rows[index], index]];
                }
            });
        });
    };
    BaseEditingController.prototype.onUpdateStart = function (event) {
        return __awaiter(this, void 0, void 0, function () {
            var rows, index;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this.table.getRows()];
                    case 1:
                        rows = _a.sent();
                        index = this.indexByElement(event.target);
                        return [2 /*return*/, [index, rows[index]]];
                }
            });
        });
    };
    BaseEditingController.prototype.onUpdateEnd = function (_a) {
        var target = _a.target;
        return __awaiter(this, void 0, void 0, function () {
            var rows, index, row, data;
            return __generator(this, function (_b) {
                switch (_b.label) {
                    case 0: return [4 /*yield*/, this.table.getRows()];
                    case 1:
                        rows = _b.sent();
                        index = this.indexByElement(target);
                        row = rows[index];
                        data = this.getData(target);
                        return [2 /*return*/, BaseEditingController.isDirty(data, row) ? [data, row, index] : undefined];
                }
            });
        });
    };
    BaseEditingController.prototype.onUpdateCancel = function () { };
    BaseEditingController.prototype.validate = function (el) {
        return __awaiter(this, void 0, void 0, function () {
            var results;
            var _this = this;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        if (!el)
                            return [2 /*return*/];
                        return [4 /*yield*/, Promise.all(Array.from(el.querySelectorAll(CONTROL_SELECTOR)).map(function (e) { return __awaiter(_this, void 0, void 0, function () { return __generator(this, function (_a) {
                                return [2 /*return*/, e.checkValidity()];
                            }); }); }))];
                    case 1:
                        results = _a.sent();
                        // Find any validity check where the value is false, if there are none, then it is valid
                        return [2 /*return*/, (results.find(function (i) { return !i; }) !== false)];
                }
            });
        });
    };
    BaseEditingController.prototype.getData = function (target) {
        var controls = target.closest('tr').querySelectorAll(CONTROL_SELECTOR);
        var data = {};
        controls.forEach(function (c) {
            if (c.tagName === 'ANJ-CHECKBOX') {
                var control = c;
                data[control.name] = control.checked;
            }
            else {
                var control = c;
                data[control.name] = control.value;
            }
        });
        return data;
    };
    BaseEditingController.prototype.indexByElement = function (target) {
        return Array.from(this.table.querySelectorAll('anj-row-edit-control')).findIndex(function (el) { return el === target; });
    };
    return BaseEditingController;
}());
var BatchEditingController = /** @class */ (function (_super) {
    __extends(BatchEditingController, _super);
    function BatchEditingController(control, table) {
        var _this = _super.call(this, control, table) || this;
        _this.deleteKeys = [];
        _this.updateKeys = [];
        return _this;
    }
    // @ts-ignore
    BatchEditingController.prototype.getEditType = function (data) {
        return undefined;
    };
    BatchEditingController.prototype.onUpdateEnd = function (event) {
        return __awaiter(this, void 0, void 0, function () {
            var change;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, _super.prototype.onUpdateEnd.call(this, event)];
                    case 1:
                        change = _a.sent();
                        if (change) {
                            this.updateKeys.push(event.detail.key);
                        }
                        return [2 /*return*/, change];
                }
            });
        });
    };
    BatchEditingController.prototype.onDelete = function (event) {
        return __awaiter(this, void 0, void 0, function () {
            var change;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, _super.prototype.onDelete.call(this, event)];
                    case 1:
                        change = _a.sent();
                        if (change[0][this.table.rowKey]) {
                            this.deleteKeys.push(change[0][this.table.rowKey]);
                        }
                        return [2 /*return*/, change];
                }
            });
        });
    };
    BatchEditingController.prototype.undo = function (change) {
        return __awaiter(this, void 0, void 0, function () {
            var rows, data, key, index, keyIndex;
            var _this = this;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this.table.getRows()];
                    case 1:
                        rows = _a.sent();
                        if (change.create) {
                            data = change.create[0];
                            key = data[this.table.rowKey];
                            this.deleteKeys = this.deleteKeys.filter(function (k) { return k !== key; });
                            this.table.dispatchEvent(new CustomEvent('anjCreateStart', { detail: { key: key, data: data } }));
                        }
                        else if (change.update) {
                            data = change.update[0];
                            key = data[this.table.rowKey];
                            index = rows.findIndex(function (r) { return r[_this.table.rowKey] === key; });
                            keyIndex = this.updateKeys.findIndex(function (k) { return k === change.update[0][_this.table.rowKey]; });
                            this.updateKeys.splice(keyIndex, 1);
                            this.table.dispatchEvent(new CustomEvent('anjUpdateEnd', { detail: { key: key, data: data, index: index } }));
                        }
                        else {
                            data = change.delete[0];
                            key = data[this.table.rowKey];
                            index = rows.findIndex(function (r) { return r[_this.table.rowKey] === key; });
                            this.table.dispatchEvent(new CustomEvent('anjDelete', { detail: { key: key, data: data, index: index } }));
                        }
                        return [2 /*return*/];
                }
            });
        });
    };
    BatchEditingController.prototype.save = function () {
        return __awaiter(this, void 0, void 0, function () {
            var valid, rows, creates, change;
            var _this = this;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this.validate(this.table.querySelector('table'))];
                    case 1:
                        valid = _a.sent();
                        if (!valid) {
                            return [2 /*return*/, undefined];
                        }
                        return [4 /*yield*/, this.table.getRows()];
                    case 2:
                        rows = _a.sent();
                        creates = rows.filter(function (r) { return !r[_this.table.rowKey]; });
                        change = {};
                        if (creates.length > 0) {
                            change.create = creates;
                        }
                        if (this.deleteKeys.length > 0) {
                            change.delete = this.deleteKeys;
                        }
                        if (this.updateKeys.length > 0) {
                            change.update = rows.filter(function (r) { return (r[_this.table.rowKey] && _this.updateKeys.includes(r[_this.table.rowKey])); });
                        }
                        return [2 /*return*/, change];
                }
            });
        });
    };
    return BatchEditingController;
}(BaseEditingController));
var NoopEditingController = /** @class */ (function (_super) {
    __extends(NoopEditingController, _super);
    function NoopEditingController(control, table) {
        return _super.call(this, control, table) || this;
    }
    // @ts-ignore
    NoopEditingController.prototype.getEditType = function (data) {
        return undefined;
    };
    NoopEditingController.prototype.onDelete = function (_a) {
        var target = _a.target;
        return __awaiter(this, void 0, void 0, function () {
            var rows, index;
            return __generator(this, function (_b) {
                switch (_b.label) {
                    case 0: return [4 /*yield*/, this.table.getRows()];
                    case 1:
                        rows = _b.sent();
                        index = this.indexByElement(target);
                        return [2 /*return*/, [rows[index], index]];
                }
            });
        });
    };
    NoopEditingController.prototype.save = function () {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                return [2 /*return*/];
            });
        });
    };
    // @ts-ignore
    NoopEditingController.prototype.validate = function (el) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                return [2 /*return*/, true];
            });
        });
    };
    // @ts-ignore
    NoopEditingController.prototype.undo = function (change) {
        return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) {
            return [2 /*return*/];
        }); });
    };
    return NoopEditingController;
}(BaseEditingController));
var RowEditingController = /** @class */ (function (_super) {
    __extends(RowEditingController, _super);
    function RowEditingController(control, table) {
        return _super.call(this, control, table) || this;
    }
    RowEditingController.prototype.onCreateStart = function () {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                this.table.activeRowIndex = 0;
                this.control.activeKey = undefined;
                this.control.createDisabled = true;
                return [2 /*return*/, _super.prototype.onCreateStart.call(this)];
            });
        });
    };
    RowEditingController.prototype.onCreateEnd = function (event) {
        return __awaiter(this, void 0, void 0, function () {
            var valid;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this.validate(this.rowFromEvent(event.target))];
                    case 1:
                        valid = _a.sent();
                        if (!valid) {
                            return [2 /*return*/, undefined];
                        }
                        this.control.createDisabled = false;
                        this.table.activeRowIndex = undefined;
                        return [2 /*return*/, _super.prototype.onCreateEnd.call(this, event)];
                }
            });
        });
    };
    RowEditingController.prototype.onDelete = function (event) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                this.control.createDisabled = false;
                this.table.activeRowIndex = undefined;
                return [2 /*return*/, _super.prototype.onDelete.call(this, event)];
            });
        });
    };
    RowEditingController.prototype.onUpdateCancel = function () {
        this.control.createDisabled = false;
        this.table.activeRowIndex = undefined;
        if (!this.control.activeKey) {
            this.table.dispatchEvent(new CustomEvent('anjDelete', { detail: { index: 0, key: undefined } }));
        }
        else {
            this.control.activeKey = undefined;
        }
    };
    RowEditingController.prototype.onUpdateStart = function (event) {
        return __awaiter(this, void 0, void 0, function () {
            var removeAdd, _a, index, data;
            return __generator(this, function (_b) {
                switch (_b.label) {
                    case 0:
                        this.control.createDisabled = false;
                        removeAdd = this.table.activeRowIndex === 0 && !this.control.activeKey;
                        return [4 /*yield*/, _super.prototype.onUpdateStart.call(this, event)];
                    case 1:
                        _a = _b.sent(), index = _a[0], data = _a[1];
                        this.table.activeRowIndex = removeAdd ? index - 1 : index;
                        this.control.activeKey = event.detail.key;
                        if (removeAdd) {
                            this.table.dispatchEvent(new CustomEvent('anjDelete', { detail: { index: 0, key: undefined } }));
                        }
                        return [2 /*return*/, [index, data]];
                }
            });
        });
    };
    RowEditingController.prototype.onUpdateEnd = function (event) {
        return __awaiter(this, void 0, void 0, function () {
            var valid, change;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this.validate(this.rowFromEvent(event.target))];
                    case 1:
                        valid = _a.sent();
                        if (!valid) {
                            return [2 /*return*/, undefined];
                        }
                        return [4 /*yield*/, _super.prototype.onUpdateEnd.call(this, event)];
                    case 2:
                        change = _a.sent();
                        this.table.activeRowIndex = undefined;
                        this.control.activeKey = undefined;
                        return [2 /*return*/, change];
                }
            });
        });
    };
    // @ts-ignore
    RowEditingController.prototype.undo = function (change) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                this.control.createDisabled = false;
                this.table.activeRowIndex = undefined;
                return [2 /*return*/];
            });
        });
    };
    RowEditingController.prototype.save = function () {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                return [2 /*return*/];
            });
        });
    };
    RowEditingController.prototype.getEditType = function (data) {
        if (this.control.createDisabled && !data[this.table.rowKey]) {
            return 'create';
        }
        if (data[this.table.rowKey] && data[this.table.rowKey] === this.control.activeKey) {
            return 'update';
        }
        return undefined;
    };
    RowEditingController.prototype.rowFromEvent = function (target) {
        return target.closest('tr');
    };
    return RowEditingController;
}(BaseEditingController));
var Translations;
(function (Translations) {
    Translations["SAVE_ALL"] = "Save All";
    Translations["UNDO"] = "Undo";
    Translations["CREATE_NEW"] = "Create New";
})(Translations || (Translations = {}));
var Editing = /** @class */ (function () {
    function class_1(hostRef) {
        var _this = this;
        registerInstance(this, hostRef);
        this.rowsWillChangeListener = function () { return _this.onRowsWillChange(); };
        this.rowsDidChangeListener = function () { return _this.onRowsDidChange(); };
        this.history = [];
        /**
         * Renderer to use for cell content when the selected cell conditions are met
         */
        this.cell = function (props) { return h(EditCell, Object.assign({}, props)); };
        /**
         * If true, the user cannot create records
         */
        this.createDisabled = false;
        /**
         * Can the user add a row? Defaults to false.
         */
        this.creating = false;
        /**
         * If true, the user cannot delete records
         */
        this.deleteDisabled = false;
        /**
         * Can the user delete a row? Defaults to false.
         */
        this.deleting = false;
        /**
         * The mode of editing
         * Possible values are: `"batch"`, `"row"`, and `"noop"`. Defaults to "noop"
         */
        this.mode = 'noop';
        /**
         * If true, will emit a cancelable event to signal the table to update the underlying data
         */
        this.saving = false;
        /**
         * Can the user undo, defaults to true
         */
        this.undo = false;
        /**
         * Can the user edit? Defaults to false.
         */
        this.updating = false;
        /**
         * Rules to use for using this as a renderer
         */
        this.when = this.useAsRenderer.bind(this);
        this.anjCellControlDidLoad = createEvent(this, "anjCellControlDidLoad", 7);
        this.anjCreateStart = createEvent(this, "anjCreateStart", 7);
        this.anjCreateEnd = createEvent(this, "anjCreateEnd", 7);
        this.anjDelete = createEvent(this, "anjDelete", 7);
        this.anjUpdateStart = createEvent(this, "anjUpdateStart", 7);
        this.anjUpdateEnd = createEvent(this, "anjUpdateEnd", 7);
        this.anjEditWillSave = createEvent(this, "anjEditWillSave", 7);
    }
    class_1.prototype.componentWillLoad = function () {
        this.table = this.element.closest('anj-table');
    };
    class_1.prototype.componentDidLoad = function () {
        this.anjCellControlDidLoad.emit();
        this.table.addEventListener('anjRowsWillLoad', this.rowsWillChangeListener);
        this.table.addEventListener('anjRowsDidLoad', this.rowsDidChangeListener);
        this.table.addEventListener('anjPage', this.rowsWillChangeListener);
        this.controller = this.initController();
    };
    class_1.prototype.componentDidUnload = function () {
        this.table.removeEventListener('anjRowsWillLoad', this.rowsWillChangeListener);
        this.table.removeEventListener('anjRowsDidLoad', this.rowsDidChangeListener);
        this.table.removeEventListener('anjPage', this.rowsWillChangeListener);
    };
    class_1.prototype.initController = function () {
        switch (this.mode) {
            case 'batch':
                return new BatchEditingController(this.element, this.table);
            case 'row':
                return new RowEditingController(this.element, this.table);
            default:
                return new NoopEditingController(this.element, this.table);
        }
    };
    class_1.prototype.useAsRenderer = function (column, rowIndex) {
        return (column.editable && (this.mode === 'batch' || rowIndex === this.table.activeRowIndex));
    };
    class_1.prototype.onRowsWillChange = function () {
        this.table.activeRowIndex = undefined;
    };
    class_1.prototype.onRowsDidChange = function () {
        return __awaiter(this, void 0, void 0, function () {
            var _this = this;
            return __generator(this, function (_a) {
                return [2 /*return*/, new Promise(function (resolve) {
                        window.setTimeout(function () {
                            resolve(_this.controller.validate(_this.table.querySelector('.anj-table tbody')));
                        });
                    })];
            });
        });
    };
    class_1.prototype.onCreateStart = function () {
        return __awaiter(this, void 0, void 0, function () {
            var data;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this.controller.onCreateStart()];
                    case 1:
                        data = _a.sent();
                        this.anjCreateStart.emit({ data: data, key: undefined, index: 0 });
                        return [2 /*return*/];
                }
            });
        });
    };
    class_1.prototype.onCreateEnd = function (event) {
        return __awaiter(this, void 0, void 0, function () {
            var row;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        event.stopPropagation();
                        return [4 /*yield*/, this.controller.onCreateEnd(event)];
                    case 1:
                        row = _a.sent();
                        if (!row)
                            return [2 /*return*/];
                        this.pushHistory({ delete: [row] });
                        this.anjCreateEnd.emit({ data: row, key: undefined });
                        this.save({ create: [row] });
                        return [2 /*return*/];
                }
            });
        });
    };
    class_1.prototype.onUpdateStart = function (event) {
        return __awaiter(this, void 0, void 0, function () {
            var _a, index, data;
            return __generator(this, function (_b) {
                switch (_b.label) {
                    case 0:
                        event.stopPropagation();
                        return [4 /*yield*/, this.controller.onUpdateStart(event)];
                    case 1:
                        _a = _b.sent(), index = _a[0], data = _a[1];
                        this.anjUpdateStart.emit(Object.assign(event.detail, { index: index, data: data }));
                        return [2 /*return*/];
                }
            });
        });
    };
    class_1.prototype.onUpdateEnd = function (event) {
        return __awaiter(this, void 0, void 0, function () {
            var change, update, row, index, data;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        event.stopPropagation();
                        return [4 /*yield*/, this.controller.onUpdateEnd(event)];
                    case 1:
                        change = _a.sent();
                        if (!change)
                            return [2 /*return*/];
                        update = change[0], row = change[1], index = change[2];
                        data = Object.assign({}, row, update);
                        this.pushHistory({ update: [row] });
                        if (this.mode === 'row') {
                            this.anjUpdateEnd.emit({ key: event.detail.key, data: data, index: index });
                            this.save({ update: [data] });
                        }
                        return [2 /*return*/];
                }
            });
        });
    };
    class_1.prototype.onDelete = function (event) {
        return __awaiter(this, void 0, void 0, function () {
            var _a, data, index;
            return __generator(this, function (_b) {
                switch (_b.label) {
                    case 0:
                        event.stopPropagation();
                        return [4 /*yield*/, this.controller.onDelete(event)];
                    case 1:
                        _a = _b.sent(), data = _a[0], index = _a[1];
                        if (data[this.table.rowKey]) {
                            this.pushHistory({ create: [data] });
                        }
                        this.anjDelete.emit({ index: index, data: data, key: event.detail.key });
                        if (this.mode === 'row') {
                            this.save({ delete: [data] });
                        }
                        return [2 /*return*/];
                }
            });
        });
    };
    class_1.prototype.onUndo = function () {
        return __awaiter(this, void 0, void 0, function () {
            var change;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        change = this.popHistory();
                        return [4 /*yield*/, this.controller.undo(change)];
                    case 1:
                        _a.sent();
                        if (this.mode === 'row') {
                            this.save(change);
                        }
                        return [2 /*return*/];
                }
            });
        });
    };
    class_1.prototype.onSuperSave = function () {
        return __awaiter(this, void 0, void 0, function () {
            var change;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this.controller.save()];
                    case 1:
                        change = _a.sent();
                        if (change) {
                            this.clearHistory();
                            this.save(change);
                        }
                        return [2 /*return*/];
                }
            });
        });
    };
    class_1.prototype.save = function (patch) {
        if (!this.saving)
            return;
        this.anjEditWillSave.emit(patch);
    };
    class_1.prototype.clearHistory = function () {
        if (!this.undo)
            return;
        this.history = [];
    };
    class_1.prototype.pushHistory = function (change) {
        if (!this.undo)
            return;
        this.history = [change].concat(this.history);
    };
    class_1.prototype.popHistory = function () {
        if (!this.undo)
            return;
        var change = this.history[0];
        this.history = this.history.slice(1);
        return change;
    };
    class_1.prototype.control = function (data) {
        var _this = this;
        return h("anj-row-edit-control", { rowKey: data[this.table.rowKey], editing: this.controller ? this.controller.getEditType(data) : undefined, mode: this.mode, update: this.updating && this.mode !== 'batch', delete: this.deleting, deleteDisabled: this.deleteDisabled, onAnjCreateEnd: function (e) { return _this.onCreateEnd(e); }, onAnjUpdateCancel: function () { return _this.controller.onUpdateCancel(); }, onAnjUpdateStart: function (e) { return _this.onUpdateStart(e); }, onAnjUpdateEnd: function (e) { return _this.onUpdateEnd(e); }, onAnjDelete: function (e) { return _this.onDelete(e); } });
    };
    class_1.prototype.calculateColWidth = function () {
        var btnSize = 40;
        var multiplier = 0;
        if (this.deleting) {
            multiplier++;
        }
        if (this.updating && this.mode !== 'batch') {
            multiplier = 2;
        }
        var padding = multiplier > 0 ? 2 : 0;
        return (multiplier * btnSize) + padding + "px";
    };
    class_1.prototype.render = function () {
        var _this = this;
        return [
            h("anj-column", { filterable: false, internal: true, pinned: "right", editable: false, sizable: false, pinnable: false, orderable: false, selectable: false, name: "row-edit-control", width: this.calculateColWidth(), cellRenderer: function (data) { return _this.control(data); } }),
            this.mode === 'batch' && this.saving ?
                h("anj-button", { context: "icon", "aria-label": this.translator(Translations.SAVE_ALL), disabled: this.history.length === 0, onClick: function () { return __awaiter(_this, void 0, void 0, function () { return __generator(this, function (_a) {
                        return [2 /*return*/, this.onSuperSave()];
                    }); }); } }, h("svg", { slot: "icon-only", xmlns: "http://www.w3.org/2000/svg", width: "24", height: "24", viewBox: "0 0 24 24" }, h("path", { d: "M17 3H5c-1.11 0-2 .9-2 2v14c0 1.1.89 2 2 2h14c1.1 0 2-.9 2-2V7l-4-4zm-5 16c-1.66 0-3-1.34-3-3s1.34-3 3-3 3 1.34 3 3-1.34 3-3 3zm3-10H5V5h10v4z" }))) : undefined,
            this.undo ?
                h("anj-button", { context: "icon", "aria-label": this.translator(Translations.UNDO), disabled: this.history.length === 0, onClick: function () { return _this.onUndo(); } }, h("svg", { slot: "icon-only", xmlns: "http://www.w3.org/2000/svg", width: "24", height: "24", viewBox: "0 0 24 24" }, h("path", { d: "M12.5 8c-2.65 0-5.05.99-6.9 2.6L2 7v9h9l-3.62-3.62c1.39-1.16 3.16-1.88 5.12-1.88 3.54 0 6.55 2.31 7.6 5.5l2.37-.78C21.08 11.03 17.15 8 12.5 8z" }))) : undefined,
            this.creating ?
                h("anj-button", { context: "icon", "aria-label": this.translator(Translations.CREATE_NEW), disabled: this.createDisabled, onClick: function () { return _this.onCreateStart(); } }, h("svg", { slot: "icon-only", xmlns: "http://www.w3.org/2000/svg", width: "24", height: "24", viewBox: "0 0 24 24" }, h("path", { d: "M13 7h-2v4H7v2h4v4h2v-4h4v-2h-4V7zm-1-5C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 18c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8z" }))) : undefined
        ];
    };
    Object.defineProperty(class_1.prototype, "element", {
        get: function () { return getElement(this); },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(class_1, "style", {
        get: function () { return ".anj-table .anj-col-row-edit-control{padding-left:0;padding-right:0}.anj-table td.anj-form-cell{overflow:visible;padding-bottom:0;padding-top:0;vertical-align:bottom}.anj-table td.anj-form-cell.anj-datatype-boolean{vertical-align:middle}.anj-table td.anj-form-cell anj-date-picker-toggle{margin-top:-5px}.anj-table td.anj-form-cell anj-checkbox{position:relative;top:3px}.anj-table[column-width=auto] .anj-cell anj-form-group{width:auto}anj-scroller:not(.anj-overflow-x) tbody tr .anj-col-row-edit-control anj-button{opacity:0;-webkit-transition:opacity .2s ease;transition:opacity .2s ease}anj-scroller:not(.anj-overflow-x) tbody tr .anj-col-row-edit-control anj-button:focus,anj-scroller:not(.anj-overflow-x) tbody tr .anj-col-row-edit-control anj-button[active]{opacity:1}anj-scroller:not(.anj-overflow-x) tbody tr:focus-within .anj-col-row-edit-control anj-button,anj-scroller:not(.anj-overflow-x) tbody tr:hover .anj-col-row-edit-control anj-button{opacity:1}"; },
        enumerable: true,
        configurable: true
    });
    return class_1;
}());
Tunnel.injectProps(Editing, ['translator']);
var CONTROL_ICONS = {
    update: 'M3 17.25V21h3.75L17.81 9.94l-3.75-3.75L3 17.25zM20.71 7.04c.39-.39.39-1.02 0-1.41l-2.34-2.34c-.39-.39-1.02-.39-1.41 0l-1.83 1.83 3.75 3.75 1.83-1.83z',
    save: 'M17 3H5c-1.11 0-2 .9-2 2v14c0 1.1.89 2 2 2h14c1.1 0 2-.9 2-2V7l-4-4zm-5 16c-1.66 0-3-1.34-3-3s1.34-3 3-3 3 1.34 3 3-1.34 3-3 3zm3-10H5V5h10v4z',
    cancel: 'M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z'
};
var RowEditControl = /** @class */ (function () {
    function RowEditControl(hostRef) {
        var _this = this;
        registerInstance(this, hostRef);
        this.controlListener = function () { return _this.onControl(EditControl.save); };
        /**
         * Can the user delete a row? Defaults to false.
         */
        this.delete = false;
        /**
         * If true, the user cannot delete records
         */
        this.deleteDisabled = false;
        /**
         * The mode of editing
         * Possible values are: `"batch"` and `"row`. Defaults to "row"
         */
        this.mode = 'row';
        /**
         * Can the user edit?
         */
        this.update = false;
        this.anjUpdateCancel = createEvent(this, "anjUpdateCancel", 7);
        this.anjCreateEnd = createEvent(this, "anjCreateEnd", 7);
        this.anjDelete = createEvent(this, "anjDelete", 7);
        this.anjUpdateEnd = createEvent(this, "anjUpdateEnd", 7);
        this.anjUpdateStart = createEvent(this, "anjUpdateStart", 7);
    }
    RowEditControl.prototype.componentDidLoad = function () {
        if (this.mode === 'batch') {
            this.element.closest('tr').addEventListener('anjBlur', this.controlListener);
        }
    };
    RowEditControl.prototype.componentDidUnload = function () {
        if (this.mode === 'batch') {
            var row = this.element.closest('tr');
            if (row) {
                this.element.closest('tr').removeEventListener('anjBlur', this.controlListener);
            }
        }
    };
    RowEditControl.prototype.onControl = function (action) {
        var key = keyFromData(this.rowKey);
        var payload = { key: key };
        switch (action) {
            case EditControl.cancel:
                this.anjUpdateCancel.emit(payload);
                break;
            case EditControl.save:
                this.editing === 'create' ? this.anjCreateEnd.emit(payload) : this.anjUpdateEnd.emit(payload);
                break;
            case RowControl.delete:
                this.anjDelete.emit(payload);
                break;
            case RowControl.update:
                this.anjUpdateStart.emit(payload);
                break;
            default:
                break;
        }
    };
    RowEditControl.prototype.controlDisabled = function (control) {
        return this[control + "Disabled"];
    };
    RowEditControl.prototype.render = function () {
        var _this = this;
        var controls = this.editing ? EditControls : RowControls.filter(function (c) { return _this[c]; });
        return (h("anj-button-group", null, controls.map(function (c) { return h("anj-button", { context: "icon", onClick: function () { return _this.onControl(c); }, onAnjBlur: function (e) { return e.stopPropagation(); }, disabled: _this.controlDisabled(c), ariaLabel: c }, h("svg", { slot: "icon-only", xmlns: "http://www.w3.org/2000/svg", width: "24", height: "24", viewBox: "0 0 24 24" }, c === 'delete' ?
            h("path", { d: "M6 19c0 1.1.9 2 2 2h8c1.1 0 2-.9 2-2V7H6v12zM8 9h8v10H8V9zm7.5-5l-1-1h-5l-1 1H5v2h14V4z" }) :
            h("path", { d: CONTROL_ICONS[c] }))); })));
    };
    Object.defineProperty(RowEditControl.prototype, "element", {
        get: function () { return getElement(this); },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(RowEditControl, "style", {
        get: function () { return "anj-row-edit-control{display:block}anj-row-edit-control anj-button:not(:last-child){margin-right:.5rem}anj-row-edit-control anj-button .anj-button-link{border-radius:50%}"; },
        enumerable: true,
        configurable: true
    });
    return RowEditControl;
}());
var ValidationRule = /** @class */ (function () {
    function ValidationRule(hostRef) {
        registerInstance(this, hostRef);
        this.anjValidationRuleDidLoad = createEvent(this, "anjValidationRuleDidLoad", 7);
    }
    ValidationRule.prototype.componentDidLoad = function () {
        this.anjValidationRuleDidLoad.emit();
    };
    return ValidationRule;
}());
export { Editing as anj_editing, RowEditControl as anj_row_edit_control, ValidationRule as anj_validation_rule };
