export function beforeKeyDownHandler(grid) {
    return function (e) {
        const table = this;
        const payload = toKeydownPayload(e, grid);
        const { cancel, key } = payload;
        grid.fire({ type: 'GRID/keydown', payload });
        if (grid.isEditing) {
            e.stopImmediatePropagation();
        }
        const last = table.getSelectedLast();
        if (last && !grid.isEditing) {
            const row = last[0];
            const column = last[1];
            if (key === 'ArrowUp' && row === 0) {
                cancel();
            }
            if (key === 'ArrowLeft' && column === 0) {
                cancel();
            }
            if (key === 'ArrowDown' && row === grid.totalRows - 1) {
                cancel();
            }
            if (key === 'ArrowRight' && column === grid.totalColumns - 1) {
                cancel();
            }
            if (key === 'Backspace' || key === 'Delete') {
                handleDelete({ grid, keydown: payload });
            }
        }
    };
}
function toKeydownPayload(e, grid) {
    const event = e;
    const key = event.key;
    const isEnter = key === 'Enter';
    const isEscape = key === 'Escape';
    const isDelete = key === 'Delete';
    const { metaKey, shiftKey, ctrlKey, altKey } = event;
    const payload = {
        key,
        grid,
        event,
        isEnter,
        isEscape,
        isDelete,
        metaKey,
        shiftKey,
        ctrlKey,
        altKey,
        isCancelled: false,
        cancel: () => {
            e.preventDefault();
            e.stopImmediatePropagation();
            payload.isCancelled = true;
        },
    };
    return payload;
}
function handleDelete(args) {
    const { grid, keydown } = args;
    keydown.cancel();
    const deleted = {};
    Object.keys(grid.selectionValues).forEach((key) => (deleted[key] = undefined));
    grid.changeCells(deleted, { source: 'DELETE' });
}
