"use strict";

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());
    }));
};

Object.defineProperty(exports, "__esModule", {
    value: !0
}), exports.bindContainerDomListener = void 0;

const vutils_1 = require("@visactor/vutils"), ts_types_1 = require("../../ts-types"), TABLE_EVENT_TYPE_1 = require("../../core/TABLE_EVENT_TYPE"), scroll_1 = require("../scroll"), helper_1 = require("../../tools/helper"), pixel_ratio_1 = require("../../tools/pixel-ratio"), table_group_1 = require("./table-group"), is_cell_select_highlight_1 = require("../../state/select/is-cell-select-highlight"), helper_2 = require("../helper"), vrender_1 = require("./../../vrender");

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_1.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_1.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;
        const beforeKeydownEvent = {
            keyCode: null !== (_a = e.keyCode) && void 0 !== _a ? _a : e.which,
            code: e.code,
            event: e
        };
        if (table.fireListeners(TABLE_EVENT_TYPE_1.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)))), 
            (0, is_cell_select_highlight_1.isCellDisableSelect)(table, targetCol, targetRow)) return;
            table.selectCell(targetCol, targetRow, e.shiftKey), null !== (_h = null === (_g = table.options.keyboardOptions) || void 0 === _g ? void 0 : _g.moveEditCellOnArrowKeys) && void 0 !== _h && _h && (null === (_j = table.editorManager) || void 0 === _j ? void 0 : _j.editingEditor) && (null === (_k = table.editorManager) || void 0 === _k || _k.completeEdit(), 
            table.getElement().focus(), table.getEditor(targetCol, targetRow) && (null === (_l = table.editorManager) || void 0 === _l || _l.startEditCell(targetCol, targetRow)));
        } else if ("Escape" === e.key) null === (_m = table.editorManager) || void 0 === _m || _m.cancelEdit(), 
        table.getElement().focus(); else if ("Enter" === e.key) {
            if (null === (_o = table.editorManager) || void 0 === _o ? void 0 : _o.editingEditor) {
                if (handleKeydownListener(e), null === (_p = table.editorManager) || void 0 === _p || _p.completeEdit(), 
                table.getElement().focus(), !0 === (null === (_q = table.options.keyboardOptions) || void 0 === _q ? void 0 : _q.moveFocusCellOnEnter)) {
                    const targetCol = stateManager.select.cellPos.col, targetRow = Math.min(table.rowCount - 1, Math.max(0, stateManager.select.cellPos.row + 1));
                    if ((0, is_cell_select_highlight_1.isCellDisableSelect)(table, targetCol, targetRow)) return;
                    table.selectCell(targetCol, targetRow, e.shiftKey);
                }
                return;
            }
            if (!0 === (null === (_r = table.options.keyboardOptions) || void 0 === _r ? void 0 : _r.moveFocusCellOnEnter)) {
                const targetCol = stateManager.select.cellPos.col, targetRow = Math.min(table.rowCount - 1, Math.max(0, stateManager.select.cellPos.row + 1));
                if ((0, is_cell_select_highlight_1.isCellDisableSelect)(table, targetCol, targetRow)) return;
                table.selectCell(targetCol, targetRow, e.shiftKey);
            } else if ((null === (_t = null === (_s = table.options.keyboardOptions) || void 0 === _s ? void 0 : _s.editCellOnEnter) || void 0 === _t || _t) && 1 === (null !== (_v = null === (_u = table.stateManager.select.ranges) || void 0 === _u ? void 0 : _u.length) && void 0 !== _v ? _v : 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 === (_w = table.editorManager) || void 0 === _w || _w.startEditCell(startCol, startRow));
            }
        } else if ("Tab" === e.key) {
            if ((null === (_y = null === (_x = table.options.keyboardOptions) || void 0 === _x ? void 0 : _x.moveFocusCellOnTab) || void 0 === _y || _y) && 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), (0, is_cell_select_highlight_1.isCellDisableSelect)(table, targetCol, targetRow)) return;
                table.selectCell(targetCol, targetRow), (null === (_z = table.editorManager) || void 0 === _z ? void 0 : _z.editingEditor) && (null === (_0 = table.editorManager) || void 0 === _0 || _0.completeEdit(), 
                table.getElement().focus(), table.getEditor(targetCol, targetRow) && (null === (_1 = table.editorManager) || void 0 === _1 || _1.startEditCell(targetCol, targetRow)));
            }
        } else if (!e.ctrlKey && !e.metaKey) {
            const editCellTrigger = table.options.editCellTrigger;
            if (("keydown" === editCellTrigger || Array.isArray(editCellTrigger) && editCellTrigger.includes("keydown")) && !(null === (_2 = table.editorManager) || void 0 === _2 ? void 0 : _2.editingEditor)) {
                const allowedKeys = /^[a-zA-Z0-9+\-*\/%=.,\s]$/;
                e.key.match(allowedKeys) && (table.editorManager && (table.editorManager.beginTriggerEditCellMode = "keydown"), 
                null === (_3 = table.editorManager) || void 0 === _3 || _3.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, _b;
        if (null === (_a = table.keyboardOptions) || void 0 === _a ? void 0 : _a.copySelected) {
            const data = table.getCopyValue();
            if ((0, vutils_1.isValid)(data)) {
                e.preventDefault();
                const permissionState = yield navigator.permissions.query({
                    name: "clipboard-write"
                });
                if ((null === (_b = navigator.clipboard) || void 0 === _b ? void 0 : _b.write) && "granted" === permissionState.state) {
                    const setDataToHTML = data => {
                        const result = [ "<table>" ], META_HEAD = [ '<meta name="author" content="Visactor"/>', '<style type="text/css">td{white-space:normal}br{mso-data-placement:same-cell}</style>' ].join(""), rows = data.split("\r\n");
                        return rows.forEach((function(rowCells, rowIndex) {
                            const cells = rowCells.split("\t"), rowValues = [];
                            0 === rowIndex && result.push("<tbody>"), cells.forEach((function(cell, cellIndex) {
                                const parsedCellData = cell ? cell.toString().replace(/&/g, "&amp;").replace(/'/g, "&#39;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/\n/g, "<br>").replace(/(<br(\s*|\/)>(\r\n|\n)?|\r\n|\n)/g, "<br>\r\n").replace(/\x20{2,}/gi, (substring => `<span style="mso-spacerun: yes">${"&nbsp;".repeat(substring.length - 1)} </span>`)).replace(/\t/gi, "&#9;") : " ";
                                rowValues.push(`<td>${parsedCellData}</td>`);
                            })), result.push("<tr>", ...rowValues, "</tr>"), rowIndex === rows.length - 1 && result.push("</tbody>");
                        })), result.push("</table>"), [ META_HEAD, result.join("") ].join("");
                    }, dataHTML = setDataToHTML(data);
                    navigator.clipboard.write([ new ClipboardItem({
                        "text/html": new Blob([ dataHTML ], {
                            type: "text/html"
                        }),
                        "text/plain": new Blob([ data ], {
                            type: "text/plain"
                        })
                    }) ]);
                } else helper_1.browser.IE ? window.clipboardData.setData("Text", data) : e.clipboardData.setData("text/plain", data);
                table.fireListeners(TABLE_EVENT_TYPE_1.TABLE_EVENT_TYPE.COPY_DATA, {
                    cellRange: table.stateManager.select.ranges,
                    copyData: data
                });
            }
        }
    })))), handler.on(table.getElement(), "paste", (e => __awaiter(this, void 0, void 0, (function*() {
        var _c, _d, _e, _f;
        if ((null === (_c = table.keyboardOptions) || void 0 === _c ? void 0 : _c.pasteValueToCell) && table.changeCellValues) {
            if (null === (_d = table.editorManager) || void 0 === _d ? void 0 : _d.editingEditor) return;
            if ((null === (_e = table.stateManager.select.ranges) || void 0 === _e ? void 0 : _e.length) > 0) if (null === (_f = navigator.clipboard) || void 0 === _f ? void 0 : _f.read) navigator.clipboard.read().then((clipboardItems => {
                for (const item of clipboardItems) item.types.includes("text/html") ? pasteHtmlToTable(item) : 1 === item.types.length && "text/plain" === item.types[0] && pasteTextToTable(item);
            })); else {
                const ranges = table.stateManager.select.ranges, col = Math.min(ranges[0].start.col, ranges[0].end.col), row = Math.min(ranges[0].start.row, ranges[0].end.row), rows = (e.clipboardData || window.Clipboard).getData("text").split("\n"), values = [];
                rows.forEach((function(rowCells, rowIndex) {
                    const cells = rowCells.split("\t"), rowValues = [];
                    values.push(rowValues), cells.forEach((function(cell, cellIndex) {
                        cellIndex === cells.length - 1 && (cell = cell.trim()), rowValues.push(cell);
                    }));
                }));
                const changedCellResults = yield table.changeCellValues(col, row, values);
                table.hasListeners(TABLE_EVENT_TYPE_1.TABLE_EVENT_TYPE.PASTED_DATA) && table.fireListeners(TABLE_EVENT_TYPE_1.TABLE_EVENT_TYPE.PASTED_DATA, {
                    col: col,
                    row: row,
                    pasteData: values,
                    changedCellResults: changedCellResults
                });
            }
        }
    })))), 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) && (null === (_a = table.editorManager) || void 0 === _a || _a.completeEdit()), 
        (0, vutils_1.isValid)(table.options.pixelRatio) || table.setPixelRatio((0, pixel_ratio_1.getPixelRatio)()), 
        e.windowSizeNotChange || table.resize());
    }));
    const regex = /<tr[^>]*>([\s\S]*?)<\/tr>/g, cellRegex = /<td[^>]*>([\s\S]*?)<\/td>/g;
    function pasteHtmlToTable(item) {
        const ranges = table.stateManager.select.ranges, selectRangeLength = ranges.length, col = Math.min(ranges[selectRangeLength - 1].start.col, ranges[selectRangeLength - 1].end.col), row = Math.min(ranges[selectRangeLength - 1].start.row, ranges[selectRangeLength - 1].end.row), maxCol = Math.max(ranges[selectRangeLength - 1].start.col, ranges[selectRangeLength - 1].end.col), maxRow = Math.max(ranges[selectRangeLength - 1].start.row, ranges[selectRangeLength - 1].end.row);
        let pasteValuesColCount = 0, pasteValuesRowCount = 0, values = [];
        item.getType("text/html").then((blob => {
            blob.text().then((pastedData => __awaiter(this, void 0, void 0, (function*() {
                var _a, _b;
                if (pastedData && /(<table)|(<TABLE)/g.test(pastedData)) {
                    const matches = Array.from(pastedData.matchAll(regex));
                    for (const match of matches) {
                        const rowContent = match[1], rowValues = Array.from(rowContent.matchAll(cellRegex)).map((cellMatch => cellMatch[1].replace(/(<(?!br)([^>]+)>)/gi, "").replace(/<br(\s*|\/)>[\r\n]?/gim, "\n").replace(/&amp;/g, "&").replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&#9;/gi, "\t").replace(/&nbsp;/g, " ")));
                        values.push(rowValues), pasteValuesColCount = Math.max(pasteValuesColCount, null !== (_a = null == rowValues ? void 0 : rowValues.length) && void 0 !== _a ? _a : 0);
                    }
                    pasteValuesRowCount = null !== (_b = values.length) && void 0 !== _b ? _b : 0, values = handlePasteValues(values, pasteValuesRowCount, pasteValuesColCount, maxRow - row + 1, maxCol - col + 1);
                    const changedCellResults = yield table.changeCellValues(col, row, values, !0);
                    table.hasListeners(TABLE_EVENT_TYPE_1.TABLE_EVENT_TYPE.PASTED_DATA) && table.fireListeners(TABLE_EVENT_TYPE_1.TABLE_EVENT_TYPE.PASTED_DATA, {
                        col: col,
                        row: row,
                        pasteData: values,
                        changedCellResults: changedCellResults
                    });
                } else navigator.clipboard.read().then((clipboardItems => {
                    for (const item of clipboardItems) item.types.includes("text/plain") && item.getType("text/plain").then((blob => {
                        blob.text().then(_pasteValue);
                    }));
                }));
            }))));
        }));
    }
    function _pasteValue(pastedData) {
        var _a;
        return __awaiter(this, void 0, void 0, (function*() {
            const ranges = table.stateManager.select.ranges, selectRangeLength = ranges.length, col = Math.min(ranges[selectRangeLength - 1].start.col, ranges[selectRangeLength - 1].end.col), row = Math.min(ranges[selectRangeLength - 1].start.row, ranges[selectRangeLength - 1].end.row), maxCol = Math.max(ranges[selectRangeLength - 1].start.col, ranges[selectRangeLength - 1].end.col), maxRow = Math.max(ranges[selectRangeLength - 1].start.row, ranges[selectRangeLength - 1].end.row);
            let pasteValuesColCount = 0, pasteValuesRowCount = 0, values = [];
            pastedData.split("\n").forEach((function(rowCells, rowIndex) {
                var _a;
                const cells = rowCells.split("\t"), rowValues = [];
                values.push(rowValues), cells.forEach((function(cell, cellIndex) {
                    cellIndex === cells.length - 1 && (cell = cell.trim()), rowValues.push(cell);
                })), pasteValuesColCount = Math.max(pasteValuesColCount, null !== (_a = null == rowValues ? void 0 : rowValues.length) && void 0 !== _a ? _a : 0);
            })), pasteValuesRowCount = null !== (_a = values.length) && void 0 !== _a ? _a : 0, 
            values = handlePasteValues(values, pasteValuesRowCount, pasteValuesColCount, maxRow - row + 1, maxCol - col + 1);
            const changedCellResults = yield table.changeCellValues(col, row, values, !0);
            table.hasListeners(TABLE_EVENT_TYPE_1.TABLE_EVENT_TYPE.PASTED_DATA) && table.fireListeners(TABLE_EVENT_TYPE_1.TABLE_EVENT_TYPE.PASTED_DATA, {
                col: col,
                row: row,
                pasteData: values,
                changedCellResults: changedCellResults
            });
        }));
    }
    function pasteTextToTable(item) {
        const ranges = table.stateManager.select.ranges, selectRangeLength = ranges.length, col = Math.min(ranges[selectRangeLength - 1].start.col, ranges[selectRangeLength - 1].end.col), row = Math.min(ranges[selectRangeLength - 1].start.row, ranges[selectRangeLength - 1].end.row), maxCol = Math.max(ranges[selectRangeLength - 1].start.col, ranges[selectRangeLength - 1].end.col), maxRow = Math.max(ranges[selectRangeLength - 1].start.row, ranges[selectRangeLength - 1].end.row);
        let pasteValuesColCount = 0, pasteValuesRowCount = 0;
        item.getType("text/plain").then((blob => {
            blob.text().then((pastedData => __awaiter(this, void 0, void 0, (function*() {
                var _a;
                const rows = pastedData.replace(/\r(?!\n)/g, "\r\n").split("\r\n");
                let values = [];
                rows.length > 1 && "" === rows[rows.length - 1] && rows.pop(), rows.forEach((function(rowCells, rowIndex) {
                    var _a;
                    const cells = rowCells.split("\t"), rowValues = [];
                    values.push(rowValues), cells.forEach((function(cell, cellIndex) {
                        cell.includes("\n") && (cell = cell.replace(/^"(.*)"$/, "$1").replace(/["]*/g, (match => new Array(Math.floor(match.length / 2)).fill('"').join("")))), 
                        rowValues.push(cell);
                    })), pasteValuesColCount = Math.max(pasteValuesColCount, null !== (_a = null == rowValues ? void 0 : rowValues.length) && void 0 !== _a ? _a : 0);
                })), pasteValuesRowCount = null !== (_a = values.length) && void 0 !== _a ? _a : 0, 
                values = handlePasteValues(values, pasteValuesRowCount, pasteValuesColCount, maxRow - row + 1, maxCol - col + 1);
                const changedCellResults = yield table.changeCellValues(col, row, values, !0);
                table.hasListeners(TABLE_EVENT_TYPE_1.TABLE_EVENT_TYPE.PASTED_DATA) && table.fireListeners(TABLE_EVENT_TYPE_1.TABLE_EVENT_TYPE.PASTED_DATA, {
                    col: col,
                    row: row,
                    pasteData: values,
                    changedCellResults: changedCellResults
                });
            }))));
        }));
    }
    function handlePasteValues(values, rowCount, colCount, selectedRowCount, selectedColCount) {
        if (selectedColCount > colCount || selectedRowCount > rowCount) {
            if (selectedColCount % colCount == 0 && selectedRowCount % rowCount == 0) {
                const toPasteValues = [];
                for (let i = 0; i < selectedRowCount; i++) {
                    const rowPasteValue = [];
                    toPasteValues.push(rowPasteValue);
                    for (let j = 0; j < selectedColCount; j++) {
                        const copiedRow = i % rowCount, copiedCol = j % colCount;
                        rowPasteValue.push(values[copiedRow][copiedCol]);
                    }
                }
                return toPasteValues;
            }
            return values;
        }
        return values;
    }
    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);
            (0, helper_1.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
    }), vrender_1.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()) (0, table_group_1.endResizeCol)(table); else if (stateManager.isResizeRow()) (0, 
            table_group_1.endResizeRow)(table); else if (stateManager.isMoveCol()) {
                const endMoveColSuccess = table.stateManager.endMoveCol();
                (0, helper_2.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_1.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_1.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()) (0, table_group_1.endResizeCol)(table); else if ("grabing" === stateManager.interactionState && stateManager.isResizeRow()) (0, 
        table_group_1.endResizeRow)(table); else if (stateManager.isMoveCol()) {
            const endMoveColSuccess = table.stateManager.endMoveCol();
            (0, helper_2.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);
            (0, helper_1.getPromiseValue)(isCompleteEdit, (isCompleteEdit => {
                !1 !== isCompleteEdit && (stateManager.updateInteractionState(ts_types_1.InteractionState.default), 
                eventManager.dealTableHover());
            }));
        }
        stateManager.updateInteractionState(ts_types_1.InteractionState.default);
    };
    eventManager.globalEventListeners.push({
        name: "pointerup",
        env: "vglobal",
        callback: globalPointerupCallback
    }), vrender_1.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 === ts_types_1.InteractionState.grabing && (stateManager.isResizeCol() ? (eventManager.dealColumnResize(x, y), 
        table.hasListeners(TABLE_EVENT_TYPE_1.TABLE_EVENT_TYPE.RESIZE_COLUMN) && table.fireListeners(TABLE_EVENT_TYPE_1.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_1.TABLE_EVENT_TYPE.RESIZE_ROW) && table.fireListeners(TABLE_EVENT_TYPE_1.TABLE_EVENT_TYPE.RESIZE_ROW, {
            row: table.stateManager.rowResize.row,
            rowHeight: table.getRowHeight(table.stateManager.rowResize.row)
        })));
        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;
                    (0, scroll_1.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(ts_types_1.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) && (0, 
                    vutils_1.isValid)(targetCol) && (0, vutils_1.isValid)(targetRow) && table.stateManager.updateSelectPos(targetCol.col, 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
    }), vrender_1.vglobal.addEventListener("pointermove", globalPointermoveCallback);
}

exports.bindContainerDomListener = bindContainerDomListener;
//# sourceMappingURL=container-dom.js.map
