"use strict";

exports.__esModule = true;
require("core-js/modules/es.array.push.js");
require("core-js/modules/es.error.cause.js");
var _base = require("../base");
var _element = require("../../helpers/dom/element");
var _array = require("../../helpers/array");
var _number = require("../../helpers/number");
var _translations = require("../../translations");
var _src = require("../../3rdparty/walkontable/src");
function _classPrivateMethodInitSpec(obj, privateSet) { _checkPrivateRedeclaration(obj, privateSet); privateSet.add(obj); }
function _classPrivateFieldInitSpec(obj, privateMap, value) { _checkPrivateRedeclaration(obj, privateMap); privateMap.set(obj, value); }
function _checkPrivateRedeclaration(obj, privateCollection) { if (privateCollection.has(obj)) { throw new TypeError("Cannot initialize the same private elements twice on an object"); } }
function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); }
function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
function _classPrivateFieldGet(receiver, privateMap) { var descriptor = _classExtractFieldDescriptor(receiver, privateMap, "get"); return _classApplyDescriptorGet(receiver, descriptor); }
function _classApplyDescriptorGet(receiver, descriptor) { if (descriptor.get) { return descriptor.get.call(receiver); } return descriptor.value; }
function _classPrivateFieldSet(receiver, privateMap, value) { var descriptor = _classExtractFieldDescriptor(receiver, privateMap, "set"); _classApplyDescriptorSet(receiver, descriptor, value); return value; }
function _classExtractFieldDescriptor(receiver, privateMap, action) { if (!privateMap.has(receiver)) { throw new TypeError("attempted to " + action + " private field on non-instance"); } return privateMap.get(receiver); }
function _classApplyDescriptorSet(receiver, descriptor, value) { if (descriptor.set) { descriptor.set.call(receiver, value); } else { if (!descriptor.writable) { throw new TypeError("attempted to set read only private field"); } descriptor.value = value; } }
function _classPrivateMethodGet(receiver, privateSet, fn) { if (!privateSet.has(receiver)) { throw new TypeError("attempted to get private field on non-instance"); } return fn; }
// Developer note! Whenever you make a change in this file, make an analogous change in manualColumnResize.js

const PLUGIN_KEY = 'manualRowResize';
exports.PLUGIN_KEY = PLUGIN_KEY;
const PLUGIN_PRIORITY = 30;
exports.PLUGIN_PRIORITY = PLUGIN_PRIORITY;
const PERSISTENT_STATE_KEY = 'manualRowHeights';

/* eslint-disable jsdoc/require-description-complete-sentence */

/**
 * @plugin ManualRowResize
 * @class ManualRowResize
 *
 * @description
 * This plugin allows to change rows height. To make rows height persistent the {@link Options#persistentState}
 * plugin should be enabled.
 *
 * The plugin creates additional components to make resizing possibly using user interface:
 * - handle - the draggable element that sets the desired height of the row.
 * - guide - the helper guide that shows the desired height as a horizontal guide.
 */
var _config = /*#__PURE__*/new WeakMap();
var _onMouseOver = /*#__PURE__*/new WeakSet();
var _onMouseDown = /*#__PURE__*/new WeakSet();
var _onMouseMove = /*#__PURE__*/new WeakSet();
var _onMouseUp = /*#__PURE__*/new WeakSet();
var _onContextMenu = /*#__PURE__*/new WeakSet();
var _onModifyRowHeight = /*#__PURE__*/new WeakSet();
var _onMapInit = /*#__PURE__*/new WeakSet();
class ManualRowResize extends _base.BasePlugin {
  static get PLUGIN_KEY() {
    return PLUGIN_KEY;
  }
  static get PLUGIN_PRIORITY() {
    return PLUGIN_PRIORITY;
  }

  /**
   * @type {HTMLTableCellElement}
   */

