import { r as registerInstance, d as createEvent, c as getElement } from './core-1db051ba.js';
import { i as enterAsClick } from './utils-3aef1637.js';
import { T as Tunnel } from './i18n.provider-15e382c4.js';
import { k as keyFromData } from './table.utils-110cc530.js';

const CELL_SELECTOR = 'td.anj-selectable';
var Translations;
(function (Translations) {
    Translations["SELECT_CELL"] = "Select Cell";
})(Translations || (Translations = {}));
const CellSelection = class {
    constructor(hostRef) {
        registerInstance(this, hostRef);
        this.cellClickListener = (e) => this.onCellClick(e);
        this.cellKeyListener = enterAsClick(this.onCellClick.bind(this));
        this.tableWillUpdateListener = () => this.onTableWillChange();
        this.tableDidUpdateListener = () => this.onTableDidChange();
        this.anjCellSelect = 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 = keyFromData(cell.dataset.rowKey);
        this.anjCellSelect.emit({ cell, columnField, rowKey });
    }
    get element() { return getElement(this); }
};
Tunnel.injectProps(CellSelection, ['translator']);

export { CellSelection as anj_cell_selection };
