'use strict';

Object.defineProperty(exports, '__esModule', { value: true });

const core = require('./core-bc7a73f4.js');
require('./utils-2a7c8f6e.js');
const table_utils = require('./table.utils-12a2d306.js');
const i18n_provider = require('./i18n.provider-c74c1600.js');
require('./column.renderer-5a4e3cf2.js');
const row = require('./row-a856f0a2.js');
const a11y = require('./a11y-fb385a78.js');

var Translations;
(function (Translations) {
    Translations["DESELECT"] = "Deselect";
    Translations["SELECT"] = "Select";
})(Translations || (Translations = {}));
const RowSelectControl = class {
    constructor(hostRef) {
        core.registerInstance(this, hostRef);
        this.clickListener = (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 = core.createEvent(this, "anjRowSelectClick", 7);
    }
    onSelected() {
        if (!this.rowEl || this.checkOnly()) {
            return;
        }
        if (this.selected) {
            this.rowEl.classList.add('anj-selected');
        }
        else {
            this.rowEl.classList.remove('anj-selected');
        }
    }
    async componentDidLoad() {
        this.rowEl = this.element.parentElement.parentElement;
        this.onSelected();
        if (!this.checkOnly()) {
            this.rowEl.classList.add('anj-selectable');
            this.rowEl.addEventListener('click', this.clickListener);
        }
    }
    componentDidUnload() {
        if (!this.checkOnly()) {
            this.rowEl.removeEventListener('click', this.clickListener);
        }
    }
    onRowSelect(event) {
        if (event && event instanceof MouseEvent && event.composedPath().find((e) => e.tagName !== 'TR' && a11y.isFocusable(e))) {
            return;
        }
        const checkbox = event ? event.target : undefined;
        if (!checkbox || checkbox.checked !== this.selected) {
            this.selected = checkbox ? checkbox.checked : !this.selected;
            this.anjRowSelectClick.emit({ key: table_utils.keyFromData(this.rowKey) });
        }
    }
    defaultLabelFormatter(key, selected) {
        return selected ? `${this.translator(Translations.DESELECT)}: ${key}` : `${this.translator(Translations.SELECT)}: ${key}`;
    }
    checkOnly() {
        return (this.mode === 'batch' && this.showCheck);
    }
    render() {
        if (!this.showCheck)
            return;
        const label = this.labelFormatter(this.rowKey, this.selected);
        const className = 'anj-selection-control';
        return this.mode === 'batch' ?
            core.h("anj-checkbox", { value: `${this.rowKey}`, name: `${this.rowKey}-selected`, checked: this.selected, solo: true, "aria-label": label, class: className })
            : core.h("anj-radio", { value: `${this.rowKey}`, class: className, checked: this.selected, "aria-label": label, name: "anj-row-select", solo: true });
    }
    get element() { return core.getElement(this); }
    static get watchers() { return {
        "selected": ["onSelected"]
    }; }
    static get style() { return "anj-row-select-control[mode=batch]{display:block;line-height:1;margin:0 0 -1px}"; }
};
i18n_provider.Tunnel.injectProps(RowSelectControl, ['translator']);

const RowSelection = class {
    constructor(hostRef) {
        core.registerInstance(this, hostRef);
        this.rowsDidChangeListener = () => 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 = core.createEvent(this, "anjRowControlDidLoad", 7);
        this.anjRowSelect = core.createEvent(this, "anjRowSelect", 7);
    }
    connectedCallback() {
        this.table = this.element.closest('anj-table');
        this.table.addEventListener('anjRowsDidLoad', this.rowsDidChangeListener);
    }
    componentDidLoad() {
        this.anjRowControlDidLoad.emit();
    }
    disconnectedCallback() {
        this.table.removeEventListener('anjRowsDidLoad', this.rowsDidChangeListener);
    }
    static clearStyles(el) {
        if (el) {
            el.removeAttribute('style');
        }
    }
    onRowsDidChange() {
        if (this.headerControl) {
            return this.checkSelectAll();
        }
    }
    async onSelection(event) {
        event.stopPropagation();
        const detail = event.detail;
        this.table.selectedRowKeys = this.table.selectedRowKeys.includes(detail.key) ? this.table.selectedRowKeys.filter(k => k !== detail.key)
            : (this.mode === 'batch') ? this.table.selectedRowKeys.concat([detail.key]) : [detail.key];
        if (this.mode === 'batch' && this.showCheckAll) {
            await this.checkSelectAll();
        }
        this.anjRowSelect.emit({ key: detail.key, selectedRowKeys: this.table.selectedRowKeys });
    }
    async onSelectAll(event) {
        event.stopPropagation();
        const checkbox = this.headerControl.querySelector('anj-checkbox');
        const rows = await this.table.getRows();
        const rowKeys = rows.map(r => r[this.table.rowKey]);
        const selectAll = (checkbox.checked || checkbox.indeterminate);
        this.table.selectedRowKeys = selectAll
            ? this.table.selectedRowKeys.concat(rowKeys.filter(k => !this.table.selectedRowKeys.includes(k)))
            : this.table.selectedRowKeys.filter(k => !rowKeys.includes(k));
        this.anjRowSelect.emit({ key: undefined, selectedRowKeys: this.table.selectedRowKeys });
        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.
     */
    async checkSelectAll(rs, keys, check) {
        const rows = rs || await this.table.getRows();
        const checkbox = check || this.headerControl.querySelector('anj-checkbox');
        const rowKeys = keys || rows.map(r => r[this.table.rowKey]);
        const selectedKeys = rowKeys.filter(k => 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;
    }
    renderRow(props) {
        const attrs = { colspan: props.columns.length - 1 };
        // The first cell is a dummy cell to keep things kosher
        return (core.h(row.Row, Object.assign({}, props), core.h("tr", { class: table_utils.TableClasses.detailRow }, core.h("td", { style: { border: '0', 'border-color': 'transparent', width: '0', padding: '0' } }), core.h("td", Object.assign({}, attrs, { class: table_utils.TableClasses.detailCell, ref: (r) => { RowSelection.clearStyles(r); } }), core.h("div", { class: table_utils.TableClasses.detailWrapper }, this.template
            ? core.h("div", { class: table_utils.TableClasses.detail, ref: r => this.table.renderer.fromTemplate(this.template, r, props.row, props.rowIndex) })
            : this.formatter ? core.h("div", { class: table_utils.TableClasses.detail, innerHTML: this.formatter(props.row, props.rowIndex) })
                : core.h("div", { class: table_utils.TableClasses.detail }, this.renderer(props.row, props.rowIndex)))))));
    }
    cell(data) {
        return core.h("anj-row-select-control", { showCheck: this.showChecks, rowKey: data[this.table.rowKey], selected: this.selected(data), mode: this.mode, labelFormatter: this.labelFormatter, onAnjRowSelectClick: e => this.onSelection(e) });
    }
    header() {
        return this.mode === 'batch' && this.showCheckAll ?
            core.h("anj-row-select-control", { showCheck: true, rowKey: table_utils.ALL_ROWS_KEY, mode: this.mode, labelFormatter: this.labelFormatter, ref: e => this.headerControl = e, onAnjRowSelectClick: e => this.onSelectAll(e) }) : undefined;
    }
    selected(data) {
        return this.table.selectedRowKeys.includes(data[this.table.rowKey]);
    }
    hasDetail() {
        return !!(this.template || this.renderer || this.formatter);
    }
    useAsRenderer(data) {
        return (this.hasDetail() && this.selected(data));
    }
    render() {
        return core.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: (data) => this.cell(data), headerRenderer: () => this.header() });
    }
    get element() { return core.getElement(this); }
    static get style() { 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}"; }
};

exports.anj_row_select_control = RowSelectControl;
exports.anj_row_selection = RowSelection;