  constructor(hotInstance) {
    super(hotInstance);
    /**
     * Callback to call on map's `init` local hook.
     */
    _classPrivateMethodInitSpec(this, _onMapInit);
    /**
     * Modifies the provided row height, based on the plugin settings.
     *
     * @param {number} height Row height.
     * @param {number} row Visual row index.
     * @returns {number}
     */
    _classPrivateMethodInitSpec(this, _onModifyRowHeight);
    /**
     * Callback for "contextmenu" event triggered on element showing move handle. It removes handle and guide elements.
     */
    _classPrivateMethodInitSpec(this, _onContextMenu);
    /**
     * 'mouseup' event callback - apply the row resizing.
     *
     * @fires Hooks#beforeRowResize
     * @fires Hooks#afterRowResize
     */
    _classPrivateMethodInitSpec(this, _onMouseUp);
    /**
     * 'mousemove' event callback - refresh the handle and guide positions, cache the new row height.
     *
     * @param {MouseEvent} event The mouse event.
     */
    _classPrivateMethodInitSpec(this, _onMouseMove);
    /**
     * 'mousedown' event callback.
     *
     * @param {MouseEvent} event The mouse event.
     */
    _classPrivateMethodInitSpec(this, _onMouseDown);
    /**
     * 'mouseover' event callback - set the handle position.
     *
     * @param {MouseEvent} event The mouse event.
     */
    _classPrivateMethodInitSpec(this, _onMouseOver);
    _defineProperty(this, "currentTH", null);
    /**
     * @type {number}
     */
    _defineProperty(this, "currentRow", null);
    /**
     * @type {number[]}
     */
    _defineProperty(this, "selectedRows", []);
    /**
     * @type {number}
     */
    _defineProperty(this, "currentHeight", null);
    /**
     * @type {number}
     */
    _defineProperty(this, "newSize", null);
    /**
     * @type {number}
     */
    _defineProperty(this, "startY", null);
    /**
     * @type {number}
     */
    _defineProperty(this, "startHeight", null);
    /**
     * @type {number}
     */
    _defineProperty(this, "startOffset", null);
    /**
     * @type {HTMLElement}
     */
    _defineProperty(this, "handle", this.hot.rootDocument.createElement('DIV'));
    /**
     * @type {HTMLElement}
     */
    _defineProperty(this, "guide", this.hot.rootDocument.createElement('DIV'));
    /**
     * @type {boolean}
     */
    _defineProperty(this, "pressed", false);
    /**
     * @type {boolean}
     */
    _defineProperty(this, "isTriggeredByRMB", false);
    /**
     * @type {number}
     */
    _defineProperty(this, "dblclick", 0);
    /**
     * @type {number}
     */
    _defineProperty(this, "autoresizeTimeout", null);
    /**
     * PhysicalIndexToValueMap to keep and track widths for physical row indexes.
     *
     * @private
     * @type {PhysicalIndexToValueMap}
     */
    _defineProperty(this, "rowHeightsMap", void 0);
    /**
     * Private pool to save configuration from updateSettings.
     *
     * @type {object}
     */
    _classPrivateFieldInitSpec(this, _config, {
      writable: true,
      value: void 0
    });
    (0, _element.addClass)(this.handle, 'manualRowResizer');
    (0, _element.addClass)(this.guide, 'manualRowResizerGuide');
  }

  /**
   * @private
   * @returns {string}
   */
  get inlineDir() {
    return this.hot.isRtl() ? 'right' : 'left';
  }

  /**
   * Checks if the plugin is enabled in the handsontable settings. This method is executed in {@link Hooks#beforeInit}
   * hook and if it returns `true` then the {@link ManualRowResize#enablePlugin} method is called.
   *
   * @returns {boolean}
   */
  isEnabled() {
    return this.hot.getSettings()[PLUGIN_KEY];
  }

