"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 _pluginHooks = _interopRequireDefault(require("../../pluginHooks"));
var _cellsCollection = _interopRequireDefault(require("./cellsCollection"));
var _cellCoords = _interopRequireDefault(require("./cellCoords"));
var _autofill = _interopRequireDefault(require("./calculations/autofill"));
var _selection = _interopRequireDefault(require("./calculations/selection"));
var _toggleMerge = _interopRequireDefault(require("./contextMenuItem/toggleMerge"));
var _array = require("../../helpers/array");
var _object = require("../../helpers/object");
var _console = require("../../helpers/console");
var _number = require("../../helpers/number");
var _utils = require("./utils");
var _element = require("../../helpers/dom/element");
var _browser = require("../../helpers/browser");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
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(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : String(i); }
function _toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
function _classPrivateFieldSet(receiver, privateMap, value) { var descriptor = _classExtractFieldDescriptor(receiver, privateMap, "set"); _classApplyDescriptorSet(receiver, descriptor, value); return value; }
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 _classPrivateFieldGet(receiver, privateMap) { var descriptor = _classExtractFieldDescriptor(receiver, privateMap, "get"); return _classApplyDescriptorGet(receiver, descriptor); }
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 _classApplyDescriptorGet(receiver, descriptor) { if (descriptor.get) { return descriptor.get.call(receiver); } return descriptor.value; }
function _classPrivateMethodGet(receiver, privateSet, fn) { if (!privateSet.has(receiver)) { throw new TypeError("attempted to get private field on non-instance"); } return fn; }
_pluginHooks.default.getSingleton().register('beforeMergeCells');
_pluginHooks.default.getSingleton().register('afterMergeCells');
_pluginHooks.default.getSingleton().register('beforeUnmergeCells');
_pluginHooks.default.getSingleton().register('afterUnmergeCells');
const PLUGIN_KEY = exports.PLUGIN_KEY = 'mergeCells';
const PLUGIN_PRIORITY = exports.PLUGIN_PRIORITY = 150;
const SHORTCUTS_GROUP = PLUGIN_KEY;

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

/**
 * @plugin MergeCells
 * @class MergeCells
 *
 * @description
 * Plugin, which allows merging cells in the table (using the initial configuration, API or context menu).
 *
 * @example
 *
 * ::: only-for javascript
 * ```js
 * const hot = new Handsontable(document.getElementById('example'), {
 *  data: getData(),
 *  mergeCells: [
 *    {row: 0, col: 3, rowspan: 3, colspan: 3},
 *    {row: 2, col: 6, rowspan: 2, colspan: 2},
 *    {row: 4, col: 8, rowspan: 3, colspan: 3}
 *  ],
 * ```
 * :::
 *
 * ::: only-for react
 * ```jsx
 * <HotTable
 *   data={getData()}
 *   // enable plugin
 *   mergeCells={[
 *    {row: 0, col: 3, rowspan: 3, colspan: 3},
 *    {row: 2, col: 6, rowspan: 2, colspan: 2},
 *    {row: 4, col: 8, rowspan: 3, colspan: 3}
 *   ]}
 * />
 * ```
 * :::
 */
