"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.EventManager = void 0;

const vrender_1 = require("./../vrender"), TABLE_EVENT_TYPE_1 = require("../core/TABLE_EVENT_TYPE"), media_click_1 = require("./media-click"), drill_1 = require("./drill"), sparkline_event_1 = require("./sparkline-event"), stick_text_1 = require("../scenegraph/stick-text"), table_group_1 = require("./listener/table-group"), scroll_bar_1 = require("./listener/scroll-bar"), container_dom_1 = require("./listener/container-dom"), touch_1 = require("./listener/touch"), axis_click_1 = require("./self-event-listener/pivot-chart/axis-click"), axis_hover_1 = require("./self-event-listener/pivot-chart/axis-hover"), env_1 = require("../tools/env"), vutils_1 = require("@visactor/vutils"), scroll_1 = require("./scroll"), is_cell_select_highlight_1 = require("../state/select/is-cell-select-highlight"), checkbox_1 = require("./self-event-listener/list-table/checkbox"), button_1 = require("./component/button"), icon_1 = require("./self-event-listener/base-table/icon"), dropdown_menu_1 = require("./self-event-listener/base-table/dropdown-menu"), dbclick_auto_column_width_1 = require("./self-event-listener/base-table/dbclick-auto-column-width"), helper_1 = require("../tools/helper"), style_1 = require("../tools/style");

