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 { RichText, vglobal } from "./../vrender";

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

import { bindMediaClick } from "./media-click";

import { bindDrillEvent, checkHaveDrill } from "./drill";

import { bindSparklineHoverEvent } from "./sparkline-event";

import { checkHaveTextStick, handleTextStick } from "../scenegraph/stick-text";

import { bindGesture, bindTableGroupListener } from "./listener/table-group";

import { bindScrollBarListener } from "./listener/scroll-bar";

import { bindContainerDomListener } from "./listener/container-dom";

import { bindTouchListener } from "./listener/touch";

import { setDataToHTML } from "./util";

import { bindAxisClickEvent } from "./self-event-listener/pivot-chart/axis-click";

import { bindAxisHoverEvent } from "./self-event-listener/pivot-chart/axis-hover";

import { Env } from "../tools/env";

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

import { InertiaScroll } from "./scroll";

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

import { bindGroupCheckboxTreeChange, bindGroupTitleCheckboxChange, bindHeaderCheckboxChange } from "./self-event-listener/list-table/checkbox";

import { bindButtonClickEvent } from "./component/button";

import { bindIconClickEvent } from "./self-event-listener/base-table/icon";

import { bindDropdownMenuEvent } from "./self-event-listener/base-table/dropdown-menu";

import { bindDBClickAutoColumnWidthEvent } from "./self-event-listener/base-table/dbclick-auto-column-width";

import { clearActiveCellRangeState, setActiveCellRangeState } from "../tools/style";