  /**
   * Enables the plugin functionality for this Handsontable instance.
   */
  enablePlugin() {
    if (this.enabled) {
      return;
    }
    this.rowHeightsMap = new _translations.PhysicalIndexToValueMap();
    this.rowHeightsMap.addLocalHook('init', () => _classPrivateMethodGet(this, _onMapInit, _onMapInit2).call(this));
    this.hot.rowIndexMapper.registerMap(this.pluginName, this.rowHeightsMap);
    this.addHook('modifyRowHeight', (height, row) => _classPrivateMethodGet(this, _onModifyRowHeight, _onModifyRowHeight2).call(this, height, row));
    this.bindEvents();
    super.enablePlugin();
  }

  /**
   * Updates the plugin's state.
   *
   * This method is executed when [`updateSettings()`](@/api/core.md#updatesettings) is invoked with any of the following configuration options:
   *  - [`manualRowResize`](@/api/options.md#manualrowresize)
   */
  updatePlugin() {
    this.disablePlugin();
    this.enablePlugin();
    super.updatePlugin();
  }

  /**
   * Disables the plugin functionality for this Handsontable instance.
   */
  disablePlugin() {
    _classPrivateFieldSet(this, _config, this.rowHeightsMap.getValues());
    this.hot.rowIndexMapper.unregisterMap(this.pluginName);
    super.disablePlugin();
  }

  /**
   * Saves the current sizes using the persistentState plugin (the {@link Options#persistentState} option has to be
   * enabled).
   *
   * @fires Hooks#persistentStateSave
   */
  saveManualRowHeights() {
    this.hot.runHooks('persistentStateSave', PERSISTENT_STATE_KEY, this.rowHeightsMap.getValues());
  }

  /**
   * Loads the previously saved sizes using the persistentState plugin (the {@link Options#persistentState} option
   * has be enabled).
   *
   * @returns {Array}
   * @fires Hooks#persistentStateLoad
   */
  loadManualRowHeights() {
    const storedState = {};
    this.hot.runHooks('persistentStateLoad', PERSISTENT_STATE_KEY, storedState);
    return storedState.value;
  }

  /**
   * Sets the new height for specified row index.
   *
   * @param {number} row Visual row index.
   * @param {number} height Row height.
   * @returns {number} Returns new height.
   */
  setManualSize(row, height) {
    const physicalRow = this.hot.toPhysicalRow(row);
    const newHeight = Math.max(height, _src.ViewportRowsCalculator.DEFAULT_HEIGHT);
    this.rowHeightsMap.setValueAtIndex(physicalRow, newHeight);
    return newHeight;
  }