var _lastDesiredCoords = /*#__PURE__*/new WeakMap();
var _onAfterInit = /*#__PURE__*/new WeakSet();
var _onAfterIsMultipleSelection = /*#__PURE__*/new WeakSet();
var _onModifyTransformStart = /*#__PURE__*/new WeakSet();
var _onModifyTransformEnd = /*#__PURE__*/new WeakSet();
var _onModifyGetCellCoords = /*#__PURE__*/new WeakSet();
var _addMergeActionsToContextMenu = /*#__PURE__*/new WeakSet();
var _onAfterRenderer = /*#__PURE__*/new WeakSet();
var _onBeforeSetRangeStart = /*#__PURE__*/new WeakSet();
var _onBeforeSetRangeEnd = /*#__PURE__*/new WeakSet();
var _onAfterGetCellMeta = /*#__PURE__*/new WeakSet();
var _onAfterViewportRowCalculatorOverride = /*#__PURE__*/new WeakSet();
var _onAfterViewportColumnCalculatorOverride = /*#__PURE__*/new WeakSet();
var _onModifyAutofillRange = /*#__PURE__*/new WeakSet();
var _onAfterCreateCol = /*#__PURE__*/new WeakSet();
var _onAfterRemoveCol = /*#__PURE__*/new WeakSet();
var _onAfterCreateRow = /*#__PURE__*/new WeakSet();
var _onAfterRemoveRow = /*#__PURE__*/new WeakSet();
var _onAfterChange = /*#__PURE__*/new WeakSet();
var _onBeforeDrawAreaBorders = /*#__PURE__*/new WeakSet();
var _onAfterModifyTransformStart = /*#__PURE__*/new WeakSet();
var _onAfterDrawSelection = /*#__PURE__*/new WeakSet();
var _onBeforeRemoveCellClassNames = /*#__PURE__*/new WeakSet();
var _onBeforeBeginEditing = /*#__PURE__*/new WeakSet();
class MergeCells extends _base.BasePlugin {
  constructor() {
    super(...arguments);
    /**
     * Allows to prevent opening the editor while more than one merged cell is selected.
     *
     * @param {number} row Visual row index of the edited cell.
     * @param {number} column Visual column index of the edited cell.
     * @param {string | null} initialValue The initial editor value.
     * @param {MouseEvent | KeyboardEvent} event The event which was responsible for opening the editor.
     * @returns {boolean | undefined}
     */
    _classPrivateMethodInitSpec(this, _onBeforeBeginEditing);
    /**
     * `beforeRemoveCellClassNames` hook callback. Used to remove additional class name from all cells in the table.
     *
     * @returns {string[]} An `Array` of `String`s. Each of these strings will act like class names to be removed from
     *   all the cells in the table.
     */
    _classPrivateMethodInitSpec(this, _onBeforeRemoveCellClassNames);
    /**
     * `afterDrawSelection` hook callback. Used to add the additional class name for the entirely-selected merged cells.
     *
     * @param {number} currentRow Visual row index of the currently processed cell.
     * @param {number} currentColumn Visual column index of the currently cell.
     * @param {Array} cornersOfSelection Array of the current selection in a form of `[startRow, startColumn, endRow,
     *   endColumn]`.
     * @param {number|undefined} layerLevel Number indicating which layer of selection is currently processed.
     * @returns {string|undefined} A `String`, which will act as an additional `className` to be added to the currently
     *   processed cell.
     */
    _classPrivateMethodInitSpec(this, _onAfterDrawSelection);
    /**
     * `afterModifyTransformStart` hook callback. Fixes a problem with navigating through merged cells at the edges of
     * the table with the <kbd>**Enter**</kbd>/<kbd>**Shift**</kbd>+<kbd>**Enter**</kbd>/<kbd>**Tab**</kbd>/<kbd>**Shift**</kbd>+<kbd>**Tab**</kbd> keys.
     *
     * @param {CellCoords} coords Coordinates of the to-be-selected cell.
     * @param {number} rowTransformDir Row transformation direction (negative value = up, 0 = none, positive value =
     *   down).
     * @param {number} colTransformDir Column transformation direction (negative value = up, 0 = none, positive value =
     *   down).
     */
    _classPrivateMethodInitSpec(this, _onAfterModifyTransformStart);
    /**
     * `beforeDrawAreaBorders` hook callback.
     *
     * @param {Array} corners Visual coordinates of the area corners.
     * @param {string} className Class name for the area.
     */
    _classPrivateMethodInitSpec(this, _onBeforeDrawAreaBorders);
    /**
     * `afterChange` hook callback. Used to propagate merged cells after using Autofill.
     *
     * @param {Array} changes The changes array.
     * @param {string} source Determines the source of the change.
     */
    _classPrivateMethodInitSpec(this, _onAfterChange);
    /**
     * `afterRemoveRow` hook callback.
     *
     * @param {number} row Row index.
     * @param {number} count Number of removed rows.
     */
    _classPrivateMethodInitSpec(this, _onAfterRemoveRow);
    /**
     * `afterCreateRow` hook callback.
     *
     * @param {number} row Row index.
     * @param {number} count Number of created rows.
     * @param {string} source Source of change.
     */
    _classPrivateMethodInitSpec(this, _onAfterCreateRow);
    /**
     * `afterRemoveCol` hook callback.
     *
     * @param {number} column Column index.
     * @param {number} count Number of removed columns.
     */
    _classPrivateMethodInitSpec(this, _onAfterRemoveCol);
    /**
     * `afterCreateCol` hook callback.
     *
     * @param {number} column Column index.
     * @param {number} count Number of created columns.
     */
    _classPrivateMethodInitSpec(this, _onAfterCreateCol);
    /**
     * The `modifyAutofillRange` hook callback.
     *
     * @param {Array} drag The drag area coordinates.
     * @param {Array} select The selection information.
     * @returns {Array} The new drag area.
     */
    _classPrivateMethodInitSpec(this, _onModifyAutofillRange);
    /**
     * `afterViewportColumnCalculatorOverride` hook callback.
     *
     * @param {object} calc The column calculator object.
     */
    _classPrivateMethodInitSpec(this, _onAfterViewportColumnCalculatorOverride);
    /**
     * `afterViewportRowCalculatorOverride` hook callback.
     *
     * @param {object} calc The row calculator object.
     */
    _classPrivateMethodInitSpec(this, _onAfterViewportRowCalculatorOverride);
    /**
     * The `afterGetCellMeta` hook callback.
     *
     * @param {number} row Row index.
     * @param {number} col Column index.
     * @param {object} cellProperties The cell properties object.
     */
    _classPrivateMethodInitSpec(this, _onAfterGetCellMeta);
    /**
     * `beforeSetRangeEnd` hook callback.
     * While selecting cells with keyboard or mouse, make sure that rectangular area is expanded to the extent of the
     * merged cell.
     *
     * Note: Please keep in mind that callback may modify both start and end range coordinates by the reference.
     *
     * @param {object} coords Cell coords.
     */
    _classPrivateMethodInitSpec(this, _onBeforeSetRangeEnd);
    /**
     * `beforeSetRangeStart` and `beforeSetRangeStartOnly` hook callback.
     * A selection within merge area should be rewritten to the start of merge area.
     *
     * @param {object} coords Cell coords.
     */
    _classPrivateMethodInitSpec(this, _onBeforeSetRangeStart);
    /**
     * `afterRenderer` hook callback.
     *
     * @param {HTMLElement} TD The cell to be modified.
     * @param {number} row Row index.
     * @param {number} col Visual column index.
     */
    _classPrivateMethodInitSpec(this, _onAfterRenderer);
    /**
     * `afterContextMenuDefaultOptions` hook callback.
     *
     * @param {object} defaultOptions The default context menu options.
     */
    _classPrivateMethodInitSpec(this, _addMergeActionsToContextMenu);
    /**
     * `modifyGetCellCoords` hook callback. Swaps the `getCell` coords with the merged parent coords.
     *
     * @param {number} row Row index.
     * @param {number} column Visual column index.
     * @returns {Array|undefined} Visual coordinates of the merge.
     */
    _classPrivateMethodInitSpec(this, _onModifyGetCellCoords);
    /**
     * `modifyTransformEnd` hook callback. Needed to handle "jumping over" merged merged cells, while selecting.
     *
     * @param {object} delta The transformation delta.
     */
    _classPrivateMethodInitSpec(this, _onModifyTransformEnd);
    /**
     * `modifyTransformStart` hook callback.
     *
     * @param {object} delta The transformation delta.
     */
    _classPrivateMethodInitSpec(this, _onModifyTransformStart);
    /**
     * Modifies the information on whether the current selection contains multiple cells. The `afterIsMultipleSelection`
     * hook callback.
     *
     * @param {boolean} isMultiple Determines whether the current selection contains multiple cells.
     * @returns {boolean}
     */
    _classPrivateMethodInitSpec(this, _onAfterIsMultipleSelection);
    /**
     * `afterInit` hook callback.
     */
    _classPrivateMethodInitSpec(this, _onAfterInit);
    /**
     * A container for all the merged cells.
     *
     * @private
     * @type {MergedCellsCollection}
     */
    _defineProperty(this, "mergedCellsCollection", null);
    /**
     * Instance of the class responsible for all the autofill-related calculations.
     *
     * @private
     * @type {AutofillCalculations}
     */
    _defineProperty(this, "autofillCalculations", null);
    /**
     * Instance of the class responsible for the selection-related calculations.
     *
     * @private
     * @type {SelectionCalculations}
     */
    _defineProperty(this, "selectionCalculations", null);
    /**
     * @type {CellCoords}
     */
    _classPrivateFieldInitSpec(this, _lastDesiredCoords, {
      writable: true,
      value: null
    });
  }
  static get PLUGIN_KEY() {
    return PLUGIN_KEY;
  }
  static get PLUGIN_PRIORITY() {
    return PLUGIN_PRIORITY;
  }
  /**
   * 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 MergeCells#enablePlugin} method is called.
   *
   * @returns {boolean}
   */
  isEnabled() {
    return !!this.hot.getSettings()[PLUGIN_KEY];
  }