export 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.copySourceRange = null, 
        this.table = table, this.handleTextStickBindId = [], this.inertiaScroll = new InertiaScroll(table.stateManager), 
        "node" === Env.mode || table.options.disableInteraction || (this.bindOuterEvent(), 
        setTimeout((() => {
            this.bindSelfEvent();
        }), 0));
    }
    bindOuterEvent() {
        bindTableGroupListener(this), bindContainerDomListener(this), bindScrollBarListener(this), 
        bindTouchListener(this), bindGesture(this);
    }
    updateEventBinder() {
        setTimeout((() => {
            var _a;
            this.table.isReleased || (checkHaveTextStick(this.table) && 0 === (null === (_a = this.handleTextStickBindId) || void 0 === _a ? void 0 : _a.length) ? (this.handleTextStickBindId.push(this.table.on(TABLE_EVENT_TYPE.SCROLL, (e => {
                handleTextStick(this.table);
            }))), this.handleTextStickBindId.push(this.table.on(TABLE_EVENT_TYPE.RESIZE_COLUMN_END, (e => {
                handleTextStick(this.table);
            }))), this.handleTextStickBindId.push(this.table.on(TABLE_EVENT_TYPE.RESIZE_ROW_END, (e => {
                handleTextStick(this.table);
            })))) : !checkHaveTextStick(this.table) && this.handleTextStickBindId && (this.handleTextStickBindId.forEach((id => {
                this.table.off(id);
            })), this.handleTextStickBindId = []), bindSparklineHoverEvent(this.table));
        }), 0);
    }
    bindSelfEvent() {
        this.table.isReleased || (bindIconClickEvent(this.table), bindDropdownMenuEvent(this.table), 
        this.updateEventBinder(), bindMediaClick(this.table), bindDBClickAutoColumnWidthEvent(this.table), 
        this.table.isPivotTable() && checkHaveDrill(this.table) && bindDrillEvent(this.table), 
        bindSparklineHoverEvent(this.table), bindAxisClickEvent(this.table), bindAxisHoverEvent(this.table), 
        bindGroupTitleCheckboxChange(this.table), bindGroupCheckboxTreeChange(this.table), 
        bindHeaderCheckboxChange(this.table), 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) && isCellDisableSelect(this.table, eventArgs.col, eventArgs.row)) return isSelectMoving || this.table.stateManager.updateSelectPos(-1, -1), 
            !1;
            if (!this.table.isHeader(eventArgs.col, eventArgs.row) && 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 && (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.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);
        let useerCustomCanResizeColumn = !0;
        return this.table.internalProps.canResizeColumn && !this.table.internalProps.canResizeColumn(resizeCol.col, resizeCol.row, this.table) && (useerCustomCanResizeColumn = !1), 
        useerCustomCanResizeColumn && 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(x, y, event) {
        let col = this.table.getColAtRelativePosition(x), row = this.table.getRowAtRelativePosition(y);
        -1 === col && "row" === this.table.stateManager.columnMove.movingColumnOrRow && (col = 0), 
        -1 === row && "column" === this.table.stateManager.columnMove.movingColumnOrRow && (row = 0), 
        isValid(col) && isValid(row) && this.table.stateManager.updateMoveCol(col, row, x, y, event);
    }
    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.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 RichText) {
            const icon = target.pickIcon(event.global);
            if (icon) return this.table.fireListeners(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 && vglobal.removeEventListener(item.name, item.callback);
        })), this.globalEventListeners = [];
    }
    enableScroll() {
        this._enableTableScroll = !0;
    }
    disableScroll() {
        this._enableTableScroll = !1;
    }
    handleCopy(e, isCut = !1) {
        var _a, _b, _c, _d, _e, _f;
        return __awaiter(this, void 0, void 0, (function*() {
            const table = this.table;
            !isCut && (this.cutWaitPaste = !1), this.copySourceRange = null;
            const sourceRanges = table.stateManager.select.ranges;
            if (sourceRanges && 1 === sourceRanges.length) {
                const sourceRange = sourceRanges[0];
                this.copySourceRange = {
                    startCol: Math.min(sourceRange.start.col, sourceRange.end.col),
                    startRow: Math.min(sourceRange.start.row, sourceRange.end.row)
                };
            } else if (!(null == sourceRanges ? void 0 : sourceRanges.length)) return void (this.copySourceRange = null);
            const data = this.table.getCopyValue(null === (_b = null === (_a = table.options.keyboardOptions) || void 0 === _a ? void 0 : _a.getCopyCellValue) || void 0 === _b ? void 0 : _b.value);
            if (isValid(data)) {
                e.preventDefault();
                const element = table.getElement();
                element && element !== document.activeElement && (element.focus(), yield new Promise((resolve => setTimeout(resolve, 10))));
                try {
                    if (navigator.clipboard && navigator.clipboard.writeText) {
                        let hasPermission = !0;
                        if (navigator.permissions && navigator.permissions.query) try {
                            hasPermission = "granted" === (yield navigator.permissions.query({
                                name: "clipboard-write"
                            })).state;
                        } catch (permissionError) {
                            hasPermission = !0;
                        }
                        if (hasPermission) try {
                            if (window.ClipboardItem) {
                                let htmlValues = data;
                                1 === table.stateManager.select.ranges.length && (null === (_d = null === (_c = table.options.keyboardOptions) || void 0 === _c ? void 0 : _c.getCopyCellValue) || void 0 === _d ? void 0 : _d.html) && (htmlValues = this.table.getCopyValue(null === (_e = table.options.keyboardOptions) || void 0 === _e ? void 0 : _e.getCopyCellValue.html));
                                const dataHTML = setDataToHTML(htmlValues);
                                yield navigator.clipboard.write([ new ClipboardItem({
                                    "text/html": new Blob([ dataHTML ], {
                                        type: "text/html"
                                    }),
                                    "text/plain": new Blob([ data ], {
                                        type: "text/plain"
                                    })
                                }) ]);
                            } else yield navigator.clipboard.writeText(data);
                        } catch (clipboardError) {
                            this.fallbackCopyToClipboard(data, e);
                        } else this.fallbackCopyToClipboard(data, e);
                    } else this.fallbackCopyToClipboard(data, e);
                    table.fireListeners(TABLE_EVENT_TYPE.COPY_DATA, {
                        cellRange: table.stateManager.select.ranges,
                        copyData: data,
                        isCut: isCut
                    });
                } catch (error) {
                    this.fallbackCopyToClipboard(data, e);
                }
            }
            (null === (_f = table.keyboardOptions) || void 0 === _f ? void 0 : _f.showCopyCellBorder) && (setActiveCellRangeState(table), 
            table.clearSelected());
        }));
    }
    fallbackCopyToClipboard(data, e) {
        try {
            if (e.clipboardData) return void e.clipboardData.setData("text/plain", data);
            document.activeElement && document.activeElement !== document.body && document.activeElement.blur();
            const textArea = document.createElement("textarea");
            textArea.value = data, textArea.style.position = "fixed", textArea.style.left = "-999999px", 
            textArea.style.top = "-999999px", textArea.style.opacity = "0", textArea.setAttribute("readonly", ""), 
            textArea.setAttribute("aria-hidden", "true"), document.body.appendChild(textArea), 
            textArea.focus(), textArea.select(), textArea.setSelectionRange(0, data.length);
            try {
                document.execCommand("copy");
            } catch (execError) {} finally {
                document.body.removeChild(textArea);
            }
        } catch (error) {}
    }
    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;
        return __awaiter(this, void 0, void 0, (function*() {
            const table = this.table;
            if (!(null === (_a = table.editorManager) || void 0 === _a ? void 0 : _a.editingEditor)) {
                if (table.changeCellValues && (null === (_b = table.stateManager.select.ranges) || void 0 === _b ? void 0 : _b.length) > 0) try {
                    if (navigator.clipboard && navigator.clipboard.read) try {
                        const clipboardItems = yield navigator.clipboard.read();
                        let handled = !1;
                        for (const item of clipboardItems) {
                            if (item.types.includes("text/html")) {
                                yield this.pasteHtmlToTable(item), handled = !0;
                                break;
                            }
                            if (item.types.includes("text/plain")) {
                                yield this.pasteTextToTable(item), handled = !0;
                                break;
                            }
                        }
                        handled || (yield this.fallbackPasteFromClipboard(e));
                    } catch (clipboardError) {
                        yield this.fallbackPasteFromClipboard(e);
                    } else yield this.fallbackPasteFromClipboard(e);
                } catch (error) {
                    yield this.fallbackPasteFromClipboard(e);
                }
                (null === (_c = table.keyboardOptions) || void 0 === _c ? void 0 : _c.showCopyCellBorder) && clearActiveCellRangeState(table);
            }
        }));
    }
    fallbackPasteFromClipboard(e) {
        return __awaiter(this, void 0, void 0, (function*() {
            const table = this.table, 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);
            try {
                const element = table.getElement();
                element && element !== document.activeElement && (element.focus(), yield new Promise((resolve => setTimeout(resolve, 10))));
                const clipboardData = e.clipboardData || window.clipboardData || window.Clipboard;
                if (clipboardData) {
                    const pastedData = clipboardData.getData("text") || clipboardData.getData("Text");
                    if (pastedData) return void (yield this.processPastedText(pastedData, col, row));
                }
            } catch (error) {}
        }));
    }
    processPastedText(pastedData, col, row) {
        var _a;
        return __awaiter(this, void 0, void 0, (function*() {
            const table = this.table, rows = pastedData.split("\n"), values = [];
            let processedValues;
            rows.forEach((function(rowCells) {
                const cells = rowCells.split("\t"), rowValues = [];
                values.push(rowValues), cells.forEach((function(cell, cellIndex) {
                    cellIndex === cells.length - 1 && (cell = cell.trim()), rowValues.push(cell);
                }));
            })), (null === (_a = table.options.keyboardOptions) || void 0 === _a ? void 0 : _a.processFormulaBeforePaste) && this.copySourceRange && (processedValues = table.options.keyboardOptions.processFormulaBeforePaste(values, this.copySourceRange.startCol, this.copySourceRange.startRow, col, row));
            const changedCellResults = yield table.changeCellValues(col, row, processedValues || values, !0);
            table.hasListeners(TABLE_EVENT_TYPE.PASTED_DATA) && table.fireListeners(TABLE_EVENT_TYPE.PASTED_DATA, {
                col: col,
                row: row,
                pasteData: processedValues || values,
                changedCellResults: changedCellResults
            });
        }));
    }
    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, _c;
                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);
                    }
                    let processedValues;
                    pasteValuesRowCount = null !== (_b = values.length) && void 0 !== _b ? _b : 0, values = this.handlePasteValues(values, pasteValuesRowCount, pasteValuesColCount, maxRow - row + 1, maxCol - col + 1), 
                    (null === (_c = table.options.keyboardOptions) || void 0 === _c ? void 0 : _c.processFormulaBeforePaste) && this.copySourceRange && (processedValues = table.options.keyboardOptions.processFormulaBeforePaste(values, this.copySourceRange.startCol, this.copySourceRange.startRow, col, row));
                    const changedCellResults = yield table.changeCellValues(col, row, processedValues || values, !0);
                    table.hasListeners(TABLE_EVENT_TYPE.PASTED_DATA) && table.fireListeners(TABLE_EVENT_TYPE.PASTED_DATA, {
                        col: col,
                        row: row,
                        pasteData: processedValues || 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, _b;
        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 = [];
            let processedValues;
            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), 
            (null === (_b = table.options.keyboardOptions) || void 0 === _b ? void 0 : _b.processFormulaBeforePaste) && this.copySourceRange && (processedValues = table.options.keyboardOptions.processFormulaBeforePaste(values, this.copySourceRange.startCol, this.copySourceRange.startRow, col, row));
            const changedCellResults = yield table.changeCellValues(col, row, processedValues || values, !0);
            table.hasListeners(TABLE_EVENT_TYPE.PASTED_DATA) && table.fireListeners(TABLE_EVENT_TYPE.PASTED_DATA, {
                col: col,
                row: row,
                pasteData: processedValues || values,
                changedCellResults: changedCellResults
            });
        }));
    }
    pasteTextToTable(item) {
        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);
            try {
                const blob = yield item.getType("text/plain"), pastedData = yield blob.text(), values = this.parsePastedData(pastedData), pasteValuesRowCount = values.length, pasteValuesColCount = Math.max(...values.map((row => row.length)), 0), processedValues = this.handlePasteValues(values, pasteValuesRowCount, pasteValuesColCount, maxRow - row + 1, maxCol - col + 1), changedCellResults = yield table.changeCellValues(col, row, processedValues, !0);
                table.hasListeners(TABLE_EVENT_TYPE.PASTED_DATA) && table.fireListeners(TABLE_EVENT_TYPE.PASTED_DATA, {
                    col: col,
                    row: row,
                    pasteData: processedValues,
                    changedCellResults: changedCellResults
                });
            } catch (error) {}
        }));
    }
    parsePastedData(pastedData) {
        const rows = pastedData.replace(/\r(?!\n)/g, "\r\n").split("\r\n"), values = [];
        return rows.length > 1 && "" === rows[rows.length - 1] && rows.pop(), rows.forEach((rowCells => {
            const rowValues = rowCells.split("\t").map((cell => this.processCellValue(cell)));
            values.push(rowValues);
        })), values;
    }
    processCellValue(cell) {
        cell.includes("\n") && (cell = cell.replace(/^"(.*)"$/, "$1").replace(/["]*/g, (match => new Array(Math.floor(match.length / 2)).fill('"').join(""))));
        const numValue = Number(cell);
        return isNaN(numValue) ? cell : numValue;
    }
    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;
    }
}
//# sourceMappingURL=event.js.map