  /**
   * Sets the resize handle position.
   *
   * @private
   * @param {HTMLCellElement} TH TH HTML element.
   */
  setupHandlePosition(TH) {
    this.currentTH = TH;
    const {
      view
    } = this.hot;
    const {
      _wt: wt
    } = view;
    const cellCoords = wt.wtTable.getCoords(this.currentTH);
    const row = cellCoords.row;

    // Ignore row headers.
    if (row < 0) {
      return;
    }
    const headerWidth = (0, _element.outerWidth)(this.currentTH);
    const box = this.currentTH.getBoundingClientRect();
    // Read "fixedRowsTop" and "fixedRowsBottom" through the Walkontable as in that context, the fixed
    // rows are modified (reduced by the number of hidden rows) by TableView module.
    const fixedRowTop = row < wt.getSetting('fixedRowsTop');
    const fixedRowBottom = row >= view.countNotHiddenRowIndexes(0, 1) - wt.getSetting('fixedRowsBottom');
    let relativeHeaderPosition;
    if (fixedRowTop) {
      relativeHeaderPosition = wt.wtOverlays.topInlineStartCornerOverlay.getRelativeCellPosition(this.currentTH, cellCoords.row, cellCoords.col);
    } else if (fixedRowBottom) {
      relativeHeaderPosition = wt.wtOverlays.bottomInlineStartCornerOverlay.getRelativeCellPosition(this.currentTH, cellCoords.row, cellCoords.col);
    }

    // If the TH is not a child of the top-left/bottom-left overlay, recalculate using
    // the left overlay - as this overlay contains the rest of the headers.
    if (!relativeHeaderPosition) {
      relativeHeaderPosition = wt.wtOverlays.inlineStartOverlay.getRelativeCellPosition(this.currentTH, cellCoords.row, cellCoords.col);
    }
    this.currentRow = this.hot.rowIndexMapper.getVisualFromRenderableIndex(row);
    this.selectedRows = [];
    const isFullRowSelected = this.hot.selection.isSelectedByCorner() || this.hot.selection.isSelectedByRowHeader();
    if (this.hot.selection.isSelected() && isFullRowSelected) {
      const selectionRanges = this.hot.getSelectedRange();
      (0, _array.arrayEach)(selectionRanges, selectionRange => {
        const fromRow = selectionRange.getTopStartCorner().row;
        const toRow = selectionRange.getBottomStartCorner().row;

        // Add every selected row for resize action.
        (0, _number.rangeEach)(fromRow, toRow, rowIndex => {
          if (!this.selectedRows.includes(rowIndex)) {
            this.selectedRows.push(rowIndex);
          }
        });
      });
    }

    // Resizing element beyond the current selection (also when there is no selection).
    if (!this.selectedRows.includes(this.currentRow)) {
      this.selectedRows = [this.currentRow];
    }
    this.startOffset = relativeHeaderPosition.top - 6;
    this.startHeight = parseInt(box.height, 10);
    this.handle.style.top = `${this.startOffset + this.startHeight}px`;
    this.handle.style[this.inlineDir] = `${relativeHeaderPosition.start}px`;
    this.handle.style.width = `${headerWidth}px`;
    this.hot.rootElement.appendChild(this.handle);
  }

  /**
   * Refresh the resize handle position.
   *
   * @private
   */
  refreshHandlePosition() {
    this.handle.style.top = `${this.startOffset + this.currentHeight}px`;
  }

  /**
   * Sets the resize guide position.
   *
   * @private
   */
  setupGuidePosition() {
    const handleWidth = parseInt((0, _element.outerWidth)(this.handle), 10);
    const handleEndPosition = parseInt(this.handle.style[this.inlineDir], 10) + handleWidth;
    const maximumVisibleElementWidth = parseInt(this.hot.view.maximumVisibleElementWidth(0), 10);
    (0, _element.addClass)(this.handle, 'active');
    (0, _element.addClass)(this.guide, 'active');
    this.guide.style.top = this.handle.style.top;
    this.guide.style[this.inlineDir] = `${handleEndPosition}px`;
    this.guide.style.width = `${maximumVisibleElementWidth - handleWidth}px`;
    this.hot.rootElement.appendChild(this.guide);
  }

  /**
   * Refresh the resize guide position.
   *
   * @private
   */
  refreshGuidePosition() {
    this.guide.style.top = this.handle.style.top;
  }

  /**
   * Hides both the resize handle and resize guide.
   *
   * @private
   */
  hideHandleAndGuide() {
    (0, _element.removeClass)(this.handle, 'active');
    (0, _element.removeClass)(this.guide, 'active');
  }

  /**
   * Checks if provided element is considered as a row header.
   *
   * @private
   * @param {HTMLElement} element HTML element.
   * @returns {boolean}
   */
  checkIfRowHeader(element) {
    var _element$parentNode;
    const thElement = (0, _element.closest)(element, ['TH'], this.hot.rootElement);
    return thElement && ((_element$parentNode = element.parentNode) === null || _element$parentNode === void 0 || (_element$parentNode = _element$parentNode.parentNode) === null || _element$parentNode === void 0 ? void 0 : _element$parentNode.tagName) === 'TBODY';
  }