  /**
   * Enables the plugin functionality for this Handsontable instance.
   */
  enablePlugin() {
    var _this = this;
    if (this.enabled) {
      return;
    }
    this.mergedCellsCollection = new _cellsCollection.default(this);
    this.autofillCalculations = new _autofill.default(this);
    this.selectionCalculations = new _selection.default(this);
    this.addHook('afterInit', function () {
      for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
        args[_key] = arguments[_key];
      }
      return _classPrivateMethodGet(_this, _onAfterInit, _onAfterInit2).call(_this, ...args);
    });
    this.addHook('modifyTransformStart', function () {
      for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
        args[_key2] = arguments[_key2];
      }
      return _classPrivateMethodGet(_this, _onModifyTransformStart, _onModifyTransformStart2).call(_this, ...args);
    });
    this.addHook('afterModifyTransformStart', function () {
      for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
        args[_key3] = arguments[_key3];
      }
      return _classPrivateMethodGet(_this, _onAfterModifyTransformStart, _onAfterModifyTransformStart2).call(_this, ...args);
    });
    this.addHook('modifyTransformEnd', function () {
      for (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {
        args[_key4] = arguments[_key4];
      }
      return _classPrivateMethodGet(_this, _onModifyTransformEnd, _onModifyTransformEnd2).call(_this, ...args);
    });
    this.addHook('modifyGetCellCoords', function () {
      for (var _len5 = arguments.length, args = new Array(_len5), _key5 = 0; _key5 < _len5; _key5++) {
        args[_key5] = arguments[_key5];
      }
      return _classPrivateMethodGet(_this, _onModifyGetCellCoords, _onModifyGetCellCoords2).call(_this, ...args);
    });
    this.addHook('beforeSetRangeStart', function () {
      for (var _len6 = arguments.length, args = new Array(_len6), _key6 = 0; _key6 < _len6; _key6++) {
        args[_key6] = arguments[_key6];
      }
      return _classPrivateMethodGet(_this, _onBeforeSetRangeStart, _onBeforeSetRangeStart2).call(_this, ...args);
    });
    this.addHook('beforeSetRangeStartOnly', function () {
      for (var _len7 = arguments.length, args = new Array(_len7), _key7 = 0; _key7 < _len7; _key7++) {
        args[_key7] = arguments[_key7];
      }
      return _classPrivateMethodGet(_this, _onBeforeSetRangeStart, _onBeforeSetRangeStart2).call(_this, ...args);
    });
    this.addHook('beforeSetRangeEnd', function () {
      for (var _len8 = arguments.length, args = new Array(_len8), _key8 = 0; _key8 < _len8; _key8++) {
        args[_key8] = arguments[_key8];
      }
      return _classPrivateMethodGet(_this, _onBeforeSetRangeEnd, _onBeforeSetRangeEnd2).call(_this, ...args);
    });
    this.addHook('afterIsMultipleSelection', function () {
      for (var _len9 = arguments.length, args = new Array(_len9), _key9 = 0; _key9 < _len9; _key9++) {
        args[_key9] = arguments[_key9];
      }
      return _classPrivateMethodGet(_this, _onAfterIsMultipleSelection, _onAfterIsMultipleSelection2).call(_this, ...args);
    });
    this.addHook('afterRenderer', function () {
      for (var _len10 = arguments.length, args = new Array(_len10), _key10 = 0; _key10 < _len10; _key10++) {
        args[_key10] = arguments[_key10];
      }
      return _classPrivateMethodGet(_this, _onAfterRenderer, _onAfterRenderer2).call(_this, ...args);
    });
    this.addHook('afterContextMenuDefaultOptions', function () {
      for (var _len11 = arguments.length, args = new Array(_len11), _key11 = 0; _key11 < _len11; _key11++) {
        args[_key11] = arguments[_key11];
      }
      return _classPrivateMethodGet(_this, _addMergeActionsToContextMenu, _addMergeActionsToContextMenu2).call(_this, ...args);
    });
    this.addHook('afterGetCellMeta', function () {
      for (var _len12 = arguments.length, args = new Array(_len12), _key12 = 0; _key12 < _len12; _key12++) {
        args[_key12] = arguments[_key12];
      }
      return _classPrivateMethodGet(_this, _onAfterGetCellMeta, _onAfterGetCellMeta2).call(_this, ...args);
    });
    this.addHook('afterViewportRowCalculatorOverride', function () {
      for (var _len13 = arguments.length, args = new Array(_len13), _key13 = 0; _key13 < _len13; _key13++) {
        args[_key13] = arguments[_key13];
      }
      return _classPrivateMethodGet(_this, _onAfterViewportRowCalculatorOverride, _onAfterViewportRowCalculatorOverride2).call(_this, ...args);
    });
    this.addHook('afterViewportColumnCalculatorOverride', function () {
      for (var _len14 = arguments.length, args = new Array(_len14), _key14 = 0; _key14 < _len14; _key14++) {
        args[_key14] = arguments[_key14];
      }
      return _classPrivateMethodGet(_this, _onAfterViewportColumnCalculatorOverride, _onAfterViewportColumnCalculatorOverride2).call(_this, ...args);
    });
    this.addHook('modifyAutofillRange', function () {
      for (var _len15 = arguments.length, args = new Array(_len15), _key15 = 0; _key15 < _len15; _key15++) {
        args[_key15] = arguments[_key15];
      }
      return _classPrivateMethodGet(_this, _onModifyAutofillRange, _onModifyAutofillRange2).call(_this, ...args);
    });
    this.addHook('afterCreateCol', function () {
      for (var _len16 = arguments.length, args = new Array(_len16), _key16 = 0; _key16 < _len16; _key16++) {
        args[_key16] = arguments[_key16];
      }
      return _classPrivateMethodGet(_this, _onAfterCreateCol, _onAfterCreateCol2).call(_this, ...args);
    });
    this.addHook('afterRemoveCol', function () {
      for (var _len17 = arguments.length, args = new Array(_len17), _key17 = 0; _key17 < _len17; _key17++) {
        args[_key17] = arguments[_key17];
      }
      return _classPrivateMethodGet(_this, _onAfterRemoveCol, _onAfterRemoveCol2).call(_this, ...args);
    });
    this.addHook('afterCreateRow', function () {
      for (var _len18 = arguments.length, args = new Array(_len18), _key18 = 0; _key18 < _len18; _key18++) {
        args[_key18] = arguments[_key18];
      }
      return _classPrivateMethodGet(_this, _onAfterCreateRow, _onAfterCreateRow2).call(_this, ...args);
    });
    this.addHook('afterRemoveRow', function () {
      for (var _len19 = arguments.length, args = new Array(_len19), _key19 = 0; _key19 < _len19; _key19++) {
        args[_key19] = arguments[_key19];
      }
      return _classPrivateMethodGet(_this, _onAfterRemoveRow, _onAfterRemoveRow2).call(_this, ...args);
    });
    this.addHook('afterChange', function () {
      for (var _len20 = arguments.length, args = new Array(_len20), _key20 = 0; _key20 < _len20; _key20++) {
        args[_key20] = arguments[_key20];
      }
      return _classPrivateMethodGet(_this, _onAfterChange, _onAfterChange2).call(_this, ...args);
    });
    this.addHook('beforeDrawBorders', function () {
      for (var _len21 = arguments.length, args = new Array(_len21), _key21 = 0; _key21 < _len21; _key21++) {
        args[_key21] = arguments[_key21];
      }
      return _classPrivateMethodGet(_this, _onBeforeDrawAreaBorders, _onBeforeDrawAreaBorders2).call(_this, ...args);
    });
    this.addHook('afterDrawSelection', function () {
      for (var _len22 = arguments.length, args = new Array(_len22), _key22 = 0; _key22 < _len22; _key22++) {
        args[_key22] = arguments[_key22];
      }
      return _classPrivateMethodGet(_this, _onAfterDrawSelection, _onAfterDrawSelection2).call(_this, ...args);
    });
    this.addHook('beforeRemoveCellClassNames', function () {
      for (var _len23 = arguments.length, args = new Array(_len23), _key23 = 0; _key23 < _len23; _key23++) {
        args[_key23] = arguments[_key23];
      }
      return _classPrivateMethodGet(_this, _onBeforeRemoveCellClassNames, _onBeforeRemoveCellClassNames2).call(_this, ...args);
    });
    this.addHook('beforeBeginEditing', function () {
      for (var _len24 = arguments.length, args = new Array(_len24), _key24 = 0; _key24 < _len24; _key24++) {
        args[_key24] = arguments[_key24];
      }
      return _classPrivateMethodGet(_this, _onBeforeBeginEditing, _onBeforeBeginEditing2).call(_this, ...args);
    });
    this.addHook('beforeUndoStackChange', (action, source) => {
      if (source === 'MergeCells') {
        return false;
      }
    });
    this.registerShortcuts();
    super.enablePlugin();
  }

  /**
   * Disables the plugin functionality for this Handsontable instance.
   */
  disablePlugin() {
    this.clearCollections();
    this.unregisterShortcuts();
    this.hot.render();
    super.disablePlugin();
  }

  /**
   * Updates the plugin's state.
   *
   * This method is executed when [`updateSettings()`](@/api/core.md#updatesettings) is invoked with any of the
   * following configuration options:
   *  - [`mergeCells`](@/api/options.md#mergecells)
   */
  updatePlugin() {
    const settings = this.hot.getSettings()[PLUGIN_KEY];
    this.disablePlugin();
    this.enablePlugin();
    this.generateFromSettings(settings);
    super.updatePlugin();
  }

  /**
   * If the browser is recognized as Chrome, force an additional repaint to prevent showing the effects of a Chrome bug.
   *
   * Issue described in https://github.com/handsontable/dev-handsontable/issues/521.
   *
   * @private
   */
  ifChromeForceRepaint() {
    if (!(0, _browser.isChrome)()) {
      return;
    }
    const rowsToRefresh = [];
    let rowIndexesToRefresh = [];
    this.mergedCellsCollection.mergedCells.forEach(mergedCell => {
      const {
        row,
        rowspan
      } = mergedCell;
      for (let r = row + 1; r < row + rowspan; r++) {
        rowIndexesToRefresh.push(r);
      }
    });

    // Remove duplicates
    rowIndexesToRefresh = [...new Set(rowIndexesToRefresh)];
    rowIndexesToRefresh.forEach(rowIndex => {
      const renderableRowIndex = this.hot.rowIndexMapper.getRenderableFromVisualIndex(rowIndex);
      this.hot.view._wt.wtOverlays.getOverlays(true).map(overlay => (overlay === null || overlay === void 0 ? void 0 : overlay.name) === 'master' ? overlay : overlay.clone.wtTable).forEach(wtTableRef => {
        const rowToRefresh = wtTableRef.getRow(renderableRowIndex);
        if (rowToRefresh) {
          // Modify the TR's `background` property to later modify it asynchronously.
          // The background color is getting modified only with the alpha, so the change should not be visible (and is
          // covered by the TDs' background color).
          rowToRefresh.style.background = (0, _element.getStyle)(rowToRefresh, 'backgroundColor').replace(')', ', 0.99)');
          rowsToRefresh.push(rowToRefresh);
        }
      });
    });

    // Asynchronously revert the TRs' `background` property to force a fresh repaint.
    this.hot._registerTimeout(() => {
      rowsToRefresh.forEach(rowElement => {
        rowElement.style.background = (0, _element.getStyle)(rowElement, 'backgroundColor').replace(', 0.99)', ')');
      });
    }, 1);
  }

  /**
   * Validates a single setting object, represented by a single merged cell information object.
   *
   * @private
   * @param {object} setting An object with `row`, `col`, `rowspan` and `colspan` properties.
   * @returns {boolean}
   */
  validateSetting(setting) {
    let valid = true;
    if (!setting) {
      return false;
    }
    if (_cellCoords.default.containsNegativeValues(setting)) {
      (0, _console.warn)(_cellCoords.default.NEGATIVE_VALUES_WARNING(setting));
      valid = false;
    } else if (_cellCoords.default.isOutOfBounds(setting, this.hot.countRows(), this.hot.countCols())) {
      (0, _console.warn)(_cellCoords.default.IS_OUT_OF_BOUNDS_WARNING(setting));
      valid = false;
    } else if (_cellCoords.default.isSingleCell(setting)) {
      (0, _console.warn)(_cellCoords.default.IS_SINGLE_CELL(setting));
      valid = false;
    } else if (_cellCoords.default.containsZeroSpan(setting)) {
      (0, _console.warn)(_cellCoords.default.ZERO_SPAN_WARNING(setting));
      valid = false;
    }
    return valid;
  }

  /**
   * Generates the merged cells from the settings provided to the plugin.
   *
   * @private
   * @param {Array|boolean} settings The settings provided to the plugin.
   */
  generateFromSettings(settings) {
    if (Array.isArray(settings)) {
      const populatedNulls = [];
      (0, _array.arrayEach)(settings, setting => {
        if (!this.validateSetting(setting)) {
          return;
        }
        const highlight = this.hot._createCellCoords(setting.row, setting.col);
        const rangeEnd = this.hot._createCellCoords(setting.row + setting.rowspan - 1, setting.col + setting.colspan - 1);
        const mergeRange = this.hot._createCellRange(highlight, highlight, rangeEnd);

        // Merging without data population.
        this.mergeRange(mergeRange, true, true);
        (0, _number.rangeEach)(setting.row, setting.row + setting.rowspan - 1, rowIndex => {
          (0, _number.rangeEach)(setting.col, setting.col + setting.colspan - 1, columnIndex => {
            // Not resetting a cell representing a merge area's value.
            if ((rowIndex === setting.row && columnIndex === setting.col) === false) {
              populatedNulls.push([rowIndex, columnIndex, null]);
            }
          });
        });
      });

      // There are no merged cells. Thus, no data population is needed.
      if (populatedNulls.length === 0) {
        return;
      }
      this.hot.setDataAtCell(populatedNulls);
    }
  }

  /**
   * Clears the merged cells from the merged cell container.
   */
  clearCollections() {
    this.mergedCellsCollection.clear();
  }

  /**
   * Returns `true` if a range is mergeable.
   *
   * @private
   * @param {object} newMergedCellInfo Merged cell information object to test.
   * @param {boolean} [auto=false] `true` if triggered at initialization.
   * @returns {boolean}
   */
  canMergeRange(newMergedCellInfo) {
    let auto = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
    return auto ? true : this.validateSetting(newMergedCellInfo);
  }

  /**
   * Merge or unmerge, based on last selected range.
   *
   * @private
   */
  toggleMergeOnSelection() {
    const currentRange = this.hot.getSelectedRangeLast();
    if (!currentRange) {
      return;
    }
    currentRange.setDirection(this.hot.isRtl() ? 'NE-SW' : 'NW-SE');
    const {
      from,
      to
    } = currentRange;
    this.toggleMerge(currentRange);
    this.hot.selectCell(from.row, from.col, to.row, to.col, false);
  }

  /**
   * Merges the selection provided as a cell range.
   *
   * @param {CellRange} [cellRange] Selection cell range.
   */
  mergeSelection() {
    let cellRange = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : this.hot.getSelectedRangeLast();
    if (!cellRange) {
      return;
    }
    cellRange.setDirection(this.hot.isRtl() ? 'NE-SW' : 'NW-SE');
    const {
      from,
      to
    } = cellRange;
    this.unmergeRange(cellRange, true);
    this.mergeRange(cellRange);
    this.hot.selectCell(from.row, from.col, to.row, to.col, false);
  }

  /**
   * Unmerges the selection provided as a cell range.
   *
   * @param {CellRange} [cellRange] Selection cell range.
   */
  unmergeSelection() {
    let cellRange = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : this.hot.getSelectedRangeLast();
    if (!cellRange) {
      return;
    }
    const {
      from,
      to
    } = cellRange;
    this.unmergeRange(cellRange, true);
    this.hot.selectCell(from.row, from.col, to.row, to.col, false);
  }

  /**
   * Merges cells in the provided cell range.
   *
   * @private
   * @param {CellRange} cellRange Cell range to merge.
   * @param {boolean} [auto=false] `true` if is called automatically, e.g. At initialization.
   * @param {boolean} [preventPopulation=false] `true`, if the method should not run `populateFromArray` at the end,
   *   but rather return its arguments.
   * @returns {Array|boolean} Returns an array of [row, column, dataUnderCollection] if preventPopulation is set to
   *   true. If the the merging process went successful, it returns `true`, otherwise - `false`.
   * @fires Hooks#beforeMergeCells
   * @fires Hooks#afterMergeCells
   */
  mergeRange(cellRange) {
    let auto = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
    let preventPopulation = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
    const topStart = cellRange.getTopStartCorner();
    const bottomEnd = cellRange.getBottomEndCorner();
    const mergeParent = {
      row: topStart.row,
      col: topStart.col,
      rowspan: bottomEnd.row - topStart.row + 1,
      colspan: bottomEnd.col - topStart.col + 1
    };
    const clearedData = [];
    let populationInfo = null;
    if (!this.canMergeRange(mergeParent, auto)) {
      return false;
    }
    this.hot.runHooks('beforeMergeCells', cellRange, auto);
    (0, _number.rangeEach)(0, mergeParent.rowspan - 1, i => {
      (0, _number.rangeEach)(0, mergeParent.colspan - 1, j => {
        let clearedValue = null;
        if (!clearedData[i]) {
          clearedData[i] = [];
        }
        if (i === 0 && j === 0) {
          clearedValue = this.hot.getSourceDataAtCell(this.hot.toPhysicalRow(mergeParent.row), this.hot.toPhysicalColumn(mergeParent.col));
        } else {
          this.hot.setCellMeta(mergeParent.row + i, mergeParent.col + j, 'hidden', true);
        }
        clearedData[i][j] = clearedValue;
      });
    });
    this.hot.setCellMeta(mergeParent.row, mergeParent.col, 'spanned', true);
    const mergedCellAdded = this.mergedCellsCollection.add(mergeParent);
    if (mergedCellAdded) {
      if (preventPopulation) {
        populationInfo = [mergeParent.row, mergeParent.col, clearedData];
      } else {
        this.hot.populateFromArray(mergeParent.row, mergeParent.col, clearedData, undefined, undefined, this.pluginName);
      }
      if (!auto) {
        this.ifChromeForceRepaint();
      }
      this.hot.runHooks('afterMergeCells', cellRange, mergeParent, auto);
      return populationInfo;
    }
    return true;
  }

  /**
   * Unmerges the selection provided as a cell range. If no cell range is provided, it uses the current selection.
   *
   * @private
   * @param {CellRange} cellRange Selection cell range.
   * @param {boolean} [auto=false] `true` if called automatically by the plugin.
   *
   * @fires Hooks#beforeUnmergeCells
   * @fires Hooks#afterUnmergeCells
   */
  unmergeRange(cellRange) {
    let auto = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
    const mergedCells = this.mergedCellsCollection.getWithinRange(cellRange);
    if (!mergedCells) {
      return;
    }
    this.hot.runHooks('beforeUnmergeCells', cellRange, auto);
    (0, _array.arrayEach)(mergedCells, currentCollection => {
      this.mergedCellsCollection.remove(currentCollection.row, currentCollection.col);
      (0, _number.rangeEach)(0, currentCollection.rowspan - 1, i => {
        (0, _number.rangeEach)(0, currentCollection.colspan - 1, j => {
          this.hot.removeCellMeta(currentCollection.row + i, currentCollection.col + j, 'hidden');
          this.hot.removeCellMeta(currentCollection.row + i, currentCollection.col + j, 'copyable');
        });
      });
      this.hot.removeCellMeta(currentCollection.row, currentCollection.col, 'spanned');
    });
    this.hot.runHooks('afterUnmergeCells', cellRange, auto);
    this.hot.render();
  }

  /**
   * Merges or unmerges, based on the cell range provided as `cellRange`.
   *
   * @private
   * @param {CellRange} cellRange The cell range to merge or unmerged.
   */
  toggleMerge(cellRange) {
    const mergedCell = this.mergedCellsCollection.get(cellRange.from.row, cellRange.from.col);
    const mergedCellCoversWholeRange = mergedCell.row === cellRange.from.row && mergedCell.col === cellRange.from.col && mergedCell.row + mergedCell.rowspan - 1 === cellRange.to.row && mergedCell.col + mergedCell.colspan - 1 === cellRange.to.col;
    if (mergedCellCoversWholeRange) {
      this.unmergeRange(cellRange);
    } else {
      this.mergeSelection(cellRange);
    }
  }

  /**
   * Merges the specified range.
   *
   * @param {number} startRow Start row of the merged cell.
   * @param {number} startColumn Start column of the merged cell.
   * @param {number} endRow End row of the merged cell.
   * @param {number} endColumn End column of the merged cell.
   * @fires Hooks#beforeMergeCells
   * @fires Hooks#afterMergeCells
   */
  merge(startRow, startColumn, endRow, endColumn) {
    const start = this.hot._createCellCoords(startRow, startColumn);
    const end = this.hot._createCellCoords(endRow, endColumn);
    this.mergeRange(this.hot._createCellRange(start, start, end));
  }

  /**
   * Unmerges the merged cell in the provided range.
   *
   * @param {number} startRow Start row of the merged cell.
   * @param {number} startColumn Start column of the merged cell.
   * @param {number} endRow End row of the merged cell.
   * @param {number} endColumn End column of the merged cell.
   * @fires Hooks#beforeUnmergeCells
   * @fires Hooks#afterUnmergeCells
   */
  unmerge(startRow, startColumn, endRow, endColumn) {
    const start = this.hot._createCellCoords(startRow, startColumn);
    const end = this.hot._createCellCoords(endRow, endColumn);
    this.unmergeRange(this.hot._createCellRange(start, start, end));
  }
  /**
   * Register shortcuts responsible for toggling a merge.
   *
   * @private
   */
  registerShortcuts() {
    const shortcutManager = this.hot.getShortcutManager();
    const gridContext = shortcutManager.getContext('grid');
    gridContext.addShortcut({
      keys: [['Control', 'm']],
      callback: () => {
        const range = this.hot.getSelectedRangeLast();
        if (range && !range.isSingleHeader()) {
          this.toggleMerge(range);
          this.hot.render();
        }
      },
      runOnlyIf: event => !event.altKey,
      // right ALT in some systems triggers ALT+CTRL
      group: SHORTCUTS_GROUP
    });
  }

  /**
   * Unregister shortcuts responsible for toggling a merge.
   *
   * @private
   */
  unregisterShortcuts() {
    const shortcutManager = this.hot.getShortcutManager();
    const gridContext = shortcutManager.getContext('grid');
    gridContext.removeShortcutsByGroup(SHORTCUTS_GROUP);
  }
  /**
   * Modify viewport start when needed. We extend viewport when merged cells aren't fully visible.
   *
   * @private
   * @param {object} calc The row calculator object.
   * @param {number} nrOfColumns Number of visual columns.
   */
  modifyViewportRowStart(calc, nrOfColumns) {
    const rowMapper = this.hot.rowIndexMapper;
    const visualStartRow = rowMapper.getVisualFromRenderableIndex(calc.startRow);
    for (let visualColumnIndex = 0; visualColumnIndex < nrOfColumns; visualColumnIndex += 1) {
      const mergeParentForViewportStart = this.mergedCellsCollection.get(visualStartRow, visualColumnIndex);
      if ((0, _object.isObject)(mergeParentForViewportStart)) {
        const renderableIndexAtMergeStart = rowMapper.getRenderableFromVisualIndex(rowMapper.getNearestNotHiddenIndex(mergeParentForViewportStart.row, 1));

        // Merge start is out of the viewport (i.e. when we scrolled to the bottom and we can see just part of a merge).
        if (renderableIndexAtMergeStart < calc.startRow) {
          // We extend viewport when some rows have been merged.
          calc.startRow = renderableIndexAtMergeStart;
          // We are looking for next merges inside already extended viewport (starting again from row equal to 0).
          this.modifyViewportRowStart(calc, nrOfColumns); // recursively search upwards

          return; // Finish the current loop. Everything will be checked from the beginning by above recursion.
        }
      }
    }
  }

  /**
   *  Modify viewport end when needed. We extend viewport when merged cells aren't fully visible.
   *
   * @private
   * @param {object} calc The row calculator object.
   * @param {number} nrOfColumns Number of visual columns.
   */
  modifyViewportRowEnd(calc, nrOfColumns) {
    const rowMapper = this.hot.rowIndexMapper;
    const visualEndRow = rowMapper.getVisualFromRenderableIndex(calc.endRow);
    for (let visualColumnIndex = 0; visualColumnIndex < nrOfColumns; visualColumnIndex += 1) {
      const mergeParentForViewportEnd = this.mergedCellsCollection.get(visualEndRow, visualColumnIndex);
      if ((0, _object.isObject)(mergeParentForViewportEnd)) {
        const mergeEnd = mergeParentForViewportEnd.row + mergeParentForViewportEnd.rowspan - 1;
        const renderableIndexAtMergeEnd = rowMapper.getRenderableFromVisualIndex(rowMapper.getNearestNotHiddenIndex(mergeEnd, -1));

        // Merge end is out of the viewport.
        if (renderableIndexAtMergeEnd > calc.endRow) {
          // We extend the viewport when some rows have been merged.
          calc.endRow = renderableIndexAtMergeEnd;
          // We are looking for next merges inside already extended viewport (starting again from row equal to 0).
          this.modifyViewportRowEnd(calc, nrOfColumns); // recursively search upwards

          return; // Finish the current loop. Everything will be checked from the beginning by above recursion.
        }
      }
    }
  }
  /**
   * Modify viewport start when needed. We extend viewport when merged cells aren't fully visible.
   *
   * @private
   * @param {object} calc The column calculator object.
   * @param {number} nrOfRows Number of visual rows.
   */
  modifyViewportColumnStart(calc, nrOfRows) {
    const columnMapper = this.hot.columnIndexMapper;
    const visualStartCol = columnMapper.getVisualFromRenderableIndex(calc.startColumn);
    for (let visualRowIndex = 0; visualRowIndex < nrOfRows; visualRowIndex += 1) {
      const mergeParentForViewportStart = this.mergedCellsCollection.get(visualRowIndex, visualStartCol);
      if ((0, _object.isObject)(mergeParentForViewportStart)) {
        const renderableIndexAtMergeStart = columnMapper.getRenderableFromVisualIndex(columnMapper.getNearestNotHiddenIndex(mergeParentForViewportStart.col, 1));

        // Merge start is out of the viewport (i.e. when we scrolled to the right and we can see just part of a merge).
        if (renderableIndexAtMergeStart < calc.startColumn) {
          // We extend viewport when some columns have been merged.
          calc.startColumn = renderableIndexAtMergeStart;
          // We are looking for next merges inside already extended viewport (starting again from column equal to 0).
          this.modifyViewportColumnStart(calc, nrOfRows); // recursively search upwards

          return; // Finish the current loop. Everything will be checked from the beginning by above recursion.
        }
      }
    }
  }

  /**
   *  Modify viewport end when needed. We extend viewport when merged cells aren't fully visible.
   *
   * @private
   * @param {object} calc The column calculator object.
   * @param {number} nrOfRows Number of visual rows.
   */
  modifyViewportColumnEnd(calc, nrOfRows) {
    const columnMapper = this.hot.columnIndexMapper;
    const visualEndCol = columnMapper.getVisualFromRenderableIndex(calc.endColumn);
    for (let visualRowIndex = 0; visualRowIndex < nrOfRows; visualRowIndex += 1) {
      const mergeParentForViewportEnd = this.mergedCellsCollection.get(visualRowIndex, visualEndCol);
      if ((0, _object.isObject)(mergeParentForViewportEnd)) {
        const mergeEnd = mergeParentForViewportEnd.col + mergeParentForViewportEnd.colspan - 1;
        const renderableIndexAtMergeEnd = columnMapper.getRenderableFromVisualIndex(columnMapper.getNearestNotHiddenIndex(mergeEnd, -1));

        // Merge end is out of the viewport.
        if (renderableIndexAtMergeEnd > calc.endColumn) {
          // We extend the viewport when some columns have been merged.
          calc.endColumn = renderableIndexAtMergeEnd;
          // We are looking for next merges inside already extended viewport (starting again from column equal to 0).
          this.modifyViewportColumnEnd(calc, nrOfRows); // recursively search upwards

          return; // Finish the current loop. Everything will be checked from the beginning by above recursion.
        }
      }
    }
  }

  /**
   * Translates merged cell coordinates to renderable indexes.
   *
   * @private
   * @param {number} parentRow Visual row index.
   * @param {number} rowspan Rowspan which describes shift which will be applied to parent row
   *                         to calculate renderable index which points to the most bottom
   *                         index position. Pass rowspan as `0` to calculate the most top
   *                         index position.
   * @param {number} parentColumn Visual column index.
   * @param {number} colspan Colspan which describes shift which will be applied to parent column
   *                         to calculate renderable index which points to the most right
   *                         index position. Pass colspan as `0` to calculate the most left
   *                         index position.
   * @returns {number[]}
   */
  translateMergedCellToRenderable(parentRow, rowspan, parentColumn, colspan) {
    const {
      rowIndexMapper: rowMapper,
      columnIndexMapper: columnMapper
    } = this.hot;
    let firstNonHiddenRow;
    let firstNonHiddenColumn;
    if (rowspan === 0) {
      firstNonHiddenRow = rowMapper.getNearestNotHiddenIndex(parentRow, 1);
    } else {
      firstNonHiddenRow = rowMapper.getNearestNotHiddenIndex(parentRow + rowspan - 1, -1);
    }
    if (colspan === 0) {
      firstNonHiddenColumn = columnMapper.getNearestNotHiddenIndex(parentColumn, 1);
    } else {
      firstNonHiddenColumn = columnMapper.getNearestNotHiddenIndex(parentColumn + colspan - 1, -1);
    }
    const renderableRow = parentRow >= 0 ? rowMapper.getRenderableFromVisualIndex(firstNonHiddenRow) : parentRow;
    const renderableColumn = parentColumn >= 0 ? columnMapper.getRenderableFromVisualIndex(firstNonHiddenColumn) : parentColumn;
    return [renderableRow, renderableColumn];
  }
}
exports.MergeCells = MergeCells;
function _onAfterInit2() {
  this.generateFromSettings(this.hot.getSettings()[PLUGIN_KEY]);
  this.hot.render();
}
function _onAfterIsMultipleSelection2(isMultiple) {
  if (isMultiple) {
    const mergedCells = this.mergedCellsCollection.mergedCells;
    const selectionRange = this.hot.getSelectedRangeLast();
    for (let group = 0; group < mergedCells.length; group += 1) {
      if (selectionRange.from.row === mergedCells[group].row && selectionRange.from.col === mergedCells[group].col && selectionRange.to.row === mergedCells[group].row + mergedCells[group].rowspan - 1 && selectionRange.to.col === mergedCells[group].col + mergedCells[group].colspan - 1) {
        return false;
      }
    }
  }
  return isMultiple;
}
function _onModifyTransformStart2(delta) {
  const currentlySelectedRange = this.hot.getSelectedRangeLast();
  let newDelta = {
    row: delta.row,
    col: delta.col
  };
  let nextPosition = null;
  const currentPosition = this.hot._createCellCoords(currentlySelectedRange.highlight.row, currentlySelectedRange.highlight.col);
  const mergedParent = this.mergedCellsCollection.get(currentPosition.row, currentPosition.col);
  if (!_classPrivateFieldGet(this, _lastDesiredCoords)) {
    _classPrivateFieldSet(this, _lastDesiredCoords, this.hot._createCellCoords(null, null));
  }
  if (mergedParent) {
    // only merge selected
    const mergeTopLeft = this.hot._createCellCoords(mergedParent.row, mergedParent.col);
    const mergeBottomRight = this.hot._createCellCoords(mergedParent.row + mergedParent.rowspan - 1, mergedParent.col + mergedParent.colspan - 1);
    const mergeRange = this.hot._createCellRange(mergeTopLeft, mergeTopLeft, mergeBottomRight);
    if (!mergeRange.includes(_classPrivateFieldGet(this, _lastDesiredCoords))) {
      _classPrivateFieldSet(this, _lastDesiredCoords, this.hot._createCellCoords(null, null)); // reset outdated version of lastDesiredCoords
    }
    newDelta.row = _classPrivateFieldGet(this, _lastDesiredCoords).row ? _classPrivateFieldGet(this, _lastDesiredCoords).row - currentPosition.row : newDelta.row;
    newDelta.col = _classPrivateFieldGet(this, _lastDesiredCoords).col ? _classPrivateFieldGet(this, _lastDesiredCoords).col - currentPosition.col : newDelta.col;
    if (delta.row > 0) {
      // moving down
      newDelta.row = mergedParent.row + mergedParent.rowspan - 1 - currentPosition.row + delta.row;
    } else if (delta.row < 0) {
      // moving up
      newDelta.row = currentPosition.row - mergedParent.row + delta.row;
    }
    if (delta.col > 0) {
      // moving right
      newDelta.col = mergedParent.col + mergedParent.colspan - 1 - currentPosition.col + delta.col;
    } else if (delta.col < 0) {
      // moving left
      newDelta.col = currentPosition.col - mergedParent.col + delta.col;
    }
  }
  nextPosition = this.hot._createCellCoords(currentlySelectedRange.highlight.row + newDelta.row, currentlySelectedRange.highlight.col + newDelta.col);
  const nextPositionMergedCell = this.mergedCellsCollection.get(nextPosition.row, nextPosition.col);
  if (nextPositionMergedCell) {
    // skipping the invisible cells in the merge range
    const firstRenderableCoords = this.mergedCellsCollection.getFirstRenderableCoords(nextPositionMergedCell.row, nextPositionMergedCell.col);
    _classPrivateFieldSet(this, _lastDesiredCoords, nextPosition);
    newDelta = {
      row: firstRenderableCoords.row - currentPosition.row,
      col: firstRenderableCoords.col - currentPosition.col
    };
  }
  if (newDelta.row !== 0) {
    delta.row = newDelta.row;
  }
  if (newDelta.col !== 0) {
    delta.col = newDelta.col;
  }
}
function _onModifyTransformEnd2(delta) {
  const currentSelectionRange = this.hot.getSelectedRangeLast();
  const newDelta = (0, _object.clone)(delta);
  const newSelectionRange = this.selectionCalculations.getUpdatedSelectionRange(currentSelectionRange, delta);
  let tempDelta = (0, _object.clone)(newDelta);
  const mergedCellsWithinRange = this.mergedCellsCollection.getWithinRange(newSelectionRange, true);
  do {
    tempDelta = (0, _object.clone)(newDelta);
    this.selectionCalculations.getUpdatedSelectionRange(currentSelectionRange, newDelta);
    (0, _array.arrayEach)(mergedCellsWithinRange, mergedCell => {
      this.selectionCalculations.snapDelta(newDelta, currentSelectionRange, mergedCell);
    });
  } while (newDelta.row !== tempDelta.row || newDelta.col !== tempDelta.col);
  delta.row = newDelta.row;
  delta.col = newDelta.col;
}
function _onModifyGetCellCoords2(row, column) {
  if (row < 0 || column < 0) {
    return;
  }
  const mergeParent = this.mergedCellsCollection.get(row, column);
  if (!mergeParent) {
    return;
  }
  const {
    row: mergeRow,
    col: mergeColumn,
    colspan,
    rowspan
  } = mergeParent;
  return [
  // Most top-left merged cell coords.
  mergeRow, mergeColumn,
  // Most bottom-right merged cell coords.
  mergeRow + rowspan - 1, mergeColumn + colspan - 1];
}
function _addMergeActionsToContextMenu2(defaultOptions) {
  defaultOptions.items.push({
    name: '---------'
  }, (0, _toggleMerge.default)(this));
}
function _onAfterRenderer2(TD, row, col) {
  const mergedCell = this.mergedCellsCollection.get(row, col);
  // We shouldn't override data in the collection.
  const mergedCellCopy = (0, _object.isObject)(mergedCell) ? (0, _object.clone)(mergedCell) : undefined;
  if ((0, _object.isObject)(mergedCellCopy)) {
    const {
      rowIndexMapper: rowMapper,
      columnIndexMapper: columnMapper
    } = this.hot;
    const {
      row: mergeRow,
      col: mergeColumn,
      colspan,
      rowspan
    } = mergedCellCopy;
    const [lastMergedRowIndex, lastMergedColumnIndex] = this.translateMergedCellToRenderable(mergeRow, rowspan, mergeColumn, colspan);
    const renderedRowIndex = rowMapper.getRenderableFromVisualIndex(row);
    const renderedColumnIndex = columnMapper.getRenderableFromVisualIndex(col);
    const maxRowSpan = lastMergedRowIndex - renderedRowIndex + 1; // Number of rendered columns.
    const maxColSpan = lastMergedColumnIndex - renderedColumnIndex + 1; // Number of rendered columns.

    // We just try to determine some values basing on the actual number of rendered indexes (some columns may be hidden).
    mergedCellCopy.row = rowMapper.getNearestNotHiddenIndex(mergedCellCopy.row, 1);
    // We just try to determine some values basing on the actual number of rendered indexes (some columns may be hidden).
    mergedCellCopy.col = columnMapper.getNearestNotHiddenIndex(mergedCellCopy.col, 1);
    // The `rowSpan` property for a `TD` element should be at most equal to number of rendered rows in the merge area.
    mergedCellCopy.rowspan = Math.min(mergedCellCopy.rowspan, maxRowSpan);
    // The `colSpan` property for a `TD` element should be at most equal to number of rendered columns in the merge area.
    mergedCellCopy.colspan = Math.min(mergedCellCopy.colspan, maxColSpan);
  }
  (0, _utils.applySpanProperties)(TD, mergedCellCopy, row, col);
}
function _onBeforeSetRangeStart2(coords) {
  // TODO: It is a workaround, but probably this hook may be needed. Every selection on the merge area
  // could set start point of the selection to the start of the merge area. However, logic inside `expandByRange` need
  // an initial start point. Click on the merge cell when there are some hidden indexes break the logic in some cases.
  // Please take a look at #7010 for more information. I'm not sure if selection directions are calculated properly
  // and what was idea for flipping direction inside `expandByRange` method.
  if (this.mergedCellsCollection.isFirstRenderableMergedCell(coords.row, coords.col)) {
    const mergeParent = this.mergedCellsCollection.get(coords.row, coords.col);
    [coords.row, coords.col] = [mergeParent.row, mergeParent.col];
  }
}
function _onBeforeSetRangeEnd2(coords) {
  const selRange = this.hot.getSelectedRangeLast();
  selRange.highlight = this.hot._createCellCoords(selRange.highlight.row, selRange.highlight.col); // clone in case we will modify its reference
  selRange.to = coords;
  let rangeExpanded = false;
  if (this.hot.selection.isSelectedByColumnHeader() || this.hot.selection.isSelectedByRowHeader()) {
    return;
  }
  do {
    rangeExpanded = false;
    for (let i = 0; i < this.mergedCellsCollection.mergedCells.length; i += 1) {
      const cellInfo = this.mergedCellsCollection.mergedCells[i];
      const mergedCellRange = cellInfo.getRange();
      if (selRange.expandByRange(mergedCellRange)) {
        coords.row = selRange.to.row;
        coords.col = selRange.to.col;
        rangeExpanded = true;
      }
    }
  } while (rangeExpanded);
}
function _onAfterGetCellMeta2(row, col, cellProperties) {
  const mergeParent = this.mergedCellsCollection.get(row, col);
  if (mergeParent) {
    if (mergeParent.row !== row || mergeParent.col !== col) {
      cellProperties.copyable = false;
    } else {
      cellProperties.rowspan = mergeParent.rowspan;
      cellProperties.colspan = mergeParent.colspan;
    }
  }
}
function _onAfterViewportRowCalculatorOverride2(calc) {
  const nrOfColumns = this.hot.countCols();
  this.modifyViewportRowStart(calc, nrOfColumns);
  this.modifyViewportRowEnd(calc, nrOfColumns);
}
function _onAfterViewportColumnCalculatorOverride2(calc) {
  const nrOfRows = this.hot.countRows();
  this.modifyViewportColumnStart(calc, nrOfRows);
  this.modifyViewportColumnEnd(calc, nrOfRows);
}
function _onModifyAutofillRange2(drag, select) {
  this.autofillCalculations.correctSelectionAreaSize(select);
  const dragDirection = this.autofillCalculations.getDirection(select, drag);
  let dragArea = drag;
  if (this.autofillCalculations.dragAreaOverlapsCollections(select, dragArea, dragDirection)) {
    dragArea = select;
    return dragArea;
  }
  const mergedCellsWithinSelectionArea = this.mergedCellsCollection.getWithinRange({
    from: {
      row: select[0],
      col: select[1]
    },
    to: {
      row: select[2],
      col: select[3]
    }
  });
  if (!mergedCellsWithinSelectionArea) {
    return dragArea;
  }
  dragArea = this.autofillCalculations.snapDragArea(select, dragArea, dragDirection, mergedCellsWithinSelectionArea);
  return dragArea;
}
function _onAfterCreateCol2(column, count) {
  this.mergedCellsCollection.shiftCollections('right', column, count);
}
function _onAfterRemoveCol2(column, count) {
  this.mergedCellsCollection.shiftCollections('left', column, count);
}
function _onAfterCreateRow2(row, count, source) {
  if (source === 'auto') {
    return;
  }
  this.mergedCellsCollection.shiftCollections('down', row, count);
}
function _onAfterRemoveRow2(row, count) {
  this.mergedCellsCollection.shiftCollections('up', row, count);
}
function _onAfterChange2(changes, source) {
  if (source !== 'Autofill.fill') {
    return;
  }
  this.autofillCalculations.recreateAfterDataPopulation(changes);
}
function _onBeforeDrawAreaBorders2(corners, className) {
  if (className && className === 'area') {
    const selectedRange = this.hot.getSelectedRangeLast();
    const mergedCellsWithinRange = this.mergedCellsCollection.getWithinRange(selectedRange);
    (0, _array.arrayEach)(mergedCellsWithinRange, mergedCell => {
      if (selectedRange.getBottomEndCorner().row === mergedCell.getLastRow() && selectedRange.getBottomEndCorner().col === mergedCell.getLastColumn()) {
        corners[2] = mergedCell.row;
        corners[3] = mergedCell.col;
      }
    });
  }
}
function _onAfterModifyTransformStart2(coords, rowTransformDir, colTransformDir) {
  if (!this.enabled) {
    return;
  }
  const mergedCellAtCoords = this.mergedCellsCollection.get(coords.row, coords.col);
  if (!mergedCellAtCoords) {
    return;
  }
  const goingDown = rowTransformDir > 0;
  const goingUp = rowTransformDir < 0;
  const goingLeft = colTransformDir < 0;
  const goingRight = colTransformDir > 0;
  const mergedCellOnBottomEdge = mergedCellAtCoords.row + mergedCellAtCoords.rowspan - 1 === this.hot.countRows() - 1;
  const mergedCellOnTopEdge = mergedCellAtCoords.row === 0;
  const mergedCellOnRightEdge = mergedCellAtCoords.col + mergedCellAtCoords.colspan - 1 === this.hot.countCols() - 1;
  const mergedCellOnLeftEdge = mergedCellAtCoords.col === 0;
  if (goingDown && mergedCellOnBottomEdge || goingUp && mergedCellOnTopEdge || goingRight && mergedCellOnRightEdge || goingLeft && mergedCellOnLeftEdge) {
    coords.row = mergedCellAtCoords.row;
    coords.col = mergedCellAtCoords.col;
  }
}
function _onAfterDrawSelection2(currentRow, currentColumn, cornersOfSelection, layerLevel) {
  // Nothing's selected (hook might be triggered by the custom borders)
  if (!cornersOfSelection) {
    return;
  }
  return this.selectionCalculations.getSelectedMergedCellClassName(currentRow, currentColumn, cornersOfSelection, layerLevel);
}
function _onBeforeRemoveCellClassNames2() {
  return this.selectionCalculations.getSelectedMergedCellClassNameToRemove();
}
function _onBeforeBeginEditing2(row, column, initialValue, event) {
  if (!(event instanceof MouseEvent)) {
    return;
  }
  const selection = this.hot.getSelectedRangeLast();
  const mergeCell = this.mergedCellsCollection.getByRange(selection);
  if (!mergeCell) {
    return;
  }
  const from = this.hot._createCellCoords(mergeCell.row, mergeCell.col);
  const to = this.hot._createCellCoords(mergeCell.row + mergeCell.rowspan - 1, mergeCell.col + mergeCell.colspan - 1);
  return this.hot.selection.getLayerLevel() === 0 && selection.isEqual(this.hot._createCellRange(from, from, to));
}