class EventManager {
    constructor(table) {
        this.isDown = !1, this.isDraging = !1, this.globalEventListeners = [], this._enableTableScroll = !0, 
        this.cutWaitPaste = !1, this.clipboardCheckTimer = null, this.cutOperationTime = 0, 
        this.lastClipboardContent = "", this.cutCellRange = null, this.table = table, this.handleTextStickBindId = [], 
        this.inertiaScroll = new scroll_1.InertiaScroll(table.stateManager), "node" === env_1.Env.mode || table.options.disableInteraction || (this.bindOuterEvent(), 
        setTimeout((() => {
            this.bindSelfEvent();
        }), 0));
    }
    bindOuterEvent() {
        (0, table_group_1.bindTableGroupListener)(this), (0, container_dom_1.bindContainerDomListener)(this), 
        (0, scroll_bar_1.bindScrollBarListener)(this), (0, touch_1.bindTouchListener)(this), 
        (0, table_group_1.bindGesture)(this);
    }
    updateEventBinder() {
        setTimeout((() => {
            var _a;
            this.table.isReleased || ((0, stick_text_1.checkHaveTextStick)(this.table) && 0 === (null === (_a = this.handleTextStickBindId) || void 0 === _a ? void 0 : _a.length) ? (this.handleTextStickBindId.push(this.table.on(TABLE_EVENT_TYPE_1.TABLE_EVENT_TYPE.SCROLL, (e => {
                (0, stick_text_1.handleTextStick)(this.table);
            }))), this.handleTextStickBindId.push(this.table.on(TABLE_EVENT_TYPE_1.TABLE_EVENT_TYPE.RESIZE_COLUMN_END, (e => {
                (0, stick_text_1.handleTextStick)(this.table);
            }))), this.handleTextStickBindId.push(this.table.on(TABLE_EVENT_TYPE_1.TABLE_EVENT_TYPE.RESIZE_ROW_END, (e => {
                (0, stick_text_1.handleTextStick)(this.table);
            })))) : !(0, stick_text_1.checkHaveTextStick)(this.table) && this.handleTextStickBindId && (this.handleTextStickBindId.forEach((id => {
                this.table.off(id);
            })), this.handleTextStickBindId = []), (0, sparkline_event_1.bindSparklineHoverEvent)(this.table));
        }), 0);
    }
    bindSelfEvent() {
        this.table.isReleased || ((0, icon_1.bindIconClickEvent)(this.table), (0, dropdown_menu_1.bindDropdownMenuEvent)(this.table), 
        this.updateEventBinder(), (0, media_click_1.bindMediaClick)(this.table), (0, dbclick_auto_column_width_1.bindDBClickAutoColumnWidthEvent)(this.table), 
        this.table.isPivotTable() && (0, drill_1.checkHaveDrill)(this.table) && (0, drill_1.bindDrillEvent)(this.table), 
        (0, sparkline_event_1.bindSparklineHoverEvent)(this.table), (0, axis_click_1.bindAxisClickEvent)(this.table), 
        (0, axis_hover_1.bindAxisHoverEvent)(this.table), (0, checkbox_1.bindGroupTitleCheckboxChange)(this.table), 
        (0, checkbox_1.bindGroupCheckboxTreeChange)(this.table), (0, checkbox_1.bindHeaderCheckboxChange)(this.table), 
        (0, button_1.bindButtonClickEvent)(this.table));
    }
    dealTableHover(eventArgsSet) {
        if (!eventArgsSet) return void this.table.stateManager.updateHoverPos(-1, -1);
        const {eventArgs: eventArgs} = eventArgsSet;
        eventArgs ? this.table.stateManager.updateHoverPos(eventArgs.col, eventArgs.row) : this.table.stateManager.updateHoverPos(-1, -1);
    }
    dealIconHover(eventArgsSet) {
        const {eventArgs: eventArgs} = eventArgsSet;
        eventArgs ? this.table.stateManager.updateHoverIcon(eventArgs.col, eventArgs.row, eventArgs.target, eventArgs.targetCell) : this.table.stateManager.updateHoverIcon(-1, -1, void 0, void 0);
    }
    dealMenuHover(eventArgsSet) {}
    dealTableSelect(eventArgsSet, isSelectMoving) {
        var _a, _b, _c, _d, _e, _f, _g, _h, _j;
        if (!eventArgsSet) return this.table.stateManager.updateSelectPos(-1, -1), !1;
        const {eventArgs: eventArgs} = eventArgsSet;
        if (eventArgs) {
            if ("checkbox" === eventArgs.target.name || "radio" === eventArgs.target.name || "switch" === eventArgs.target.name || "button" === eventArgs.target.name) return !1;
            if (this.table.isHeader(eventArgs.col, eventArgs.row) && (0, is_cell_select_highlight_1.isCellDisableSelect)(this.table, eventArgs.col, eventArgs.row)) return isSelectMoving || this.table.stateManager.updateSelectPos(-1, -1), 
            !1;
            if (!this.table.isHeader(eventArgs.col, eventArgs.row) && (0, is_cell_select_highlight_1.isCellDisableSelect)(this.table, eventArgs.col, eventArgs.row)) {
                if (!isSelectMoving) {
                    const isHasSelected = !!(null === (_a = this.table.stateManager.select.ranges) || void 0 === _a ? void 0 : _a.length);
                    this.table.stateManager.updateSelectPos(-1, -1), isHasSelected && this.table.stateManager.endSelectCells(!0, isHasSelected);
                }
                return !1;
            }
            if (this.table.isPivotChart() && ("axis-label" === (null === (_b = null == eventArgsSet ? void 0 : eventArgsSet.eventArgs) || void 0 === _b ? void 0 : _b.target.name) || "chart" === (null === (_c = null == eventArgsSet ? void 0 : eventArgsSet.eventArgs) || void 0 === _c ? void 0 : _c.target.type))) return this.table.stateManager.updateSelectPos(-1, -1), 
            !1;
            const shiftMultiSelect = null === (_e = null === (_d = this.table.keyboardOptions) || void 0 === _d ? void 0 : _d.shiftMultiSelect) || void 0 === _e || _e, ctrlMultiSelect = null === (_g = null === (_f = this.table.keyboardOptions) || void 0 === _f ? void 0 : _f.ctrlMultiSelect) || void 0 === _g || _g;
            return this.table.stateManager.updateSelectPos("row" === this.table.stateManager.select.selectInline ? this.table.colCount - 1 : eventArgs.col, "col" === this.table.stateManager.select.selectInline ? this.table.rowCount - 1 : eventArgs.row, eventArgs.event.shiftKey && shiftMultiSelect, (eventArgs.event.ctrlKey || eventArgs.event.metaKey) && ctrlMultiSelect, !1, !isSelectMoving && (null === (_j = null === (_h = this.table.options.select) || void 0 === _h ? void 0 : _h.makeSelectCellVisible) || void 0 === _j || _j)), 
            !0;
        }
        return !1;
    }
    dealFillSelect(eventArgsSet, isSelectMoving) {
        var _a, _b, _c, _d, _e, _f, _g, _h;
        const {eventArgs: eventArgs} = eventArgsSet;
        if (eventArgs) {
            if ((null === (_b = null === (_a = this.table.stateManager.select) || void 0 === _a ? void 0 : _a.ranges) || void 0 === _b ? void 0 : _b.length) && this.table.stateManager.isFillHandle()) {
                let updateRow, updateCol;
                const currentRange = this.table.stateManager.select.ranges[this.table.stateManager.select.ranges.length - 1];
                isSelectMoving && ((0, vutils_1.isValid)(this.table.stateManager.fillHandle.directionRow) || (Math.abs(this.table.stateManager.fillHandle.startY - eventArgsSet.abstractPos.y) >= Math.abs(this.table.stateManager.fillHandle.startX - eventArgsSet.abstractPos.x) ? this.table.stateManager.fillHandle.directionRow = !0 : this.table.stateManager.fillHandle.directionRow = !1), 
                Math.abs(this.table.stateManager.fillHandle.startY - eventArgsSet.abstractPos.y) >= Math.abs(this.table.stateManager.fillHandle.startX - eventArgsSet.abstractPos.x) ? this.table.stateManager.fillHandle.startY - eventArgsSet.abstractPos.y > 0 ? this.table.stateManager.fillHandle.direction = "top" : this.table.stateManager.fillHandle.direction = "bottom" : this.table.stateManager.fillHandle.startX - eventArgsSet.abstractPos.x > 0 ? this.table.stateManager.fillHandle.direction = "left" : this.table.stateManager.fillHandle.direction = "right", 
                this.table.stateManager.fillHandle.directionRow ? (updateRow = eventArgs.row, updateCol = currentRange.end.col) : (updateRow = currentRange.end.row, 
                updateCol = eventArgs.col));
                const ctrlMultiSelect = null === (_d = null === (_c = this.table.keyboardOptions) || void 0 === _c ? void 0 : _c.ctrlMultiSelect) || void 0 === _d || _d;
                this.table.stateManager.updateSelectPos(isSelectMoving ? updateCol : currentRange.end.col, isSelectMoving ? updateRow : currentRange.end.row, !0, (eventArgs.event.ctrlKey || eventArgs.event.metaKey) && ctrlMultiSelect, !1, !isSelectMoving);
            } else {
                const shiftMultiSelect = null === (_f = null === (_e = this.table.keyboardOptions) || void 0 === _e ? void 0 : _e.shiftMultiSelect) || void 0 === _f || _f, ctrlMultiSelect = null === (_h = null === (_g = this.table.keyboardOptions) || void 0 === _g ? void 0 : _g.ctrlMultiSelect) || void 0 === _h || _h;
                this.table.stateManager.updateSelectPos(eventArgs.col, eventArgs.row, eventArgs.event.shiftKey && shiftMultiSelect, (eventArgs.event.ctrlKey || eventArgs.event.metaKey) && ctrlMultiSelect, !1, !isSelectMoving);
            }
            return !0;
        }
        return !1;
    }
    deelTableSelectAll() {
        this.table.stateManager.updateSelectPos(-1, -1, !1, !1, !0), this.table.fireListeners(TABLE_EVENT_TYPE_1.TABLE_EVENT_TYPE.SELECTED_CELL, {
            ranges: this.table.stateManager.select.ranges,
            col: 0,
            row: 0
        });
    }
    dealMenuSelect(eventArgsSet) {}
    checkColumnResize(eventArgsSet, update) {
        const {eventArgs: eventArgs} = eventArgsSet;
        if (this.table.internalProps.enableTreeStickCell && !eventArgs) return !1;
        const resizeCol = this.table.scenegraph.getResizeColAt(eventArgsSet.abstractPos.x, eventArgsSet.abstractPos.y, null == eventArgs ? void 0 : eventArgs.targetCell);
        return this.table._canResizeColumn(resizeCol.col, resizeCol.row) && resizeCol.col >= 0 ? (update && this.table.stateManager.startResizeCol(resizeCol.col, eventArgsSet.abstractPos.x, eventArgsSet.abstractPos.y, resizeCol.rightFrozen), 
        !0) : (this.table.stateManager.isResizeCol() && this.table.stateManager.endResizeCol(), 
        !1);
    }
    checkRowResize(eventArgsSet, update) {
        const {eventArgs: eventArgs} = eventArgsSet;
        if (eventArgs) {
            const resizeRow = this.table.scenegraph.getResizeRowAt(eventArgsSet.abstractPos.x, eventArgsSet.abstractPos.y, eventArgs.targetCell);
            if (this.table._canResizeRow(resizeRow.col, resizeRow.row) && resizeRow.row >= 0) return update && this.table.stateManager.startResizeRow(resizeRow.row, eventArgsSet.abstractPos.x, eventArgsSet.abstractPos.y, resizeRow.bottomFrozen), 
            !0;
        }
        return !1;
    }
    cellIsHeaderCheck(eventArgsSet, update) {
        const {eventArgs: eventArgs} = eventArgsSet, {col: col, row: row, target: target} = eventArgs;
        if (!this.table.isHeader(col, row)) return !1;
        return "checkbox" === this.table.getCellType(eventArgs.col, eventArgs.row) && "checkbox" === target.name;
    }
    checkCellFillhandle(eventArgsSet, update) {
        var _a, _b, _c, _d, _e;
        let isFillHandle = !1;
        if (isFillHandle = "function" == typeof (null === (_a = this.table.options.excelOptions) || void 0 === _a ? void 0 : _a.fillHandle) ? this.table.options.excelOptions.fillHandle({
            selectRanges: this.table.stateManager.select.ranges,
            table: this.table
        }) : null === (_b = this.table.options.excelOptions) || void 0 === _b ? void 0 : _b.fillHandle, 
        isFillHandle) {
            const {eventArgs: eventArgs} = eventArgsSet;
            if (eventArgs && (null === (_d = null === (_c = this.table.stateManager.select) || void 0 === _c ? void 0 : _c.ranges) || void 0 === _d ? void 0 : _d.length)) {
                const lastCol = Math.max(this.table.stateManager.select.ranges[this.table.stateManager.select.ranges.length - 1].start.col, this.table.stateManager.select.ranges[this.table.stateManager.select.ranges.length - 1].end.col), lastRow = Math.max(this.table.stateManager.select.ranges[this.table.stateManager.select.ranges.length - 1].start.row, this.table.stateManager.select.ranges[this.table.stateManager.select.ranges.length - 1].end.row), startCol = Math.min(this.table.stateManager.select.ranges[this.table.stateManager.select.ranges.length - 1].start.col, this.table.stateManager.select.ranges[this.table.stateManager.select.ranges.length - 1].end.col), startRow = Math.min(this.table.stateManager.select.ranges[this.table.stateManager.select.ranges.length - 1].start.row, this.table.stateManager.select.ranges[this.table.stateManager.select.ranges.length - 1].end.row);
                let lastCellBoundTargetX;
                if (lastCol < this.table.colCount - 1) {
                    lastCellBoundTargetX = this.table.scenegraph.highPerformanceGetCell(lastCol, lastRow).globalAABBBounds.x2;
                } else if (0 === startCol) {
                    lastCellBoundTargetX = this.table.scenegraph.highPerformanceGetCell(0, lastRow).globalAABBBounds.x1;
                } else {
                    lastCellBoundTargetX = this.table.scenegraph.highPerformanceGetCell(startCol - 1, lastRow).globalAABBBounds.x2;
                }
                const distanceX = Math.abs(eventArgsSet.abstractPos.x - lastCellBoundTargetX);
                let lastCellBoundTargetY;
                if (lastRow < this.table.rowCount - 1) {
                    lastCellBoundTargetY = this.table.scenegraph.highPerformanceGetCell(lastCol, lastRow).globalAABBBounds.y2;
                } else {
                    lastCellBoundTargetY = this.table.scenegraph.highPerformanceGetCell(lastCol, startRow - 1).globalAABBBounds.y2;
                }
                const distanceY = Math.abs(eventArgsSet.abstractPos.y - lastCellBoundTargetY), squareSize = 18;
                if ((null === (_e = this.table.stateManager.fillHandle) || void 0 === _e ? void 0 : _e.isFilling) || distanceX <= squareSize / 2 && distanceY <= squareSize / 2) return update && this.table.stateManager.startFillSelect(eventArgsSet.abstractPos.x, eventArgsSet.abstractPos.y), 
                !0;
            }
        }
        return !1;
    }
    dealColumnResize(xInTable, yInTable) {
        this.table.stateManager.updateResizeCol(xInTable, yInTable);
    }
    dealRowResize(xInTable, yInTable) {
        this.table.stateManager.updateResizeRow(xInTable, yInTable);
    }
    checkColumnMover(eventArgsSet) {
        var _a;
        const {eventArgs: eventArgs} = eventArgsSet;
        return !(!eventArgs || !this.table._canDragHeaderPosition(eventArgs.col, eventArgs.row)) && (this.table.stateManager.startMoveCol(eventArgs.col, eventArgs.row, eventArgsSet.abstractPos.x, eventArgsSet.abstractPos.y, null === (_a = null == eventArgs ? void 0 : eventArgs.event) || void 0 === _a ? void 0 : _a.nativeEvent), 
        !0);
    }
    dealColumnMover(eventArgsSet) {
        var _a;
        const {eventArgs: eventArgs} = eventArgsSet;
        (0, vutils_1.isValid)(eventArgs.col) && (0, vutils_1.isValid)(eventArgs.row) && this.table.stateManager.updateMoveCol(eventArgs.col, eventArgs.row, eventArgsSet.abstractPos.x, eventArgsSet.abstractPos.y, null === (_a = null == eventArgs ? void 0 : eventArgs.event) || void 0 === _a ? void 0 : _a.nativeEvent);
    }
    startColumnResize(eventArgsSet) {}
    dealIconClick(e, eventArgsSet) {
        const {eventArgs: eventArgs} = eventArgsSet, {target: target, event: event, col: col, row: row} = eventArgs || {
            target: e.target,
            event: e,
            col: -1,
            row: -1
        }, icon = target;
        if (icon.role && icon.role.startsWith("icon-")) return this.table.fireListeners(TABLE_EVENT_TYPE_1.TABLE_EVENT_TYPE.ICON_CLICK, {
            name: icon.name,
            x: (icon.globalAABBBounds.x1 + icon.globalAABBBounds.x2) / 2,
            y: icon.globalAABBBounds.y2,
            col: col,
            row: row,
            funcType: icon.attribute.funcType,
            icon: icon,
            event: event
        }), !0;
        if (target instanceof vrender_1.RichText) {
            const icon = target.pickIcon(event.global);
            if (icon) return this.table.fireListeners(TABLE_EVENT_TYPE_1.TABLE_EVENT_TYPE.ICON_CLICK, {
                name: icon.attribute.id,
                x: icon.globalX + icon.globalAABBBounds.width() / 2,
                y: icon.globalY + icon.AABBBounds.height(),
                col: col,
                row: row,
                funcType: icon.attribute.funcType,
                icon: icon,
                event: event
            }), !0;
        }
        return !1;
    }
    release() {
        var _a;
        null === (_a = this.gesture) || void 0 === _a || _a.release(), this.globalEventListeners.forEach((item => {
            "document" === item.env ? document.removeEventListener(item.name, item.callback) : "body" === item.env ? document.body.removeEventListener(item.name, item.callback) : "window" === item.env ? window.removeEventListener(item.name, item.callback) : "vglobal" === item.env && vrender_1.vglobal.removeEventListener(item.name, item.callback);
        })), this.globalEventListeners = [];
    }
    enableScroll() {
        this._enableTableScroll = !0;
    }
    disableScroll() {
        this._enableTableScroll = !1;
    }
    handleCopy(e, isCut = !1) {
        var _a, _b;
        return __awaiter(this, void 0, void 0, (function*() {
            const table = this.table;
            !isCut && (this.cutWaitPaste = !1);
            const data = this.table.getCopyValue();
            if ((0, vutils_1.isValid)(data)) {
                e.preventDefault();
                const permissionState = yield navigator.permissions.query({
                    name: "clipboard-write"
                });
                if ((null === (_a = navigator.clipboard) || void 0 === _a ? void 0 : _a.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,
                    isCut: isCut
                });
            }
            (null === (_b = table.keyboardOptions) || void 0 === _b ? void 0 : _b.showCopyCellBorder) && ((0, 
            style_1.setActiveCellRangeState)(table), table.clearSelected());
        }));
    }
    handleCut(e) {
        return __awaiter(this, void 0, void 0, (function*() {
            this.handleCopy(e, !0), this.cutWaitPaste = !0, this.cutCellRange = this.table.getSelectedCellInfos(), 
            this.clipboardCheckTimer && clearTimeout(this.clipboardCheckTimer), this.clipboardCheckTimer = window.setTimeout((() => {
                this.cutWaitPaste && (this.cutWaitPaste = !1, this.cutCellRange = null, this.clipboardCheckTimer = null);
            }), 3e4), this.saveClipboardContent();
        }));
    }
    handlePaste(e) {
        this.cutWaitPaste ? this.checkClipboardChanged().then((changed => {
            this.executePaste(e), changed || this.clearCutArea(this.table), this.cutWaitPaste && (this.cutWaitPaste = !1, 
            this.cutCellRange = null, this.clipboardCheckTimer && (clearTimeout(this.clipboardCheckTimer), 
            this.clipboardCheckTimer = null));
        })).catch((() => {
            this.executePaste(e), this.cutWaitPaste && (this.cutWaitPaste = !1, this.cutCellRange = null, 
            this.clipboardCheckTimer && (clearTimeout(this.clipboardCheckTimer), this.clipboardCheckTimer = null));
        })) : this.executePaste(e);
    }
    executePaste(e) {
        var _a, _b, _c, _d;
        return __awaiter(this, void 0, void 0, (function*() {
            const table = this.table;
            if (table.changeCellValues) {
                if (null === (_a = table.editorManager) || void 0 === _a ? void 0 : _a.editingEditor) return;
                if ((null === (_b = table.stateManager.select.ranges) || void 0 === _b ? void 0 : _b.length) > 0) if (null === (_c = navigator.clipboard) || void 0 === _c ? void 0 : _c.read) navigator.clipboard.read().then((clipboardItems => {
                    for (const item of clipboardItems) item.types.includes("text/html") ? this.pasteHtmlToTable(item) : 1 === item.types.length && "text/plain" === item.types[0] && this.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, !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
                    });
                }
            }
            (null === (_d = table.keyboardOptions) || void 0 === _d ? void 0 : _d.showCopyCellBorder) && (0, 
            style_1.clearActiveCellRangeState)(table);
        }));
    }
    clearCutArea(table) {
        try {
            const selectCells = this.cutCellRange;
            if (!selectCells || 0 === selectCells.length) return;
            for (let i = 0; i < selectCells.length; i++) for (let j = 0; j < selectCells[i].length; j++) selectCells[i][j] && table.changeCellValue(selectCells[i][j].col, selectCells[i][j].row, void 0);
        } catch (error) {}
    }
    checkClipboardChanged() {
        return __awaiter(this, void 0, void 0, (function*() {
            if (!navigator.clipboard || !navigator.clipboard.readText) return !1;
            try {
                return (yield navigator.clipboard.readText()) !== this.lastClipboardContent;
            } catch (err) {
                return !1;
            }
        }));
    }
    saveClipboardContent() {
        navigator.clipboard && navigator.clipboard.readText && setTimeout((() => {
            navigator.clipboard.readText().then((text => {
                this.lastClipboardContent = text;
            })).catch((err => {}));
        }), 50);
    }
    pasteHtmlToTable(item) {
        const regex = /<tr[^>]*>([\s\S]*?)<\/tr>/g, cellRegex = /<td[^>]*>([\s\S]*?)<\/td>/g, table = this.table, 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 = this.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((data => this._pasteValue(data)));
                    }));
                }));
            }))));
        }));
    }
    _pasteValue(pastedData) {
        var _a;
        return __awaiter(this, void 0, void 0, (function*() {
            const table = this.table, 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 = this.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
            });
        }));
    }
    pasteTextToTable(item) {
        const table = this.table, 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 = this.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
                });
            }))));
        }));
    }
    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;
    }
}

exports.EventManager = EventManager;
//# sourceMappingURL=event.js.map