  /**
   * Gets the TH element from the provided element.
   *
   * @private
   * @param {HTMLElement} element HTML element.
   * @returns {HTMLElement}
   */
  getClosestTHParent(element) {
    if (element.tagName !== 'TABLE') {
      if (element.tagName === 'TH') {
        return element;
      }
      return this.getClosestTHParent(element.parentNode);
    }
    return null;
  }

  /**
   * Returns the actual height for the provided row index.
   *
   * @private
   * @param {number} row Visual row index.
   * @returns {number} Actual row height.
   */
  getActualRowHeight(row) {
    // TODO: this should utilize `this.hot.getRowHeight` after it's fixed and working properly.
    const walkontableHeight = this.hot.view._wt.wtTable.getRowHeight(row);
    if (walkontableHeight !== undefined && this.newSize < walkontableHeight) {
      return walkontableHeight;
    }
    return this.newSize;
  }
  /**
   * Auto-size row after doubleclick - callback.
   *
   * @private
   * @fires Hooks#beforeRowResize
   * @fires Hooks#afterRowResize
   */
  afterMouseDownTimeout() {
    const render = () => {
      this.hot.forceFullRender = true;
      this.hot.view.render(); // updates all
      this.hot.view.adjustElementsSize(true);
    };
    const resize = (row, forceRender) => {
      const hookNewSize = this.hot.runHooks('beforeRowResize', this.getActualRowHeight(row), row, true);
      if (hookNewSize !== undefined) {
        this.newSize = hookNewSize;
      }
      this.setManualSize(row, this.newSize); // double click sets auto row size

      this.hot.runHooks('afterRowResize', this.getActualRowHeight(row), row, true);
      if (forceRender) {
        render();
      }
    };
    if (this.dblclick >= 2) {
      const selectedRowsLength = this.selectedRows.length;
      if (selectedRowsLength > 1) {
        (0, _array.arrayEach)(this.selectedRows, selectedRow => {
          resize(selectedRow);
        });
        render();
      } else {
        (0, _array.arrayEach)(this.selectedRows, selectedRow => {
          resize(selectedRow, true);
        });
      }
    }
    this.dblclick = 0;
    this.autoresizeTimeout = null;
  }
  /**
   * Binds the mouse events.
   *
   * @private
   */
  bindEvents() {
    const {
      rootElement,
      rootWindow
    } = this.hot;
    this.eventManager.addEventListener(rootElement, 'mouseover', e => _classPrivateMethodGet(this, _onMouseOver, _onMouseOver2).call(this, e));
    this.eventManager.addEventListener(rootElement, 'mousedown', e => _classPrivateMethodGet(this, _onMouseDown, _onMouseDown2).call(this, e));
    this.eventManager.addEventListener(rootWindow, 'mousemove', e => _classPrivateMethodGet(this, _onMouseMove, _onMouseMove2).call(this, e));
    this.eventManager.addEventListener(rootWindow, 'mouseup', () => _classPrivateMethodGet(this, _onMouseUp, _onMouseUp2).call(this));
    this.eventManager.addEventListener(this.handle, 'contextmenu', () => _classPrivateMethodGet(this, _onContextMenu, _onContextMenu2).call(this));
  }
  /**
   * Destroys the plugin instance.
   */
  destroy() {
    super.destroy();
  }
}
exports.ManualRowResize = ManualRowResize;
function _onMouseOver2(event) {
  // Workaround for #6926 - if the `event.target` is temporarily detached, we can skip this callback and wait for
  // the next `onmouseover`.
  if ((0, _element.isDetached)(event.target)) {
    return;
  }

  // A "mouseover" action is triggered right after executing "contextmenu" event. It should be ignored.
  if (this.isTriggeredByRMB === true) {
    return;
  }
  if (this.checkIfRowHeader(event.target)) {
    const th = this.getClosestTHParent(event.target);
    if (th) {
      if (!this.pressed) {
        this.setupHandlePosition(th);
      }
    }
  }
}
function _onMouseDown2(event) {
  if ((0, _element.hasClass)(event.target, 'manualRowResizer')) {
    this.setupHandlePosition(this.currentTH);
    this.setupGuidePosition();
    this.pressed = true;
    if (this.autoresizeTimeout === null) {
      this.autoresizeTimeout = setTimeout(() => this.afterMouseDownTimeout(), 500);
      this.hot._registerTimeout(this.autoresizeTimeout);
    }
    this.dblclick += 1;
    this.startY = event.pageY;
    this.newSize = this.startHeight;
  }
}
function _onMouseMove2(event) {
  if (this.pressed) {
    this.currentHeight = this.startHeight + (event.pageY - this.startY);
    (0, _array.arrayEach)(this.selectedRows, selectedRow => {
      this.newSize = this.setManualSize(selectedRow, this.currentHeight);
    });
    this.refreshHandlePosition();
    this.refreshGuidePosition();
  }
}
function _onMouseUp2() {
  const render = () => {
    this.hot.forceFullRender = true;
    this.hot.view.render(); // updates all
    this.hot.view.adjustElementsSize(true);
  };
  const runHooks = (row, forceRender) => {
    this.hot.runHooks('beforeRowResize', this.getActualRowHeight(row), row, false);
    if (forceRender) {
      render();
    }
    this.saveManualRowHeights();
    this.hot.runHooks('afterRowResize', this.getActualRowHeight(row), row, false);
  };
  if (this.pressed) {
    this.hideHandleAndGuide();
    this.pressed = false;
    if (this.newSize !== this.startHeight) {
      const selectedRowsLength = this.selectedRows.length;
      if (selectedRowsLength > 1) {
        (0, _array.arrayEach)(this.selectedRows, selectedRow => {
          runHooks(selectedRow);
        });
        render();
      } else {
        (0, _array.arrayEach)(this.selectedRows, selectedRow => {
          runHooks(selectedRow, true);
        });
      }
    }
    this.setupHandlePosition(this.currentTH);
  }
}
function _onContextMenu2() {
  this.hideHandleAndGuide();
  this.hot.rootElement.removeChild(this.handle);
  this.hot.rootElement.removeChild(this.guide);
  this.pressed = false;
  this.isTriggeredByRMB = true;

  // There is thrown "mouseover" event right after opening a context menu. This flag inform that handle
  // shouldn't be drawn just after removing it.
  this.hot._registerImmediate(() => {
    this.isTriggeredByRMB = false;
  });
}
function _onModifyRowHeight2(height, row) {
  let newHeight = height;
  if (this.enabled) {
    const physicalRow = this.hot.toPhysicalRow(row);
    const rowHeight = this.rowHeightsMap.getValueAtIndex(physicalRow);
    if (this.hot.getSettings()[PLUGIN_KEY] && rowHeight) {
      newHeight = rowHeight;
    }
  }
  return newHeight;
}
function _onMapInit2() {
  const initialSetting = this.hot.getSettings()[PLUGIN_KEY];
  const loadedManualRowHeights = this.loadManualRowHeights();
  this.hot.batchExecution(() => {
    if (typeof loadedManualRowHeights !== 'undefined') {
      loadedManualRowHeights.forEach((height, index) => {
        this.rowHeightsMap.setValueAtIndex(index, height);
      });
    } else if (Array.isArray(initialSetting)) {
      initialSetting.forEach((height, index) => {
        this.rowHeightsMap.setValueAtIndex(index, height);
      });
      _classPrivateFieldSet(this, _config, initialSetting);
    } else if (initialSetting === true && Array.isArray(_classPrivateFieldGet(this, _config))) {
      _classPrivateFieldGet(this, _config).forEach((height, index) => {
        this.rowHeightsMap.setValueAtIndex(index, height);
      });
    }
  }, true);
}