/**
 * DevExtreme (esm/__internal/grids/grid_core/columns_resizing_reordering/m_columns_resizing_reordering.js)
 * Version: 23.2.6 (build 24140-0112)
 * Build date: Sun May 19 2024
 *
 * Copyright (c) 2012 - 2024 Developer Express Inc. ALL RIGHTS RESERVED
 * Read about DevExtreme licensing here: https://js.devexpress.com/Licensing/
 */
import fx from "../../../../animation/fx";
import domAdapter from "../../../../core/dom_adapter";
import $ from "../../../../core/renderer";
import Callbacks from "../../../../core/utils/callbacks";
import {
    extend
} from "../../../../core/utils/extend";
import {
    each
} from "../../../../core/utils/iterator";
import {
    getBoundingRect
} from "../../../../core/utils/position";
import {
    getHeight,
    getWidth,
    setHeight,
    setWidth
} from "../../../../core/utils/size";
import {
    isDefined,
    isObject,
    isString
} from "../../../../core/utils/type";
import eventsEngine from "../../../../events/core/events_engine";
import {
    end as dragEventEnd,
    move as dragEventMove,
    start as dragEventStart
} from "../../../../events/drag";
import pointerEvents from "../../../../events/pointer";
import {
    addNamespace,
    eventData as getEventData,
    isTouchEvent
} from "../../../../events/utils/index";
import swatchContainer from "../../../../ui/widget/swatch_container";
import modules from "../m_modules";
import gridCoreUtils from "../m_utils";
var COLUMNS_SEPARATOR_CLASS = "columns-separator";
var COLUMNS_SEPARATOR_TRANSPARENT = "columns-separator-transparent";
var DRAGGING_HEADER_CLASS = "drag-header";
var CELL_CONTENT_CLASS = "text-content";
var HEADERS_DRAG_ACTION_CLASS = "drag-action";
var TRACKER_CLASS = "tracker";
var HEADERS_DROP_HIGHLIGHT_CLASS = "drop-highlight";
var BLOCK_SEPARATOR_CLASS = "dx-block-separator";
var HEADER_ROW_CLASS = "dx-header-row";
var WIDGET_CLASS = "dx-widget";
var DRAGGING_COMMAND_CELL_CLASS = "dx-drag-command-cell";
var MODULE_NAMESPACE = "dxDataGridResizingReordering";
var COLUMNS_SEPARATOR_TOUCH_TRACKER_WIDTH = 10;
var DRAGGING_DELTA = 5;
var COLUMN_OPACITY = .5;
var allowResizing = function(that) {
    return that.option("allowColumnResizing") || that.getController("columns").isColumnOptionUsed("allowResizing")
};
var allowReordering = function(that) {
    return that.option("allowColumnReordering") || that.getController("columns").isColumnOptionUsed("allowReordering")
};
export class TrackerView extends modules.View {
    init() {
        super.init();
        this._tablePositionController = this.getController("tablePosition");
        this._subscribeToCallback()
    }
    dispose() {
        this._unsubscribeFromCallback();
        super.dispose()
    }
    optionChanged(args) {
        if ("allowColumnResizing" === args.name) {
            this._unsubscribeFromCallback();
            if (args.value) {
                this._subscribeToCallback();
                this._invalidate()
            }
        }
        super.optionChanged(args)
    }
    _renderCore() {
        var deferred = super._renderCore();
        this.element().addClass(this.addWidgetPrefix(TRACKER_CLASS));
        this.hide();
        return deferred
    }
    _unsubscribeFromCallback() {
        if (this._positionChanged) {
            this._tablePositionController.positionChanged.remove(this._positionChanged)
        }
    }
    _subscribeToCallback() {
        var that = this;
        that._positionChanged = function(position) {
            var $element = that.element();
            if ($element && $element.hasClass(that.addWidgetPrefix(TRACKER_CLASS))) {
                $element.css({
                    top: position.top
                });
                setHeight($element, position.height)
            }
        };
        this._tablePositionController.positionChanged.add(that._positionChanged)
    }
    isVisible() {
        return allowResizing(this)
    }
    show() {
        this.element().show()
    }
    hide() {
        this.element() && this.element().hide()
    }
    setHeight(value) {
        setHeight(this.element(), value)
    }
}
export class SeparatorView extends modules.View {
    _renderSeparator() {}
    _renderCore(options) {
        var deferred = super._renderCore(options);
        this._isShown = true;
        this._renderSeparator();
        this.hide();
        return deferred
    }
    show() {
        this._isShown = true
    }
    hide() {
        this._isShown = false
    }
    height(value) {
        var $element = this.element();
        if ($element) {
            if (isDefined(value)) {
                setHeight($element, value)
            } else {
                return getHeight($element)
            }
        }
    }
    width(value) {
        var $element = this.element();
        if ($element) {
            if (isDefined(value)) {
                setWidth($element, value)
            } else {
                return getWidth($element)
            }
        }
    }
}
export class ColumnsSeparatorView extends SeparatorView {
    init() {
        super.init();
        this._tablePositionController = this.getController("tablePosition");
        this._init()
    }
    dispose() {
        this._unsubscribeFromCallback();
        super.dispose()
    }
    optionChanged(args) {
        if ("allowColumnResizing" === args.name) {
            if (args.value) {
                this._init();
                this._invalidate();
                this.hide(true)
            } else {
                this._unsubscribeFromCallback();
                this._isTransparent = allowResizing(this);
                this.hide(true)
            }
        }
        super.optionChanged(args)
    }
    _renderSeparator() {
        super._renderSeparator();
        var $element = this.element();
        $element.addClass(this.addWidgetPrefix(COLUMNS_SEPARATOR_CLASS))
    }
    _subscribeToCallback() {
        var that = this;
        var $element;
        that._positionChanged = function(position) {
            $element = that.element();
            if ($element) {
                $element.css({
                    top: position.top
                });
                setHeight($element, position.height)
            }
        };
        that._tablePositionController.positionChanged.add(that._positionChanged)
    }
    _unsubscribeFromCallback() {
        this._positionChanged && this._tablePositionController.positionChanged.remove(this._positionChanged)
    }
    _init() {
        this._isTransparent = allowResizing(this);
        if (this.isVisible()) {
            this._subscribeToCallback()
        }
    }
    isVisible() {
        return this.option("showColumnHeaders") && (allowReordering(this) || allowResizing(this))
    }
    show() {
        var $element = this.element();
        if ($element && !this._isShown) {
            if (this._isTransparent) {
                $element.removeClass(this.addWidgetPrefix(COLUMNS_SEPARATOR_TRANSPARENT))
            } else {
                $element.show()
            }
        }
        super.show()
    }
    hide(force) {
        var $element = this.element();
        var columnsSeparatorTransparent = this.addWidgetPrefix(COLUMNS_SEPARATOR_TRANSPARENT);
        if ($element && (this._isShown || force)) {
            if (this._isTransparent) {
                $element.addClass(columnsSeparatorTransparent);
                $element.css("left", "");
                $element.show()
            } else {
                if ($element.hasClass(columnsSeparatorTransparent)) {
                    $element.removeClass(columnsSeparatorTransparent)
                }
                $element.hide()
            }
        }
        super.hide()
    }
    moveByX(outerX) {
        var $element = this.element();
        if ($element) {
            $element.css("left", null === outerX ? 0 : outerX - this._parentElement().offset().left)
        }
    }
    changeCursor(cursorName) {
        cursorName = isDefined(cursorName) ? cursorName : "";
        var $element = this.element();
        if ($element) {
            $element.css("cursor", cursorName)
        }
    }
}
export class BlockSeparatorView extends SeparatorView {
    init() {
        super.init();
        var dataController = this.getController("data");
        dataController.loadingChanged.add(isLoading => {
            if (!isLoading) {
                this.hide()
            }
        })
    }
    _renderSeparator() {
        super._renderSeparator();
        this.element().addClass(BLOCK_SEPARATOR_CLASS).html("&nbsp;")
    }
    hide() {
        var $parent = this._parentElement();
        var $element = this.element();
        if ($element && this._isShown) {
            $element.css("display", "none")
        }
        if ($parent && !$parent.children(".".concat(BLOCK_SEPARATOR_CLASS)).length) {
            $parent.prepend(this.element())
        }
        super.hide()
    }
    isVisible() {
        var groupPanelOptions = this.option("groupPanel");
        var columnChooserOptions = this.option("columnChooser");
        return groupPanelOptions && groupPanelOptions.visible || columnChooserOptions && columnChooserOptions.enabled
    }
    show(targetLocation) {
        var $element = this.element();
        if ($element && !this._isShown) {
            switch (targetLocation) {
                case "group":
                    this.element().css("display", "block");
                    break;
                case "columnChooser":
                    ! function(toOptions) {
                        fx.stop($element, true);
                        fx.animate($element, {
                            type: "slide",
                            from: {
                                width: 0,
                                display: toOptions.display
                            },
                            to: toOptions,
                            duration: 300,
                            easing: "swing"
                        })
                    }({
                        width: "100%",
                        display: "block"
                    });
                    break;
                default:
                    $element.css("display", "")
            }
        }
        super.show()
    }
}
export class DraggingHeaderView extends modules.View {
    init() {
        super.init();
        var dataController = this.getController("data");
        this._controller = this.getController("draggingHeader");
        this._columnsResizerViewController = this.getController("columnsResizer");
        this._columnsController = this.getController("columns");
        this._isDragging = false;
        dataController.loadingChanged.add(isLoading => {
            var element = this.element();
            if (!isLoading && element) {
                element.hide()
            }
        })
    }
    isDragging() {
        return this._isDragging
    }
    _getDraggingPanelByPos(pos) {
        var result;
        each(this._dragOptions.draggingPanels, (index, draggingPanel) => {
            if (draggingPanel) {
                var boundingRect = draggingPanel.getBoundingRect();
                if (boundingRect && (void 0 === boundingRect.bottom || pos.y < boundingRect.bottom) && (void 0 === boundingRect.top || pos.y > boundingRect.top) && (void 0 === boundingRect.left || pos.x > boundingRect.left) && (void 0 === boundingRect.right || pos.x < boundingRect.right)) {
                    result = draggingPanel;
                    return false
                }
            }
            return
        });
        return result
    }
    _renderCore() {
        this.element().addClass("".concat(this.addWidgetPrefix(DRAGGING_HEADER_CLASS), " ").concat(this.addWidgetPrefix(CELL_CONTENT_CLASS), " ").concat(WIDGET_CLASS)).hide()
    }
    _resetTargetColumnOptions() {
        var params = this._dropOptions;
        params.targetColumnIndex = -1;
        delete params.targetColumnElement;
        delete params.isLast;
        delete params.posX;
        delete params.posY
    }
    _getVisibleIndexObject(rowIndex, visibleIndex) {
        if (isDefined(rowIndex)) {
            return {
                columnIndex: visibleIndex,
                rowIndex: rowIndex
            }
        }
        return visibleIndex
    }
    dispose() {
        var element = this.element();
        this._dragOptions = null;
        element && element.parent().find(".".concat(this.addWidgetPrefix(DRAGGING_HEADER_CLASS))).remove()
    }
    isVisible() {
        var commonColumnSettings = this._columnsController.getCommonSettings();
        return this.option("showColumnHeaders") && (allowReordering(this) || commonColumnSettings.allowGrouping || commonColumnSettings.allowHiding)
    }
    dragHeader(options) {
        var {
            columnElement: columnElement
        } = options;
        var isCommandColumn = !!options.sourceColumn.type;
        this._isDragging = true;
        this._dragOptions = options;
        this._dropOptions = {
            sourceIndex: options.index,
            sourceColumnIndex: this._getVisibleIndexObject(options.rowIndex, options.columnIndex),
            sourceColumnElement: options.columnElement,
            sourceLocation: options.sourceLocation
        };
        var document = domAdapter.getDocument();
        this._onSelectStart = document.onselectstart;
        document.onselectstart = function() {
            return false
        };
        this._controller.drag(this._dropOptions);
        this.element().css({
            textAlign: columnElement && columnElement.css("textAlign"),
            height: columnElement && (isCommandColumn && columnElement.get(0).clientHeight || getHeight(columnElement)),
            width: columnElement && (isCommandColumn && columnElement.get(0).clientWidth || getWidth(columnElement)),
            whiteSpace: columnElement && columnElement.css("whiteSpace")
        }).addClass(this.addWidgetPrefix(HEADERS_DRAG_ACTION_CLASS)).toggleClass(DRAGGING_COMMAND_CELL_CLASS, isCommandColumn).text(isCommandColumn ? "" : options.sourceColumn.caption);
        this.element().appendTo(swatchContainer.getSwatchContainer(columnElement))
    }
    moveHeader(args) {
        var e = args.event;
        var {
            that: that
        } = e.data;
        var eventData = getEventData(e);
        var isResizing = that._columnsResizerViewController ? that._columnsResizerViewController.isResizing() : false;
        var dragOptions = that._dragOptions;
        if (that._isDragging && !isResizing) {
            var $element = that.element();
            var moveDeltaX = Math.abs(eventData.x - dragOptions.columnElement.offset().left - dragOptions.deltaX);
            var moveDeltaY = Math.abs(eventData.y - dragOptions.columnElement.offset().top - dragOptions.deltaY);
            if ($element.is(":visible") || moveDeltaX > DRAGGING_DELTA || moveDeltaY > DRAGGING_DELTA) {
                $element.show();
                var newLeft = eventData.x - dragOptions.deltaX;
                var newTop = eventData.y - dragOptions.deltaY;
                $element.css({
                    left: newLeft,
                    top: newTop
                });
                that.dockHeader(eventData)
            }
            e.preventDefault()
        }
    }
    dockHeader(eventData) {
        var targetDraggingPanel = this._getDraggingPanelByPos(eventData);
        var controller = this._controller;
        var params = this._dropOptions;
        var dragOptions = this._dragOptions;
        if (targetDraggingPanel) {
            var rtlEnabled = this.option("rtlEnabled");
            var isVerticalOrientation = "columnChooser" === targetDraggingPanel.getName();
            var axisName = isVerticalOrientation ? "y" : "x";
            var targetLocation = targetDraggingPanel.getName();
            var rowIndex = "headers" === targetLocation ? dragOptions.rowIndex : void 0;
            var {
                sourceColumn: sourceColumn
            } = dragOptions;
            var columnElements = targetDraggingPanel.getColumnElements(rowIndex, null === sourceColumn || void 0 === sourceColumn ? void 0 : sourceColumn.ownerBand) || [];
            var pointsByTarget = dragOptions.pointsByTarget = dragOptions.pointsByTarget || {};
            var pointsByColumns = "columnChooser" === targetLocation ? [] : pointsByTarget[targetLocation] || controller._generatePointsByColumns(extend({}, dragOptions, {
                targetDraggingPanel: targetDraggingPanel,
                columns: targetDraggingPanel.getColumns(rowIndex),
                columnElements: columnElements,
                isVerticalOrientation: isVerticalOrientation,
                startColumnIndex: "headers" === targetLocation && $(columnElements[0]).index()
            }));
            pointsByTarget[targetLocation] = pointsByColumns;
            params.targetLocation = targetLocation;
            if (pointsByColumns.length > 0) {
                for (var i = 0; i < pointsByColumns.length; i++) {
                    var centerPosition = pointsByColumns[i + 1] && (pointsByColumns[i][axisName] + pointsByColumns[i + 1][axisName]) / 2;
                    if (void 0 === centerPosition || (rtlEnabled && "x" === axisName ? eventData[axisName] > centerPosition : eventData[axisName] < centerPosition)) {
                        params.targetColumnIndex = this._getVisibleIndexObject(rowIndex, pointsByColumns[i].columnIndex);
                        if (columnElements[i]) {
                            params.targetColumnElement = columnElements.eq(i);
                            params.isLast = false
                        } else {
                            params.targetColumnElement = columnElements.last();
                            params.isLast = true
                        }
                        params.posX = pointsByColumns[i].x;
                        params.posY = pointsByColumns[i].y;
                        controller.dock(params);
                        break
                    }
                }
            } else {
                this._resetTargetColumnOptions();
                controller.dock(params)
            }
        }
    }
    dropHeader(args) {
        var e = args.event;
        var {
            that: that
        } = e.data;
        var controller = that._controller;
        that.element().hide();
        if (controller && that._isDragging) {
            controller.drop(that._dropOptions)
        }
        that.element().appendTo(that._parentElement());
        that._dragOptions = null;
        that._dropOptions = null;
        that._isDragging = false;
        domAdapter.getDocument().onselectstart = that._onSelectStart || null
    }
}
var isNextColumnResizingMode = function(that) {
    return "widget" !== that.option("columnResizingMode")
};
export class ColumnsResizerViewController extends modules.ViewController {
    init() {
        this._subscribesToCallbacks = [];
        if (allowResizing(this)) {
            this._init()
        }
    }
    dispose() {
        this._unsubscribes();
        super.dispose()
    }
    optionChanged(args) {
        super.optionChanged(args);
        if ("allowColumnResizing" === args.name) {
            if (args.value) {
                this._init();
                this._subscribeToEvents()
            } else {
                this._unsubscribes()
            }
        }
    }
    _isHeadersRowArea(posY) {
        if (this._columnHeadersView) {
            var element = this._columnHeadersView.element();
            if (element) {
                var offsetTop = element.offset().top;
                var headersRowHeight = this._columnHeadersView.getHeadersRowHeight();
                return posY >= offsetTop && posY <= offsetTop + headersRowHeight
            }
        }
        return false
    }
    _isRtlParentStyle() {
        var _a;
        return this.option("rtlEnabled") && "rtl" === (null === (_a = this._$parentContainer) || void 0 === _a ? void 0 : _a.parent().css("direction"))
    }
    _pointCreated(point, cellsLength, columns) {
        var isNextColumnMode = isNextColumnResizingMode(this);
        var rtlEnabled = this.option("rtlEnabled");
        var isRtlParentStyle = this._isRtlParentStyle();
        var firstPointColumnIndex = !isNextColumnMode && rtlEnabled && !isRtlParentStyle ? 0 : 1;
        if (point.index >= firstPointColumnIndex && point.index < cellsLength + (!isNextColumnMode && (!rtlEnabled || isRtlParentStyle) ? 1 : 0)) {
            point.columnIndex -= firstPointColumnIndex;
            var currentColumn = columns[point.columnIndex] || {};
            var nextColumn = columns[point.columnIndex + 1] || {};
            return !(isNextColumnMode ? currentColumn.allowResizing && nextColumn.allowResizing : currentColumn.allowResizing)
        }
        return true
    }
    _getTargetPoint(pointsByColumns, currentX, deltaX) {
        if (pointsByColumns) {
            for (var i = 0; i < pointsByColumns.length; i++) {
                if (pointsByColumns[i].x === pointsByColumns[0].x && pointsByColumns[i + 1] && pointsByColumns[i].x === pointsByColumns[i + 1].x) {
                    continue
                }
                if (pointsByColumns[i].x - deltaX <= currentX && currentX <= pointsByColumns[i].x + deltaX) {
                    return pointsByColumns[i]
                }
            }
        }
        return null
    }
    _moveSeparator(args) {
        var _a;
        var e = args.event;
        var that = e.data;
        var columnsSeparatorWidth = that._columnsSeparatorView.width();
        var isNextColumnMode = isNextColumnResizingMode(that);
        var deltaX = columnsSeparatorWidth / 2;
        var parentOffset = that._$parentContainer.offset();
        var parentOffsetLeft = parentOffset.left;
        var eventData = getEventData(e);
        var rtlEnabled = that.option("rtlEnabled");
        var isRtlParentStyle = this._isRtlParentStyle();
        var isDragging = null === (_a = that._draggingHeaderView) || void 0 === _a ? void 0 : _a.isDragging();
        if (that._isResizing && that._resizingInfo) {
            if ((parentOffsetLeft <= eventData.x || !isNextColumnMode && isRtlParentStyle) && (!isNextColumnMode || eventData.x <= parentOffsetLeft + getWidth(that._$parentContainer))) {
                if (that._updateColumnsWidthIfNeeded(eventData.x)) {
                    var $cell = that._columnHeadersView.getColumnElements().eq(that._resizingInfo.currentColumnIndex);
                    var cell = $cell[0];
                    if (cell) {
                        var outerWidth = cell.getBoundingClientRect().width;
                        that._columnsSeparatorView.moveByX($cell.offset().left + ((isNextColumnMode || isRtlParentStyle) && rtlEnabled ? 0 : outerWidth));
                        that._tablePositionController.update(that._targetPoint.y);
                        e.preventDefault()
                    }
                }
            }
        } else if (!isDragging) {
            if (that._isHeadersRowArea(eventData.y)) {
                if (that._previousParentOffset) {
                    if (that._previousParentOffset.left !== parentOffset.left || that._previousParentOffset.top !== parentOffset.top) {
                        that.pointsByColumns(null)
                    }
                }
                that._targetPoint = that._getTargetPoint(that.pointsByColumns(), eventData.x, columnsSeparatorWidth);
                that._previousParentOffset = parentOffset;
                that._isReadyResizing = false;
                if (that._targetPoint) {
                    that._columnsSeparatorView.changeCursor("col-resize");
                    that._columnsSeparatorView.moveByX(that._targetPoint.x - deltaX);
                    that._tablePositionController.update(that._targetPoint.y);
                    that._isReadyResizing = true;
                    e.preventDefault()
                } else {
                    that._columnsSeparatorView.changeCursor();
                    that._columnsSeparatorView.moveByX(null)
                }
            } else {
                that.pointsByColumns(null);
                that._isReadyResizing = false;
                that._columnsSeparatorView.changeCursor();
                that._columnsSeparatorView.moveByX(null)
            }
        }
    }
    _endResizing(args) {
        var e = args.event;
        var that = e.data;
        if (that._isResizing) {
            that.pointsByColumns(null);
            that._resizingInfo = null;
            that._columnsSeparatorView.hide();
            that._columnsSeparatorView.changeCursor();
            that._trackerView.hide();
            that._isReadyResizing = false;
            that._isResizing = false
        }
    }
    _getNextColumnIndex(currentColumnIndex) {
        return currentColumnIndex + 1
    }
    _setupResizingInfo(posX) {
        var currentColumnIndex = this._targetPoint.columnIndex;
        var nextColumnIndex = this._getNextColumnIndex(currentColumnIndex);
        var currentHeader = this._columnHeadersView.getHeaderElement(currentColumnIndex);
        var nextHeader = this._columnHeadersView.getHeaderElement(nextColumnIndex);
        this._resizingInfo = {
            startPosX: posX,
            currentColumnIndex: currentColumnIndex,
            currentColumnWidth: currentHeader && currentHeader.length > 0 ? getBoundingRect(currentHeader[0]).width : 0,
            nextColumnIndex: nextColumnIndex,
            nextColumnWidth: nextHeader && nextHeader.length > 0 ? getBoundingRect(nextHeader[0]).width : 0
        }
    }
    _startResizing(args) {
        var e = args.event;
        var that = e.data;
        var eventData = getEventData(e);
        if (isTouchEvent(e)) {
            if (that._isHeadersRowArea(eventData.y)) {
                that._targetPoint = that._getTargetPoint(that.pointsByColumns(), eventData.x, COLUMNS_SEPARATOR_TOUCH_TRACKER_WIDTH);
                if (that._targetPoint) {
                    that._columnsSeparatorView.moveByX(that._targetPoint.x - that._columnsSeparatorView.width() / 2);
                    that._isReadyResizing = true
                }
            } else {
                that._isReadyResizing = false
            }
        }
        if (that._isReadyResizing) {
            that._setupResizingInfo(eventData.x);
            that._isResizing = true;
            that._tablePositionController.update(that._targetPoint.y);
            that._columnsSeparatorView.show();
            that._trackerView.show();
            var scrollable = that.component.getScrollable();
            if (scrollable && that._isRtlParentStyle()) {
                that._scrollRight = getWidth(scrollable.$content()) - getWidth(scrollable.container()) - scrollable.scrollLeft()
            }
            e.preventDefault();
            e.stopPropagation()
        }
        if (this.isResizing()) {
            this._editorFactoryController.loseFocus()
        }
    }
    _generatePointsByColumns() {
        var that = this;
        var columns = that._columnsController ? that._columnsController.getVisibleColumns() : [];
        var cells = that._columnHeadersView.getColumnElements();
        var pointsByColumns = [];
        if (cells && cells.length > 0) {
            pointsByColumns = gridCoreUtils.getPointsByColumns(cells, point => that._pointCreated(point, cells.length, columns))
        }
        that._pointsByColumns = pointsByColumns
    }
    _unsubscribeFromEvents() {
        this._moveSeparatorHandler && eventsEngine.off(domAdapter.getDocument(), addNamespace(pointerEvents.move, MODULE_NAMESPACE), this._moveSeparatorHandler);
        this._startResizingHandler && eventsEngine.off(this._$parentContainer, addNamespace(pointerEvents.down, MODULE_NAMESPACE), this._startResizingHandler);
        if (this._endResizingHandler) {
            eventsEngine.off(this._columnsSeparatorView.element(), addNamespace(pointerEvents.up, MODULE_NAMESPACE), this._endResizingHandler);
            eventsEngine.off(domAdapter.getDocument(), addNamespace(pointerEvents.up, MODULE_NAMESPACE), this._endResizingHandler)
        }
    }
    _subscribeToEvents() {
        this._moveSeparatorHandler = this.createAction(this._moveSeparator);
        this._startResizingHandler = this.createAction(this._startResizing);
        this._endResizingHandler = this.createAction(this._endResizing);
        eventsEngine.on(domAdapter.getDocument(), addNamespace(pointerEvents.move, MODULE_NAMESPACE), this, this._moveSeparatorHandler);
        eventsEngine.on(this._$parentContainer, addNamespace(pointerEvents.down, MODULE_NAMESPACE), this, this._startResizingHandler);
        eventsEngine.on(this._columnsSeparatorView.element(), addNamespace(pointerEvents.up, MODULE_NAMESPACE), this, this._endResizingHandler);
        eventsEngine.on(domAdapter.getDocument(), addNamespace(pointerEvents.up, MODULE_NAMESPACE), this, this._endResizingHandler)
    }
    _updateColumnsWidthIfNeeded(posX) {
        var deltaX;
        var needUpdate;
        var contentWidth = this._rowsView.contentWidth();
        var resizingInfo = this._resizingInfo;
        var columnsController = this._columnsController;
        var visibleColumns = columnsController.getVisibleColumns();
        var columnsSeparatorWidth = this._columnsSeparatorView.width();
        var isNextColumnMode = isNextColumnResizingMode(this);
        var adaptColumnWidthByRatio = isNextColumnMode && this.option("adaptColumnWidthByRatio") && !this.option("columnAutoWidth");
        var rtlEnabled = this.option("rtlEnabled");
        var isRtlParentStyle = this._isRtlParentStyle();
        var column = visibleColumns[resizingInfo.currentColumnIndex];
        var nextColumn = visibleColumns[resizingInfo.nextColumnIndex];

        function isPercentWidth(width) {
            return isString(width) && width.endsWith("%")
        }

        function setColumnWidth(column, columnWidth, contentWidth, adaptColumnWidthByRatio) {
            if (column) {
                var oldColumnWidth = column.width;
                if (oldColumnWidth) {
                    adaptColumnWidthByRatio = isPercentWidth(oldColumnWidth)
                }
                if (adaptColumnWidthByRatio) {
                    columnsController.columnOption(column.index, "visibleWidth", columnWidth);
                    columnsController.columnOption(column.index, "width", "".concat((columnWidth / contentWidth * 100).toFixed(3), "%"))
                } else {
                    columnsController.columnOption(column.index, "visibleWidth", null);
                    columnsController.columnOption(column.index, "width", columnWidth)
                }
            }
        }
        deltaX = posX - resizingInfo.startPosX;
        if ((isNextColumnMode || isRtlParentStyle) && rtlEnabled) {
            deltaX = -deltaX
        }
        var {
            cellWidth: cellWidth,
            nextCellWidth: nextCellWidth
        } = function(delta) {
            var nextMinWidth;
            var nextCellWidth;
            var needCorrectionNextCellWidth;
            var cellWidth = resizingInfo.currentColumnWidth + delta;
            var minWidth = column && column.minWidth || columnsSeparatorWidth;
            var result = {};
            if (cellWidth >= minWidth) {
                result.cellWidth = cellWidth
            } else {
                result.cellWidth = minWidth;
                needCorrectionNextCellWidth = true
            }
            if (isNextColumnMode) {
                nextCellWidth = resizingInfo.nextColumnWidth - delta;
                nextMinWidth = nextColumn && nextColumn.minWidth || columnsSeparatorWidth;
                if (nextCellWidth >= nextMinWidth) {
                    if (needCorrectionNextCellWidth) {
                        result.nextCellWidth = resizingInfo.nextColumnWidth - (delta + minWidth - cellWidth)
                    } else {
                        result.nextCellWidth = nextCellWidth
                    }
                } else {
                    result.nextCellWidth = nextMinWidth;
                    result.cellWidth = resizingInfo.currentColumnWidth + (delta - nextMinWidth + nextCellWidth)
                }
            }
            return result
        }(deltaX);
        needUpdate = column.width !== cellWidth;
        if (needUpdate) {
            columnsController.beginUpdate();
            cellWidth = Math.floor(cellWidth);
            contentWidth = function(contentWidth, visibleColumns) {
                var allColumnsHaveWidth = visibleColumns.every(column => column.width);
                if (allColumnsHaveWidth) {
                    var totalPercent = visibleColumns.reduce((sum, column) => {
                        if (isPercentWidth(column.width)) {
                            sum += parseFloat(column.width)
                        }
                        return sum
                    }, 0);
                    if (totalPercent > 100) {
                        contentWidth = contentWidth / totalPercent * 100
                    }
                }
                return contentWidth
            }(contentWidth, visibleColumns);
            setColumnWidth(column, cellWidth, contentWidth, adaptColumnWidthByRatio);
            if (isNextColumnMode) {
                nextCellWidth = Math.floor(nextCellWidth);
                setColumnWidth(nextColumn, nextCellWidth, contentWidth, adaptColumnWidthByRatio)
            } else {
                var columnWidths = this._columnHeadersView.getColumnWidths();
                columnWidths[resizingInfo.currentColumnIndex] = cellWidth;
                var hasScroll = columnWidths.reduce((totalWidth, width) => totalWidth + width, 0) > this._rowsView.contentWidth();
                if (!hasScroll) {
                    var lastColumnIndex = gridCoreUtils.getLastResizableColumnIndex(visibleColumns);
                    if (lastColumnIndex >= 0) {
                        columnsController.columnOption(visibleColumns[lastColumnIndex].index, "visibleWidth", "auto")
                    }
                }
                for (var i = 0; i < columnWidths.length; i++) {
                    if (visibleColumns[i] && visibleColumns[i] !== column && void 0 === visibleColumns[i].width) {
                        columnsController.columnOption(visibleColumns[i].index, "width", columnWidths[i])
                    }
                }
            }
            columnsController.endUpdate();
            if (!isNextColumnMode) {
                this.component.updateDimensions();
                var scrollable = this.component.getScrollable();
                if (scrollable && isRtlParentStyle) {
                    var left = getWidth(scrollable.$content()) - getWidth(scrollable.container()) - this._scrollRight;
                    scrollable.scrollTo({
                        left: left
                    })
                }
            }
        }
        return needUpdate
    }
    _subscribeToCallback(callback, handler) {
        callback.add(handler);
        this._subscribesToCallbacks.push({
            callback: callback,
            handler: handler
        })
    }
    _unsubscribeFromCallbacks() {
        for (var i = 0; i < this._subscribesToCallbacks.length; i++) {
            var subscribe = this._subscribesToCallbacks[i];
            subscribe.callback.remove(subscribe.handler)
        }
        this._subscribesToCallbacks = []
    }
    _unsubscribes() {
        this._unsubscribeFromEvents();
        this._unsubscribeFromCallbacks()
    }
    _init() {
        var generatePointsByColumnsHandler = () => {
            if (!this._isResizing) {
                this.pointsByColumns(null)
            }
        };
        var generatePointsByColumnsScrollHandler = offset => {
            if (this._scrollLeft !== offset.left) {
                this._scrollLeft = offset.left;
                this.pointsByColumns(null)
            }
        };
        this._columnsSeparatorView = this.getView("columnsSeparatorView");
        this._columnHeadersView = this.getView("columnHeadersView");
        this._trackerView = this.getView("trackerView");
        this._rowsView = this.getView("rowsView");
        this._columnsController = this.getController("columns");
        this._tablePositionController = this.getController("tablePosition");
        this._editorFactoryController = this.getController("editorFactory");
        this._draggingHeaderView = this.component.getView("draggingHeaderView");
        this._$parentContainer = this.component.$element();
        this._subscribeToCallback(this._columnHeadersView.renderCompleted, generatePointsByColumnsHandler);
        this._subscribeToCallback(this._columnHeadersView.resizeCompleted, generatePointsByColumnsHandler);
        this._subscribeToCallback(this._columnsSeparatorView.renderCompleted, () => {
            this._unsubscribeFromEvents();
            this._subscribeToEvents()
        });
        this._subscribeToCallback(this._rowsView.renderCompleted, () => {
            this._rowsView.scrollChanged.remove(generatePointsByColumnsScrollHandler);
            this._rowsView.scrollChanged.add(generatePointsByColumnsScrollHandler)
        });
        var previousScrollbarVisibility = 0 !== this._rowsView.getScrollbarWidth();
        var previousTableHeight = 0;
        this._subscribeToCallback(this._tablePositionController.positionChanged, e => {
            if (this._isResizing && !this._rowsView.isResizing) {
                var scrollbarVisibility = 0 !== this._rowsView.getScrollbarWidth();
                if (previousScrollbarVisibility !== scrollbarVisibility || previousTableHeight && previousTableHeight !== e.height) {
                    previousScrollbarVisibility = scrollbarVisibility;
                    previousTableHeight = e.height;
                    this.component.updateDimensions()
                } else {
                    this._rowsView.updateFreeSpaceRowHeight()
                }
            }
            previousTableHeight = e.height
        })
    }
    isResizing() {
        return this._isResizing
    }
    pointsByColumns(value) {
        if (void 0 !== value) {
            this._pointsByColumns = value
        } else {
            if (!this._pointsByColumns) {
                this._generatePointsByColumns()
            }
            return this._pointsByColumns
        }
    }
}
export class TablePositionViewController extends modules.ViewController {
    constructor(component) {
        super(component);
        this.positionChanged = Callbacks()
    }
    init() {
        super.init();
        this._columnsResizerController = this.getController("columnsResizer");
        this._columnHeadersView = this.getView("columnHeadersView");
        this._rowsView = this.getView("rowsView");
        this._pagerView = this.getView("pagerView");
        this._rowsView.resizeCompleted.add(() => {
            if (this.option("allowColumnResizing")) {
                var targetPoint = this._columnsResizerController._targetPoint;
                this.update(targetPoint ? targetPoint.y : null)
            }
        })
    }
    update(top) {
        var params = {};
        var $element = this._columnHeadersView.element();
        var offset = $element && $element.offset();
        var offsetTop = offset && offset.top || 0;
        var diffOffsetTop = isDefined(top) ? Math.abs(top - offsetTop) : 0;
        var columnsHeadersHeight = this._columnHeadersView ? this._columnHeadersView.getHeight() : 0;
        var scrollBarWidth = this._rowsView.getScrollbarWidth(true);
        var rowsHeight = this._rowsView ? this._rowsView.height() - scrollBarWidth : 0;
        var draggingHeaderView = this.component.getView("draggingHeaderView");
        params.height = columnsHeadersHeight;
        var isDraggingOrResizing = this._columnsResizerController.isResizing() || draggingHeaderView.isDragging();
        if (isDraggingOrResizing) {
            params.height += rowsHeight - diffOffsetTop
        }
        if (null !== top && $element && $element.length) {
            params.top = $element[0].offsetTop + diffOffsetTop
        }
        this.positionChanged.fire(params)
    }
}
export class DraggingHeaderViewController extends modules.ViewController {
    init() {
        super.init();
        this._columnsController = this.getController("columns");
        this._tablePositionController = this.getController("tablePosition");
        this._columnHeadersView = this.getView("columnHeadersView");
        this._columnsSeparatorView = this.getView("columnsSeparatorView");
        this._draggingHeaderView = this.getView("draggingHeaderView");
        this._rowsView = this.getView("rowsView");
        this._blockSeparatorView = this.getView("blockSeparatorView");
        this._headerPanelView = this.getView("headerPanel");
        this._columnChooserView = this.getView("columnChooserView");
        var subscribeToEvents = () => {
            if (this._draggingHeaderView) {
                var draggingPanels = [this._columnChooserView, this._columnHeadersView, this._headerPanelView];
                this._unsubscribeFromEvents(this._draggingHeaderView, draggingPanels);
                this._subscribeToEvents(this._draggingHeaderView, draggingPanels)
            }
        };
        this._columnHeadersView.renderCompleted.add(subscribeToEvents);
        this._headerPanelView && this._headerPanelView.renderCompleted.add(subscribeToEvents);
        this._columnChooserView && this._columnChooserView.renderCompleted.add(subscribeToEvents)
    }
    dispose() {
        if (this._draggingHeaderView) {
            this._unsubscribeFromEvents(this._draggingHeaderView, [this._columnChooserView, this._columnHeadersView, this._headerPanelView])
        }
    }
    _generatePointsByColumns(options) {
        var that = this;
        this.isCustomGroupColumnPosition = this.checkIsCustomGroupColumnPosition(options);
        var points = gridCoreUtils.getPointsByColumns(options.columnElements, point => that._pointCreated(point, options.columns, options.targetDraggingPanel.getName(), options.sourceColumn), options.isVerticalOrientation, options.startColumnIndex);
        return points
    }
    checkIsCustomGroupColumnPosition(options) {
        var wasOnlyCommandColumns = true;
        for (var i = 0; i < options.columns.length; i += 1) {
            var col = options.columns[i];
            if ("expand" === col.command && !wasOnlyCommandColumns) {
                return true
            }
            if (!col.command) {
                wasOnlyCommandColumns = false
            }
        }
        return false
    }
    _pointCreated(point, columns, location, sourceColumn) {
        var _a;
        var targetColumn = columns[point.columnIndex];
        var prevColumn = columns[point.columnIndex - 1];
        var isColumnAfterExpandColumn = "expand" === (null === prevColumn || void 0 === prevColumn ? void 0 : prevColumn.command);
        var isFirstExpandColumn = "expand" === (null === targetColumn || void 0 === targetColumn ? void 0 : targetColumn.command) && "expand" !== (null === prevColumn || void 0 === prevColumn ? void 0 : prevColumn.command);
        var sourceColumnReorderingDisabled = sourceColumn && !sourceColumn.allowReordering;
        var otherColumnsReorderingDisabled = !(null === targetColumn || void 0 === targetColumn ? void 0 : targetColumn.allowReordering) && !(null === prevColumn || void 0 === prevColumn ? void 0 : prevColumn.allowReordering);
        switch (location) {
            case "columnChooser":
                return true;
            case "headers":
                if (sourceColumnReorderingDisabled) {
                    return true
                }
                if (!isFirstExpandColumn) {
                    return isColumnAfterExpandColumn || otherColumnsReorderingDisabled
                }
                if (this.isCustomGroupColumnPosition) {
                    return false
                }
                while ("expand" === (null === (_a = columns[point.columnIndex]) || void 0 === _a ? void 0 : _a.command)) {
                    point.columnIndex += 1
                }
                return false;
            default:
                return 0 === columns.length
        }
    }
    _subscribeToEvents(draggingHeader, draggingPanels) {
        var that = this;
        each(draggingPanels, (_, draggingPanel) => {
            if (draggingPanel) {
                var columns;
                var rowCount = draggingPanel.getRowCount ? draggingPanel.getRowCount() : 1;
                var nameDraggingPanel = draggingPanel.getName();
                var subscribeToEvents = function(index, columnElement) {
                    if (!columnElement) {
                        return
                    }
                    var $columnElement = $(columnElement);
                    var column = columns[index];
                    if (column && draggingPanel.allowDragging(column)) {
                        $columnElement.addClass(that.addWidgetPrefix(HEADERS_DRAG_ACTION_CLASS));
                        eventsEngine.on($columnElement, addNamespace(dragEventStart, MODULE_NAMESPACE), that.createAction(args => {
                            var e = args.event;
                            var eventData = getEventData(e);
                            draggingHeader.dragHeader({
                                deltaX: eventData.x - $(e.currentTarget).offset().left,
                                deltaY: eventData.y - $(e.currentTarget).offset().top,
                                sourceColumn: column,
                                index: column.index,
                                columnIndex: index,
                                columnElement: $columnElement,
                                sourceLocation: nameDraggingPanel,
                                draggingPanels: draggingPanels,
                                rowIndex: that._columnsController.getRowIndex(column.index, true)
                            })
                        }));
                        eventsEngine.on($columnElement, addNamespace(dragEventMove, MODULE_NAMESPACE), {
                            that: draggingHeader
                        }, that.createAction(draggingHeader.moveHeader));
                        eventsEngine.on($columnElement, addNamespace(dragEventEnd, MODULE_NAMESPACE), {
                            that: draggingHeader
                        }, that.createAction(draggingHeader.dropHeader))
                    }
                };
                for (var i = 0; i < rowCount; i++) {
                    var columnElements = draggingPanel.getColumnElements(i) || [];
                    if (columnElements.length) {
                        columns = draggingPanel.getColumns(i) || [];
                        each(columnElements, subscribeToEvents)
                    }
                }
            }
        })
    }
    _unsubscribeFromEvents(draggingHeader, draggingPanels) {
        var that = this;
        each(draggingPanels, (_, draggingPanel) => {
            if (draggingPanel) {
                var columnElements = draggingPanel.getColumnElements() || [];
                each(columnElements, (index, columnElement) => {
                    var $columnElement = $(columnElement);
                    eventsEngine.off($columnElement, addNamespace(dragEventStart, MODULE_NAMESPACE));
                    eventsEngine.off($columnElement, addNamespace(dragEventMove, MODULE_NAMESPACE));
                    eventsEngine.off($columnElement, addNamespace(dragEventEnd, MODULE_NAMESPACE));
                    $columnElement.removeClass(that.addWidgetPrefix(HEADERS_DRAG_ACTION_CLASS))
                })
            }
        })
    }
    _getSeparator(targetLocation) {
        return "headers" === targetLocation ? this._columnsSeparatorView : this._blockSeparatorView
    }
    hideSeparators(type) {
        var blockSeparator = this._blockSeparatorView;
        var columnsSeparator = this._columnsSeparatorView;
        this._animationColumnIndex = void 0;
        blockSeparator && blockSeparator.hide();
        "block" !== type && columnsSeparator && columnsSeparator.hide()
    }
    allowDrop(parameters) {
        return this._columnsController.allowMoveColumn(parameters.sourceColumnIndex, parameters.targetColumnIndex, parameters.sourceLocation, parameters.targetLocation)
    }
    drag(parameters) {
        var {
            sourceIndex: sourceIndex
        } = parameters;
        var {
            sourceLocation: sourceLocation
        } = parameters;
        var {
            sourceColumnElement: sourceColumnElement
        } = parameters;
        var headersView = this._columnHeadersView;
        var rowsView = this._rowsView;
        if (sourceColumnElement) {
            sourceColumnElement.css({
                opacity: COLUMN_OPACITY
            });
            if ("headers" === sourceLocation) {
                headersView && headersView.setRowsOpacity(sourceIndex, COLUMN_OPACITY);
                rowsView && rowsView.setRowsOpacity(sourceIndex, COLUMN_OPACITY)
            }
        }
    }
    dock(parameters) {
        var that = this;
        var targetColumnIndex = isObject(parameters.targetColumnIndex) ? parameters.targetColumnIndex.columnIndex : parameters.targetColumnIndex;
        var {
            sourceLocation: sourceLocation
        } = parameters;
        var {
            targetLocation: targetLocation
        } = parameters;
        var separator = that._getSeparator(targetLocation);
        var hasTargetVisibleIndex = targetColumnIndex >= 0;
        that._columnHeadersView.element().find(".".concat(HEADER_ROW_CLASS)).toggleClass(that.addWidgetPrefix(HEADERS_DROP_HIGHLIGHT_CLASS), "headers" !== sourceLocation && "headers" === targetLocation && !hasTargetVisibleIndex);
        if (separator) {
            if (that.allowDrop(parameters) && hasTargetVisibleIndex) {
                if ("group" === targetLocation || "columnChooser" === targetLocation) {
                    ! function() {
                        if (that._animationColumnIndex !== targetColumnIndex) {
                            that.hideSeparators();
                            separator.element()[parameters.isLast ? "insertAfter" : "insertBefore"](parameters.targetColumnElement);
                            that._animationColumnIndex = targetColumnIndex;
                            separator.show(targetLocation)
                        }
                    }()
                } else {
                    that.hideSeparators("block");
                    that._tablePositionController.update(parameters.posY);
                    separator.moveByX(parameters.posX - separator.width());
                    separator.show()
                }
            } else {
                that.hideSeparators()
            }
        }
    }
    drop(parameters) {
        var {
            sourceColumnElement: sourceColumnElement
        } = parameters;
        if (sourceColumnElement) {
            sourceColumnElement.css({
                opacity: ""
            });
            this._columnHeadersView.setRowsOpacity(parameters.sourceIndex, "");
            this._rowsView.setRowsOpacity(parameters.sourceIndex, "");
            this._columnHeadersView.element().find(".".concat(HEADER_ROW_CLASS)).removeClass(this.addWidgetPrefix(HEADERS_DROP_HIGHLIGHT_CLASS))
        }
        if (this.allowDrop(parameters)) {
            var separator = this._getSeparator(parameters.targetLocation);
            if (separator) {
                separator.hide()
            }
            this._columnsController.moveColumn(parameters.sourceColumnIndex, parameters.targetColumnIndex, parameters.sourceLocation, parameters.targetLocation)
        }
    }
}
var rowsView = Base => class extends Base {
    _needUpdateRowHeight(itemCount) {
        var wordWrapEnabled = this.option("wordWrapEnabled");
        var isResizing = this._columnsResizerController.isResizing();
        return super._needUpdateRowHeight.apply(this, arguments) || itemCount > 0 && wordWrapEnabled && isResizing
    }
};
var editorFactory = Base => class extends Base {
    renderFocusOverlay() {
        if (this._columnsResizerController.isResizing()) {
            return
        }
        return super.renderFocusOverlay.apply(this, arguments)
    }
};
export var columnsResizingReorderingModule = {
    views: {
        columnsSeparatorView: ColumnsSeparatorView,
        blockSeparatorView: BlockSeparatorView,
        draggingHeaderView: DraggingHeaderView,
        trackerView: TrackerView
    },
    controllers: {
        draggingHeader: DraggingHeaderViewController,
        tablePosition: TablePositionViewController,
        columnsResizer: ColumnsResizerViewController
    },
    extenders: {
        views: {
            rowsView: rowsView
        },
        controllers: {
            editorFactory: editorFactory
        }
    }
};
