var __awaiter = this && this.__awaiter || function(thisArg, _arguments, P, generator) {
    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) {
            var value;
            result.done ? resolve(result.value) : (value = result.value, value instanceof P ? value : new P((function(resolve) {
                resolve(value);
            }))).then(fulfilled, rejected);
        }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    }));
};

import { isValid } from "@visactor/vutils";

import { InteractionState } from "../../ts-types";

import { TABLE_EVENT_TYPE } from "../../core/TABLE_EVENT_TYPE";

import { handleWhell } from "../scroll";

import { getPromiseValue } from "../../tools/helper";

import { getPixelRatio } from "../../tools/pixel-ratio";

import { endResizeCol, endResizeRow } from "./table-group";

import { isCellDisableSelect } from "../../state/select/is-cell-select-highlight";

import { fireMoveColEventListeners } from "../helper";

import { vglobal } from "./../../vrender";

export function bindContainerDomListener(eventManager) {
    const table = eventManager.table, stateManager = table.stateManager, handler = table.internalProps.handler;
    function handleKeydownListener(e) {
        var _a;
        if (table.hasListeners(TABLE_EVENT_TYPE.KEYDOWN)) {
            const cellsEvent = {
                keyCode: null !== (_a = e.keyCode) && void 0 !== _a ? _a : e.which,
                code: e.code,
                event: e,
                scaleRatio: table.canvas.getBoundingClientRect().width / table.canvas.offsetWidth
            };
            table.fireListeners(TABLE_EVENT_TYPE.KEYDOWN, cellsEvent);
        }
    }
    handler.on(table.getElement(), "blur", (e => {
        eventManager.dealTableHover();
    })), handler.on(table.getElement(), "keydown", (e => {
        var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _0, _1, _2, _3, _4, _5, _6, _7, _8, _9;
        const beforeKeydownEvent = {
            keyCode: null !== (_a = e.keyCode) && void 0 !== _a ? _a : e.which,
            code: e.code,
            event: e
        };
        if (table.fireListeners(TABLE_EVENT_TYPE.BEFORE_KEYDOWN, beforeKeydownEvent), "a" === e.key && (e.ctrlKey || e.metaKey)) (null === (_b = table.keyboardOptions) || void 0 === _b ? void 0 : _b.selectAllOnCtrlA) && (e.preventDefault(), 
        eventManager.deelTableSelectAll()); else if (stateManager.select.cellPos.col >= 0 && stateManager.select.cellPos.row >= 0 && ("ArrowUp" === e.key || "ArrowDown" === e.key || "ArrowLeft" === e.key || "ArrowRight" === e.key)) {
            if ((null === (_d = null === (_c = table.options.keyboardOptions) || void 0 === _c ? void 0 : _c.moveEditCellOnArrowKeys) || void 0 === _d || !_d) && (null === (_e = table.editorManager) || void 0 === _e ? void 0 : _e.editingEditor) || !1 === (null === (_f = table.options.keyboardOptions) || void 0 === _f ? void 0 : _f.moveSelectedCellOnArrowKeys)) return;
            let targetCol, targetRow;
            if (e.preventDefault(), e.stopPropagation(), "ArrowUp" === e.key ? e.ctrlKey || e.metaKey ? (targetCol = stateManager.select.cellPos.col, 
            targetRow = 0) : (e.shiftKey, targetCol = stateManager.select.cellPos.col, targetRow = Math.min(table.rowCount - 1, Math.max(0, stateManager.select.cellPos.row - 1))) : "ArrowDown" === e.key ? e.ctrlKey || e.metaKey ? (targetCol = stateManager.select.cellPos.col, 
            targetRow = table.rowCount - 1) : (e.shiftKey, targetCol = stateManager.select.cellPos.col, 
            targetRow = Math.min(table.rowCount - 1, Math.max(0, stateManager.select.cellPos.row + 1))) : "ArrowLeft" === e.key ? e.ctrlKey || e.metaKey ? (targetCol = 0, 
            targetRow = stateManager.select.cellPos.row) : (e.shiftKey, targetRow = stateManager.select.cellPos.row, 
            targetCol = Math.min(table.colCount - 1, Math.max(0, stateManager.select.cellPos.col - 1))) : "ArrowRight" === e.key && (e.ctrlKey || e.metaKey ? (targetCol = table.colCount - 1, 
            targetRow = stateManager.select.cellPos.row) : (e.shiftKey, targetRow = stateManager.select.cellPos.row, 
            targetCol = Math.min(table.colCount - 1, Math.max(0, stateManager.select.cellPos.col + 1)))), 
            isCellDisableSelect(table, targetCol, targetRow)) return;
            const enableShiftSelectMode = null === (_h = null === (_g = table.options.keyboardOptions) || void 0 === _g ? void 0 : _g.shiftMultiSelect) || void 0 === _h || _h;
            table.selectCell(targetCol, targetRow, e.shiftKey && enableShiftSelectMode), null !== (_k = null === (_j = table.options.keyboardOptions) || void 0 === _j ? void 0 : _j.moveEditCellOnArrowKeys) && void 0 !== _k && _k && (null === (_l = table.editorManager) || void 0 === _l ? void 0 : _l.editingEditor) && (null === (_m = table.editorManager) || void 0 === _m || _m.completeEdit(), 
            table.getElement().focus(), table.getEditor(targetCol, targetRow) && (null === (_o = table.editorManager) || void 0 === _o || _o.startEditCell(targetCol, targetRow)));
        } else if ("Escape" === e.key) null === (_p = table.editorManager) || void 0 === _p || _p.cancelEdit(), 
        table.getElement().focus(); else if ("Enter" === e.key) {
            if (null === (_q = table.editorManager) || void 0 === _q ? void 0 : _q.editingEditor) {
                if (handleKeydownListener(e), null === (_r = table.editorManager) || void 0 === _r || _r.completeEdit(), 
                table.getElement().focus(), !0 === (null === (_s = table.options.keyboardOptions) || void 0 === _s ? void 0 : _s.moveFocusCellOnEnter)) {
                    const targetCol = stateManager.select.cellPos.col, targetRow = Math.min(table.rowCount - 1, Math.max(0, stateManager.select.cellPos.row + 1));
                    if (isCellDisableSelect(table, targetCol, targetRow)) return;
                    const enableShiftSelectMode = null === (_u = null === (_t = table.options.keyboardOptions) || void 0 === _t ? void 0 : _t.shiftMultiSelect) || void 0 === _u || _u;
                    table.selectCell(targetCol, targetRow, e.shiftKey && enableShiftSelectMode);
                }
                return;
            }
            if (!0 === (null === (_v = table.options.keyboardOptions) || void 0 === _v ? void 0 : _v.moveFocusCellOnEnter)) {
                const targetCol = stateManager.select.cellPos.col, targetRow = Math.min(table.rowCount - 1, Math.max(0, stateManager.select.cellPos.row + 1));
                if (isCellDisableSelect(table, targetCol, targetRow)) return;
                const enableShiftSelectMode = null === (_x = null === (_w = table.options.keyboardOptions) || void 0 === _w ? void 0 : _w.shiftMultiSelect) || void 0 === _x || _x;
                table.selectCell(targetCol, targetRow, e.shiftKey && enableShiftSelectMode);
            } else if ((null === (_z = null === (_y = table.options.keyboardOptions) || void 0 === _y ? void 0 : _y.editCellOnEnter) || void 0 === _z || _z) && 1 === (null !== (_1 = null === (_0 = table.stateManager.select.ranges) || void 0 === _0 ? void 0 : _0.length) && void 0 !== _1 ? _1 : 0)) {
                const startCol = table.stateManager.select.ranges[0].start.col, startRow = table.stateManager.select.ranges[0].start.row, endCol = table.stateManager.select.ranges[0].end.col, endRow = table.stateManager.select.ranges[0].end.row;
                startCol === endCol && startRow === endRow && table.getEditor(startCol, startRow) && (null === (_2 = table.editorManager) || void 0 === _2 || _2.startEditCell(startCol, startRow));
            }
        } else if ("Tab" === e.key) {
            if ((null === (_4 = null === (_3 = table.options.keyboardOptions) || void 0 === _3 ? void 0 : _3.moveFocusCellOnTab) || void 0 === _4 || _4) && stateManager.select.cellPos.col >= 0 && stateManager.select.cellPos.row >= 0) {
                if (stateManager.select.cellPos.col === table.colCount - 1 && stateManager.select.cellPos.row === table.rowCount - 1) return;
                let targetCol, targetRow;
                if (e.preventDefault(), stateManager.select.cellPos.col === table.colCount - 1 ? (targetRow = Math.min(table.rowCount - 1, stateManager.select.cellPos.row + 1), 
                targetCol = table.rowHeaderLevelCount) : (targetRow = stateManager.select.cellPos.row, 
                targetCol = stateManager.select.cellPos.col + 1), isCellDisableSelect(table, targetCol, targetRow)) return;
                table.selectCell(targetCol, targetRow), (null === (_5 = table.editorManager) || void 0 === _5 ? void 0 : _5.editingEditor) && (null === (_6 = table.editorManager) || void 0 === _6 || _6.completeEdit(), 
                table.getElement().focus(), table.getEditor(targetCol, targetRow) && (null === (_7 = table.editorManager) || void 0 === _7 || _7.startEditCell(targetCol, targetRow)));
            }
        } else if (!e.ctrlKey && !e.metaKey) {
            const editCellTrigger = table.options.editCellTrigger;
            if (("keydown" === editCellTrigger || Array.isArray(editCellTrigger) && editCellTrigger.includes("keydown")) && !(null === (_8 = table.editorManager) || void 0 === _8 ? void 0 : _8.editingEditor)) {
                const allowedKeys = /^[a-zA-Z0-9+\-*\/%=.,\s]$/;
                e.key.match(allowedKeys) && (table.editorManager && (table.editorManager.beginTriggerEditCellMode = "keydown"), 
                null === (_9 = table.editorManager) || void 0 === _9 || _9.startEditCell(stateManager.select.cellPos.col, stateManager.select.cellPos.row, ""));
            }
        }
        handleKeydownListener(e);
    })), handler.on(table.getElement(), "copy", (e => __awaiter(this, void 0, void 0, (function*() {
        var _a;
        (null === (_a = table.keyboardOptions) || void 0 === _a ? void 0 : _a.copySelected) && eventManager.handleCopy(e);
    })))), handler.on(table.getElement(), "cut", (e => __awaiter(this, void 0, void 0, (function*() {
        var _b;
        (null === (_b = table.keyboardOptions) || void 0 === _b ? void 0 : _b.cutSelected) && eventManager.handleCut(e);
    })))), handler.on(table.getElement(), "paste", (e => __awaiter(this, void 0, void 0, (function*() {
        var _c;
        (null === (_c = table.keyboardOptions) || void 0 === _c ? void 0 : _c.pasteValueToCell) && eventManager.handlePaste(e);
    })))), handler.on(table.getElement(), "contextmenu", (e => {
        var _a;
        !1 !== (null === (_a = table.eventOptions) || void 0 === _a ? void 0 : _a.preventDefaultContextMenu) ? e.preventDefault() : globalPointerupCallback(e);
    })), table.options.canvas || handler.on(table.getContainer(), "resize", (e => {
        var _a;
        table.isReleased || 0 === e.width && 0 === e.height || ((table.autoFillWidth || table.autoFillHeight || "adaptive" === table.widthMode || "adaptive" === table.heightMode) && (null === (_a = table.editorManager) || void 0 === _a || _a.completeEdit()), 
        isValid(table.options.pixelRatio) || table.setPixelRatio(getPixelRatio()), e.windowSizeNotChange || table.resize());
    }));
    const globalPointerdownCallback = e => {
        var _a;
        if (table.isReleased) return;
        table.eventManager.LastBodyPointerXY = {
            x: e.x,
            y: e.y
        }, table.eventManager.isDown = !0;
        const target = e.target;
        if (!table.getElement().contains(target) && !table.internalProps.menuHandler.containElement(target)) {
            const isCompleteEdit = null === (_a = table.editorManager) || void 0 === _a ? void 0 : _a.completeEdit(e);
            getPromiseValue(isCompleteEdit, (isCompleteEdit => {
                var _a, _b;
                if (!1 !== isCompleteEdit && (null === (_a = table.options.select) || void 0 === _a ? void 0 : _a.outsideClickDeselect)) {
                    const isHasSelected = !!(null === (_b = stateManager.select.ranges) || void 0 === _b ? void 0 : _b.length);
                    eventManager.dealTableSelect(), stateManager.endSelectCells(!0, isHasSelected);
                }
            }));
        }
    };
    eventManager.globalEventListeners.push({
        name: "pointerdown",
        env: "vglobal",
        callback: globalPointerdownCallback
    }), vglobal.addEventListener("pointerdown", globalPointerdownCallback);
    const globalPointerupCallback = e => {
        var _a, _b;
        if (table.isReleased) return;
        const target = e.target;
        if (target !== table.canvas && (e => {
            var _a, _b;
            if (stateManager.menu.isShow && setTimeout((() => {
                table.internalProps.menuHandler.pointInMenuElement(e.clientX, e.clientY) || stateManager.menu.isShow && stateManager.hideMenu();
            }), 0), stateManager.isResizeCol()) endResizeCol(table); else if (stateManager.isResizeRow()) endResizeRow(table); else if (stateManager.isMoveCol()) {
                const endMoveColSuccess = table.stateManager.endMoveCol();
                fireMoveColEventListeners(table, endMoveColSuccess, e);
            } else if (stateManager.isSelecting() && (null === (_b = null === (_a = table.stateManager.select) || void 0 === _a ? void 0 : _a.ranges) || void 0 === _b ? void 0 : _b.length)) {
                const lastCol = table.stateManager.select.ranges[table.stateManager.select.ranges.length - 1].end.col, lastRow = table.stateManager.select.ranges[table.stateManager.select.ranges.length - 1].end.row;
                if (table.stateManager.endSelectCells(), table.hasListeners(TABLE_EVENT_TYPE.DRAG_SELECT_END)) {
                    const cellsEvent = {
                        event: e,
                        cells: [],
                        col: lastCol,
                        row: lastRow,
                        scaleRatio: table.canvas.getBoundingClientRect().width / table.canvas.offsetWidth,
                        target: void 0
                    };
                    cellsEvent.cells = table.getSelectedCellInfos(), table.fireListeners(TABLE_EVENT_TYPE.DRAG_SELECT_END, cellsEvent);
                }
            }
        })(e), table.eventManager.LastBodyPointerXY = null, table.eventManager.isDown = !1, 
        table.eventManager.isDraging = !1, table.eventManager.inertiaScroll.endInertia(), 
        "grabing" === stateManager.interactionState && stateManager.isResizeCol()) endResizeCol(table); else if ("grabing" === stateManager.interactionState && stateManager.isResizeRow()) endResizeRow(table); else if (stateManager.isMoveCol()) {
            const endMoveColSuccess = table.stateManager.endMoveCol();
            fireMoveColEventListeners(table, endMoveColSuccess, e);
        } else if ((null === (_a = table.editorManager) || void 0 === _a ? void 0 : _a.editingEditor) && !table.getElement().contains(target)) {
            const isCompleteEdit = null === (_b = table.editorManager) || void 0 === _b ? void 0 : _b.completeEdit(e);
            getPromiseValue(isCompleteEdit, (isCompleteEdit => {
                !1 !== isCompleteEdit && (stateManager.updateInteractionState(InteractionState.default), 
                eventManager.dealTableHover());
            }));
        }
        stateManager.updateInteractionState(InteractionState.default);
    };
    eventManager.globalEventListeners.push({
        name: "pointerup",
        env: "vglobal",
        callback: globalPointerupCallback
    }), vglobal.addEventListener("pointerup", globalPointerupCallback);
    const globalPointermoveCallback = e => {
        var _a, _b, _c, _d, _e;
        if (table.eventManager.isDown && table.eventManager.LastBodyPointerXY) {
            const lastX = null !== (_b = null === (_a = table.eventManager.LastBodyPointerXY) || void 0 === _a ? void 0 : _a.x) && void 0 !== _b ? _b : e.x, lastY = null !== (_d = null === (_c = table.eventManager.LastBodyPointerXY) || void 0 === _c ? void 0 : _c.y) && void 0 !== _d ? _d : e.y;
            (Math.abs(lastX - e.x) > 1 || Math.abs(lastY - e.y) > 1) && (table.eventManager.isDraging = !0);
        }
        const {x: x, y: y} = table._getMouseAbstractPoint(e);
        stateManager.interactionState === InteractionState.grabing && (stateManager.isResizeCol() ? (eventManager.dealColumnResize(x, y), 
        table.hasListeners(TABLE_EVENT_TYPE.RESIZE_COLUMN) && table.fireListeners(TABLE_EVENT_TYPE.RESIZE_COLUMN, {
            col: table.stateManager.columnResize.col,
            colWidth: table.getColWidth(table.stateManager.columnResize.col)
        })) : stateManager.isResizeRow() ? (eventManager.dealRowResize(x, y), table.hasListeners(TABLE_EVENT_TYPE.RESIZE_ROW) && table.fireListeners(TABLE_EVENT_TYPE.RESIZE_ROW, {
            row: table.stateManager.rowResize.row,
            rowHeight: table.getRowHeight(table.stateManager.rowResize.row)
        })) : stateManager.isMoveCol() && eventManager.dealColumnMover(x, y, e));
        const isSelecting = table.stateManager.isSelecting();
        if (eventManager._enableTableScroll && eventManager.isDraging && isSelecting && (null === (_e = table.stateManager.select.ranges) || void 0 === _e ? void 0 : _e.length) > 0) {
            const drawRange = table.getDrawRange(), topFrozenRowHeight = table.getFrozenRowsHeight(), bottomFrozenRowHeight = table.getBottomFrozenRowsHeight(), leftFrozenColsWidth = table.getFrozenColsWidth(), rightFrozenColsWidth = table.getRightFrozenColsWidth(), startCell = table.stateManager.select.ranges[table.stateManager.select.ranges.length - 1].start;
            if (table.isSeriesNumber(startCell.col, startCell.row)) return;
            const endCell = table.stateManager.select.ranges[table.stateManager.select.ranges.length - 1].end, canScrollY = (!1 === table.isFrozenRow(startCell.row) || !1 === table.isFrozenRow(endCell.row)) && table.getAllRowsHeight() > table.tableNoFrameHeight, canScrollX = (!1 === table.isFrozenColumn(startCell.col) || !1 === table.isFrozenColumn(endCell.col)) && table.getAllColsWidth() > table.tableNoFrameWidth;
            if ((y > drawRange.bottom - bottomFrozenRowHeight || y < drawRange.top + topFrozenRowHeight) && canScrollY || (x > drawRange.right - rightFrozenColsWidth || x < drawRange.left + leftFrozenColsWidth) && canScrollX) {
                table.eventManager.scrollXSpeed = 0, table.eventManager.scrollYSpeed = 0;
                let bottom = !1, top = !1, right = !1, left = !1;
                y > drawRange.bottom - bottomFrozenRowHeight && canScrollY && table.scrollTop + table.tableNoFrameHeight < table.getAllRowsHeight() ? (bottom = !0, 
                table.eventManager.scrollYSpeed = -(y - drawRange.bottom + bottomFrozenRowHeight) / 50) : y < drawRange.top + topFrozenRowHeight && canScrollY && table.scrollTop > 0 && (top = !0, 
                table.eventManager.scrollYSpeed = -(y - drawRange.top - topFrozenRowHeight) / 50), 
                x > drawRange.right - rightFrozenColsWidth && canScrollX && table.scrollLeft + table.tableNoFrameWidth < table.getAllColsWidth() ? (right = !0, 
                table.eventManager.scrollXSpeed = -(x - drawRange.right + rightFrozenColsWidth) / 50) : x < drawRange.left + leftFrozenColsWidth && canScrollX && table.scrollLeft > 0 && (left = !0, 
                table.eventManager.scrollXSpeed = -(x - drawRange.left - leftFrozenColsWidth) / 50), 
                table.eventManager.inertiaScroll.startInertia(table.eventManager.scrollXSpeed, table.eventManager.scrollYSpeed, 1), 
                table.eventManager.inertiaScroll.setScrollHandle(((dx, dy) => {
                    var _a;
                    let selectX, selectY;
                    handleWhell({
                        deltaX: -dx,
                        deltaY: -dy
                    }, table.stateManager, !1), bottom ? selectY = table.scrollTop + drawRange.height - bottomFrozenRowHeight - 20 : top && (selectY = table.scrollTop + topFrozenRowHeight + 20), 
                    right ? selectX = table.scrollLeft + drawRange.width - rightFrozenColsWidth - 20 : left && (selectX = table.scrollLeft + leftFrozenColsWidth + 20);
                    let considerFrozenY = !1, considerFrozenX = !1;
                    right || left || (x > table.tableNoFrameWidth - table.getRightFrozenColsWidth() && x < table.tableNoFrameWidth || x > 0 && x < table.getFrozenColsWidth() ? (selectX = x, 
                    considerFrozenX = !0) : selectX = table.scrollLeft + x), bottom || top || (y > table.tableNoFrameHeight - table.getBottomFrozenRowsHeight() && y < table.tableNoFrameHeight || y > 0 && y < table.getFrozenRowsHeight() ? (selectY = y, 
                    considerFrozenY = !0) : selectY = table.scrollTop + y), table.stateManager.updateInteractionState(InteractionState.grabing);
                    const targetCol = table.getTargetColAtConsiderRightFrozen(selectX, considerFrozenX), targetRow = table.getTargetRowAtConsiderBottomFrozen(selectY, considerFrozenY);
                    !(null === (_a = table.options.select) || void 0 === _a ? void 0 : _a.disableDragSelect) && isValid(targetCol) && isValid(targetRow) && table.stateManager.updateSelectPos("row" === table.stateManager.select.selectInline ? table.colCount - 1 : targetCol.col, "col" === table.stateManager.select.selectInline ? table.rowCount - 1 : targetRow.row, !1, !1, !1, !1);
                }));
            } else table.eventManager.inertiaScroll.isInertiaScrolling() ? table.eventManager.inertiaScroll.endInertia() : table.eventManager.scrollYSpeed = 0;
        }
    };
    eventManager.globalEventListeners.push({
        name: "pointermove",
        env: "vglobal",
        callback: globalPointermoveCallback
    }), vglobal.addEventListener("pointermove", globalPointermoveCallback);
}
//# sourceMappingURL=container-dom.js.map
