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 { r as registerInstance, c as createEvent, h, g as getElement } from './core-15e24a78.js';
import './utils-3aef1637.js';
import { k as keyFromData, T as TableClasses, A as ALL_ROWS_KEY } from './table.utils-259f424b.js';
import { T as Tunnel } from './i18n.provider-7cafb88f.js';
import './column.renderer-5d1eab0d.js';
import { R as Row } from './row-4bc2b551.js';
import { i as isFocusable } from './a11y-3dcc958f.js';
var Translations;
(function (Translations) {
    Translations["DESELECT"] = "Deselect";
    Translations["SELECT"] = "Select";
})(Translations || (Translations = {}));
var RowSelectControl = /** @class */ (function () {
    function class_1(hostRef) {
        var _this = this;
        registerInstance(this, hostRef);
        this.clickListener = function (e) { _this.onRowSelect(e); };
        /**
         * The key for the row
         */
        this.labelFormatter = this.defaultLabelFormatter;
        /**
         * The mode of selection
         * Possible values are: `"batch"` and `"single`. Defaults to "single"
         */
        this.mode = 'single';
        /**
         * If true, will render a checkbox for batch selection and a radio button for single
         */
        this.showCheck = false;
        this.anjRowSelectClick = createEvent(this, "anjRowSelectClick", 7);
    }
    class_1.prototype.onSelected = function () {
        if (!this.rowEl || this.checkOnly()) {
            return;
        }
        if (this.selected) {
            this.rowEl.classList.add('anj-selected');
        }
        else {
            this.rowEl.classList.remove('anj-selected');
        }
    };
    class_1.prototype.componentDidLoad = function () {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                this.rowEl = this.element.parentElement.parentElement;
                this.onSelected();
                if (!this.checkOnly()) {
                    this.rowEl.classList.add('anj-selectable');
                    this.rowEl.addEventListener('click', this.clickListener);
                }
                return [2 /*return*/];
            });
        });
    };
    class_1.prototype.componentDidUnload = function () {
        if (!this.checkOnly()) {
            this.rowEl.removeEventListener('click', this.clickListener);
        }
    };
    class_1.prototype.onRowSelect = function (event) {
        if (event && event instanceof MouseEvent && event.composedPath().find(function (e) { return e.tagName !== 'TR' && isFocusable(e); })) {
            return;
        }
        var checkbox = event ? event.target : undefined;
        if (!checkbox || checkbox.checked !== this.selected) {
            this.selected = checkbox ? checkbox.checked : !this.selected;
            this.anjRowSelectClick.emit({ key: keyFromData(this.rowKey) });
        }
    };
    class_1.prototype.defaultLabelFormatter = function (key, selected) {
        return selected ? this.translator(Translations.DESELECT) + ": " + key : this.translator(Translations.SELECT) + ": " + key;
    };
    class_1.prototype.checkOnly = function () {
        return (this.mode === 'batch' && this.showCheck);
    };
    class_1.prototype.render = function () {
        if (!this.showCheck)
            return;
        var label = this.labelFormatter(this.rowKey, this.selected);
        var className = 'anj-selection-control';
        return this.mode === 'batch' ?
            h("anj-checkbox", { value: "" + this.rowKey, name: this.rowKey + "-selected", checked: this.selected, solo: true, "aria-label": label, class: className })
            : h("anj-radio", { value: "" + this.rowKey, class: className, checked: this.selected, "aria-label": label, name: "anj-row-select", solo: true });
    };
    Object.defineProperty(class_1.prototype, "element", {
        get: function () { return getElement(this); },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(class_1, "watchers", {
        get: function () {
            return {
                "selected": ["onSelected"]
            };
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(class_1, "style", {
        get: function () { return "anj-row-select-control[mode=batch]{display:block;line-height:1;margin:0 0 -1px}"; },
        enumerable: true,
        configurable: true
    });
    return class_1;
}());
Tunnel.injectProps(RowSelectControl, ['translator']);
var RowSelection = /** @class */ (function () {
    function class_2(hostRef) {
        var _this = this;
        registerInstance(this, hostRef);
        this.rowsDidChangeListener = function () { return _this.onRowsDidChange(); };
        /**
         * The mode of selection
         * Possible values are: `"batch"`, and `"single`. Defaults to "single"
         */
        this.mode = 'single';
        /**
         * Renderer to use for cell content when the selected cell conditions are met
         */
        this.row = this.renderRow.bind(this);
        /**
         * For batch selection only, will renderer a "select all" checkbox
         */
        this.showCheckAll = false;
        /**
         * If true, will render checkboxes for batch selection and radio buttons for single
         */
        this.showChecks = false;
        /**
         * Rules to use for using this as a renderer
         */
        this.when = this.useAsRenderer.bind(this);
        this.anjRowControlDidLoad = createEvent(this, "anjRowControlDidLoad", 7);
        this.anjRowSelect = createEvent(this, "anjRowSelect", 7);
    }
    class_2.prototype.connectedCallback = function () {
        this.table = this.element.closest('anj-table');
        this.table.addEventListener('anjRowsDidLoad', this.rowsDidChangeListener);
    };
    class_2.prototype.componentDidLoad = function () {
        this.anjRowControlDidLoad.emit();
    };
    class_2.prototype.disconnectedCallback = function () {
        this.table.removeEventListener('anjRowsDidLoad', this.rowsDidChangeListener);
    };
    class_2.clearStyles = function (el) {
        if (el) {
            el.removeAttribute('style');
        }
    };
    class_2.prototype.onRowsDidChange = function () {
        if (this.headerControl) {
            return this.checkSelectAll();
        }
    };
    class_2.prototype.onSelection = function (event) {
        return __awaiter(this, void 0, void 0, function () {
            var detail;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        event.stopPropagation();
                        detail = event.detail;
                        this.table.selectedRowKeys = this.table.selectedRowKeys.includes(detail.key) ? this.table.selectedRowKeys.filter(function (k) { return k !== detail.key; })
                            : (this.mode === 'batch') ? this.table.selectedRowKeys.concat([detail.key]) : [detail.key];
                        if (!(this.mode === 'batch' && this.showCheckAll)) return [3 /*break*/, 2];
                        return [4 /*yield*/, this.checkSelectAll()];
                    case 1:
                        _a.sent();
                        _a.label = 2;
                    case 2:
                        this.anjRowSelect.emit({ key: detail.key, selectedRowKeys: this.table.selectedRowKeys });
                        return [2 /*return*/];
                }
            });
        });
    };
    class_2.prototype.onSelectAll = function (event) {
        return __awaiter(this, void 0, void 0, function () {
            var checkbox, rows, rowKeys, selectAll;
            var _this = this;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        event.stopPropagation();
                        checkbox = this.headerControl.querySelector('anj-checkbox');
                        return [4 /*yield*/, this.table.getRows()];
                    case 1:
                        rows = _a.sent();
                        rowKeys = rows.map(function (r) { return r[_this.table.rowKey]; });
                        selectAll = (checkbox.checked || checkbox.indeterminate);
                        this.table.selectedRowKeys = selectAll
                            ? this.table.selectedRowKeys.concat(rowKeys.filter(function (k) { return !_this.table.selectedRowKeys.includes(k); }))
                            : this.table.selectedRowKeys.filter(function (k) { return !rowKeys.includes(k); });
                        this.anjRowSelect.emit({ key: undefined, selectedRowKeys: this.table.selectedRowKeys });
                        return [2 /*return*/, this.checkSelectAll(rows, rowKeys, checkbox)];
                }
            });
        });
    };
    /**
     * This is a little wonky but the main thrust is that we get all the args in onSelectAll, so if we're calling this from there, it doesn't make sense to
     * get it all again.
     */
    class_2.prototype.checkSelectAll = function (rs, keys, check) {
        return __awaiter(this, void 0, void 0, function () {
            var rows, _a, checkbox, rowKeys, selectedKeys;
            var _this = this;
            return __generator(this, function (_b) {
                switch (_b.label) {
                    case 0:
                        _a = rs;
                        if (_a) return [3 /*break*/, 2];
                        return [4 /*yield*/, this.table.getRows()];
                    case 1:
                        _a = (_b.sent());
                        _b.label = 2;
                    case 2:
                        rows = _a;
                        checkbox = check || this.headerControl.querySelector('anj-checkbox');
                        rowKeys = keys || rows.map(function (r) { return r[_this.table.rowKey]; });
                        selectedKeys = rowKeys.filter(function (k) { return _this.table.selectedRowKeys.includes(k); });
                        checkbox.indeterminate = selectedKeys.length < rows.length && selectedKeys.length > 0;
                        this.headerControl.selected = selectedKeys.length > 0;
                        checkbox.checked = selectedKeys.length > 0;
                        return [2 /*return*/];
                }
            });
        });
    };
    class_2.prototype.renderRow = function (props) {
        var _this = this;
        var attrs = { colspan: props.columns.length - 1 };
        // The first cell is a dummy cell to keep things kosher
        return (h(Row, Object.assign({}, props), h("tr", { class: TableClasses.detailRow }, h("td", { style: { border: '0', 'border-color': 'transparent', width: '0', padding: '0' } }), h("td", Object.assign({}, attrs, { class: TableClasses.detailCell, ref: function (r) { RowSelection.clearStyles(r); } }), h("div", { class: TableClasses.detailWrapper }, this.template
            ? h("div", { class: TableClasses.detail, ref: function (r) { return _this.table.renderer.fromTemplate(_this.template, r, props.row, props.rowIndex); } })
            : this.formatter ? h("div", { class: TableClasses.detail, innerHTML: this.formatter(props.row, props.rowIndex) })
                : h("div", { class: TableClasses.detail }, this.renderer(props.row, props.rowIndex)))))));
    };
    class_2.prototype.cell = function (data) {
        var _this = this;
        return h("anj-row-select-control", { showCheck: this.showChecks, rowKey: data[this.table.rowKey], selected: this.selected(data), mode: this.mode, labelFormatter: this.labelFormatter, onAnjRowSelectClick: function (e) { return _this.onSelection(e); } });
    };
    class_2.prototype.header = function () {
        var _this = this;
        return this.mode === 'batch' && this.showCheckAll ?
            h("anj-row-select-control", { showCheck: true, rowKey: ALL_ROWS_KEY, mode: this.mode, labelFormatter: this.labelFormatter, ref: function (e) { return _this.headerControl = e; }, onAnjRowSelectClick: function (e) { return _this.onSelectAll(e); } }) : undefined;
    };
    class_2.prototype.selected = function (data) {
        return this.table.selectedRowKeys.includes(data[this.table.rowKey]);
    };
    class_2.prototype.hasDetail = function () {
        return !!(this.template || this.renderer || this.formatter);
    };
    class_2.prototype.useAsRenderer = function (data) {
        return (this.hasDetail() && this.selected(data));
    };
    class_2.prototype.render = function () {
        var _this = this;
        return h("anj-column", { filterable: false, internal: true, pinned: "left", editable: false, sizable: false, pinnable: false, orderable: false, selectable: false, sortable: false, name: "row-selection" + (this.showChecks ? '-checks' : ''), width: this.showChecks ? '42px' : '0', cellRenderer: function (data) { return _this.cell(data); }, headerRenderer: function () { return _this.header(); } });
    };
    Object.defineProperty(class_2.prototype, "element", {
        get: function () { return getElement(this); },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(class_2, "style", {
        get: function () { return ".anj-table .anj-table-body .anj-row{cursor:default}.anj-table .anj-table-body .anj-row.anj-selectable.anj-selected,.anj-table .anj-table-body .anj-row.anj-selectable.anj-selected:hover{background-color:var(--anj-background)}.anj-table .anj-cell.anj-col-row-selection,.anj-table .anj-header-cell.anj-col-row-selection{border-right:0!important;padding-left:0;padding-right:0;white-space:nowrap;width:0!important}.anj-table .anj-cell.anj-col-row-selection .anj-column-caption,.anj-table .anj-header-cell.anj-col-row-selection .anj-column-caption{display:none}.anj-table .anj-cell.anj-col-row-selection-checks,.anj-table .anj-header-cell.anj-col-row-selection-checks{width:42px}.anj-table .anj-col-row-selection-checks.anj-header-cell .anj-column-caption{overflow:visible;padding-right:0}.anj-table .anj-col-row-selection-checks.anj-header-cell anj-row-select-control[show-check]{margin:-1px 0}.anj-table .anj-col-row-selection-checks.anj-header-cell anj-checkbox{margin:-1px 0;top:1px}.anj-table .anj-col-row-selection-checks.anj-cell anj-checkbox{margin:-1px 0;top:2px}.anj-table .anj-col-row-selection-checks.anj-cell anj-radio{top:-3px}.anj-table .anj-col-row-selection-checks anj-checkbox{font-size:.875rem;position:relative}.anj-table .anj-row-detail-cell{border-color:transparent!important}.anj-table anj-table .anj-row:last-child .anj-cell{border-bottom:0;border-color:transparent!important}.anj-table .anj-detail-row:hover{background-color:inherit}"; },
        enumerable: true,
        configurable: true
    });
    return class_2;
}());
export { RowSelectControl as anj_row_select_control, RowSelection as anj_row_selection };
