'use strict';

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

const core = require('./core-b7b9d752.js');
const utils = require('./utils-2a7c8f6e.js');
const i18n_provider = require('./i18n.provider-5632e5ed.js');
const table_utils = require('./table.utils-12a2d306.js');

const CELL_SELECTOR = 'td.anj-selectable';
var Translations;
(function (Translations) {
    Translations["SELECT_CELL"] = "Select Cell";
})(Translations || (Translations = {}));
const CellSelection = class {
    constructor(hostRef) {
        core.registerInstance(this, hostRef);
        this.cellClickListener = (e) => this.onCellClick(e);
        this.cellKeyListener = utils.enterAsClick(this.onCellClick.bind(this));
        this.tableWillUpdateListener = () => this.onTableWillChange();
        this.tableDidUpdateListener = () => this.onTableDidChange();
        this.anjCellSelect = core.createEvent(this, "anjCellSelect", 7);
    }
    componentWillLoad() {
        this.table = this.element.closest('anj-table');
    }
    componentDidLoad() {
        this.table.addEventListener('anjTableWillUpdate', this.tableWillUpdateListener);
        this.table.addEventListener('anjTableDidUpdate', this.tableDidUpdateListener);
    }
    componentDidUnload() {
        this.onTableWillChange();
        this.table.removeEventListener('anjTableWillUpdate', this.tableWillUpdateListener);
        this.table.removeEventListener('anjTableDidUpdate', this.tableDidUpdateListener);
    }
    onTableWillChange() {
        Array.from(this.table.querySelectorAll(CELL_SELECTOR)).forEach((el) => {
            el.removeEventListener('click', this.cellClickListener);
            el.removeEventListener('keyup', this.cellKeyListener);
        });
    }
    onTableDidChange() {
        Array.from(this.table.querySelectorAll(CELL_SELECTOR)).forEach((el) => {
            el.tabIndex = 0;
            el.setAttribute('aria-label', this.translator(Translations.SELECT_CELL));
            el.addEventListener('click', this.cellClickListener);
            el.addEventListener('keyup', this.cellKeyListener);
        });
    }
    onCellClick(event) {
        const target = event.target;
        const cell = target.tagName === 'TD' ? target : target.closest('td');
        const columnField = cell.dataset.columnField;
        const rowKey = table_utils.keyFromData(cell.dataset.rowKey);
        this.anjCellSelect.emit({ cell, columnField, rowKey });
    }
    get element() { return core.getElement(this); }
};
i18n_provider.Tunnel.injectProps(CellSelection, ['translator']);

exports.anj_cell_selection = CellSelection;
