"use strict";

function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); }
require("core-js/modules/es.object.to-string.js");
require("core-js/modules/es.reflect.construct.js");
require("core-js/modules/es.reflect.get.js");
require("core-js/modules/es.object.get-own-property-descriptor.js");
require("core-js/modules/es.symbol.to-primitive.js");
require("core-js/modules/es.date.to-primitive.js");
require("core-js/modules/es.symbol.js");
require("core-js/modules/es.symbol.description.js");
require("core-js/modules/es.number.constructor.js");
require("core-js/modules/es.symbol.iterator.js");
require("core-js/modules/es.array.iterator.js");
require("core-js/modules/es.string.iterator.js");
require("core-js/modules/web.dom-collections.iterator.js");
exports.__esModule = true;
exports.PLUGIN_PRIORITY = exports.PLUGIN_KEY = exports.DropdownMenu = void 0;
require("core-js/modules/es.array.concat.js");
require("core-js/modules/es.array.index-of.js");
require("core-js/modules/es.object.set-prototype-of.js");
require("core-js/modules/es.object.get-prototype-of.js");
var _base = require("../base");
var _array = require("../../helpers/array");
var _object = require("../../helpers/object");
var _commandExecutor = _interopRequireDefault(require("../contextMenu/commandExecutor"));
var _utils = require("../contextMenu/utils");
var _eventManager = _interopRequireDefault(require("../../eventManager"));
var _element = require("../../helpers/dom/element");
var _itemsFactory = _interopRequireDefault(require("../contextMenu/itemsFactory"));
var _menu = _interopRequireDefault(require("../contextMenu/menu"));
var _pluginHooks = _interopRequireDefault(require("../../pluginHooks"));
var _predefinedItems = require("../contextMenu/predefinedItems");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
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 _get() { if (typeof Reflect !== "undefined" && Reflect.get) { _get = Reflect.get.bind(); } else { _get = function _get(target, property, receiver) { var base = _superPropBase(target, property); if (!base) return; var desc = Object.getOwnPropertyDescriptor(base, property); if (desc.get) { return desc.get.call(arguments.length < 3 ? target : receiver); } return desc.value; }; } return _get.apply(this, arguments); }
function _superPropBase(object, property) { while (!Object.prototype.hasOwnProperty.call(object, property)) { object = _getPrototypeOf(object); if (object === null) break; } return object; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, "prototype", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); }
function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); }
function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
_pluginHooks.default.getSingleton().register('afterDropdownMenuDefaultOptions');
_pluginHooks.default.getSingleton().register('beforeDropdownMenuShow');
_pluginHooks.default.getSingleton().register('afterDropdownMenuShow');
_pluginHooks.default.getSingleton().register('afterDropdownMenuHide');
_pluginHooks.default.getSingleton().register('afterDropdownMenuExecute');
var PLUGIN_KEY = 'dropdownMenu';
exports.PLUGIN_KEY = PLUGIN_KEY;
var PLUGIN_PRIORITY = 230;
exports.PLUGIN_PRIORITY = PLUGIN_PRIORITY;
var BUTTON_CLASS_NAME = 'changeType';
var SHORTCUTS_GROUP = PLUGIN_KEY;

/* eslint-disable jsdoc/require-description-complete-sentence */
/**
 * @plugin DropdownMenu
 * @class DropdownMenu
 *
 * @description
 * This plugin creates the Handsontable Dropdown Menu. It allows to create a new row or column at any place in the grid
 * among [other features](@/guides/accessories-and-menus/context-menu.md#context-menu-with-specific-options).
 * Possible values:
 * * `true` (to enable default options),
 * * `false` (to disable completely).
 *
 * or array of any available strings:
 * * `["row_above", "row_below", "col_left", "col_right",
 * "remove_row", "remove_col", "---------", "undo", "redo"]`.
 *
 * See [the dropdown menu demo](@/guides/columns/column-menu.md) for examples.
 *
 * @example
 * ::: only-for javascript
 * ```js
 * const container = document.getElementById('example');
 * const hot = new Handsontable(container, {
 *   data: data,
 *   colHeaders: true,
 *   // enable dropdown menu
 *   dropdownMenu: true
 * });
 *
 * // or
 * const hot = new Handsontable(container, {
 *   data: data,
 *   colHeaders: true,
 *   // enable and configure dropdown menu
 *   dropdownMenu: ['remove_col', '---------', 'make_read_only', 'alignment']
 * });
 * ```
 * :::
 *
 * ::: only-for react
 * ```jsx
 * <HotTable
 *   data={data}
 *   comments={true}
 *   // enable and configure dropdown menu
 *   dropdownMenu={['remove_col', '---------', 'make_read_only', 'alignment']}
 * />
 * ```
 * :::
 */
var DropdownMenu = /*#__PURE__*/function (_BasePlugin) {
  _inherits(DropdownMenu, _BasePlugin);
  var _super = _createSuper(DropdownMenu);
  function DropdownMenu(hotInstance) {
    var _this;
    _classCallCheck(this, DropdownMenu);
    _this = _super.call(this, hotInstance);
    /**
     * Instance of {@link EventManager}.
     *
     * @private
     * @type {EventManager}
     */
    _this.eventManager = new _eventManager.default(_assertThisInitialized(_this));
    /**
     * Instance of {@link CommandExecutor}.
     *
     * @private
     * @type {CommandExecutor}
     */
    _this.commandExecutor = new _commandExecutor.default(_this.hot);
    /**
     * Instance of {@link ItemsFactory}.
     *
     * @private
     * @type {ItemsFactory}
     */
    _this.itemsFactory = null;
    /**
     * Instance of {@link Menu}.
     *
     * @private
     * @type {Menu}
     */
    _this.menu = null;

    // One listener for enable/disable functionality
    _this.hot.addHook('afterGetColHeader', function (col, TH) {
      return _this.onAfterGetColHeader(col, TH);
    });
    return _this;
  }

  /**
   * 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 DropdownMenu#enablePlugin} method is called.
   *
   * @returns {boolean}
   */
  _createClass(DropdownMenu, [{
    key: "isEnabled",
    value: function isEnabled() {
      return this.hot.getSettings()[PLUGIN_KEY];
    }

    /**
     * Enables the plugin functionality for this Handsontable instance.
     *
     * @fires Hooks#afterDropdownMenuDefaultOptions
     * @fires Hooks#beforeDropdownMenuSetItems
     */
  }, {
    key: "enablePlugin",
    value: function enablePlugin() {
      var _this2 = this;
      if (this.enabled) {
        return;
      }
      this.itemsFactory = new _itemsFactory.default(this.hot, DropdownMenu.DEFAULT_ITEMS);
      var settings = this.hot.getSettings()[PLUGIN_KEY];
      var predefinedItems = {
        items: this.itemsFactory.getItems(settings)
      };
      this.registerEvents();
      if (typeof settings.callback === 'function') {
        this.commandExecutor.setCommonCallback(settings.callback);
      }
      this.registerShortcuts();
      _get(_getPrototypeOf(DropdownMenu.prototype), "enablePlugin", this).call(this);
      this.callOnPluginsReady(function () {
        _this2.hot.runHooks('afterDropdownMenuDefaultOptions', predefinedItems);
        _this2.itemsFactory.setPredefinedItems(predefinedItems.items);
        var menuItems = _this2.itemsFactory.getItems(settings);
        if (_this2.menu) {
          _this2.menu.destroy();
        }
        _this2.menu = new _menu.default(_this2.hot, {
          className: 'htDropdownMenu',
          keepInViewport: true,
          container: settings.uiContainer || _this2.hot.rootDocument.body
        });
        _this2.hot.runHooks('beforeDropdownMenuSetItems', menuItems);
        _this2.menu.setMenuItems(menuItems);
        _this2.menu.addLocalHook('beforeOpen', function () {
          return _this2.onMenuBeforeOpen();
        });
        _this2.menu.addLocalHook('afterOpen', function () {
          return _this2.onMenuAfterOpen();
        });
        _this2.menu.addLocalHook('afterClose', function () {
          return _this2.onMenuAfterClose();
        });
        _this2.menu.addLocalHook('executeCommand', function () {
          var _this2$executeCommand;
          for (var _len = arguments.length, params = new Array(_len), _key = 0; _key < _len; _key++) {
            params[_key] = arguments[_key];
          }
          return (_this2$executeCommand = _this2.executeCommand).call.apply(_this2$executeCommand, [_this2].concat(params));
        });

        // Register all commands. Predefined and added by user or by plugins
        (0, _array.arrayEach)(menuItems, function (command) {
          return _this2.commandExecutor.registerCommand(command.key, command);
        });
      });
    }

    /**
     * Updates the plugin's state.
     *
     * This method is executed when [`updateSettings()`](@/api/core.md#updatesettings) is invoked with any of the following configuration options:
     *  - [`dropdownMenu`](@/api/options.md#dropdownmenu)
     */
  }, {
    key: "updatePlugin",
    value: function updatePlugin() {
      this.disablePlugin();
      this.enablePlugin();
      _get(_getPrototypeOf(DropdownMenu.prototype), "updatePlugin", this).call(this);
    }

    /**
     * Disables the plugin functionality for this Handsontable instance.
     */
  }, {
    key: "disablePlugin",
    value: function disablePlugin() {
      this.close();
      if (this.menu) {
        this.menu.destroy();
      }
      this.unregisterShortcuts();
      _get(_getPrototypeOf(DropdownMenu.prototype), "disablePlugin", this).call(this);
    }

    /**
     * Register shortcuts responsible for toggling dropdown menu.
     *
     * @private
     */
  }, {
    key: "registerShortcuts",
    value: function registerShortcuts() {
      var _this3 = this;
      var context = this.hot.getShortcutManager().getContext('grid');
      var callback = function callback() {
        var _this3$hot$getSelecte = _this3.hot.getSelectedRangeLast(),
          highlight = _this3$hot$getSelecte.highlight;
        if ((highlight.isHeader() && highlight.row === -1 || highlight.isCell()) && highlight.col >= 0) {
          _this3.hot.selectColumns(highlight.col, highlight.col, -1);
          var _this3$hot$getSelecte2 = _this3.hot.getSelectedRangeLast(),
            from = _this3$hot$getSelecte2.from;
          var offset = (0, _utils.getDocumentOffsetByElement)(_this3.menu.container, _this3.hot.rootDocument);
          var target = _this3.hot.getCell(-1, from.col, true);
          var rect = target.getBoundingClientRect();
          _this3.open({
            left: rect.left + offset.left,
            top: rect.top + target.offsetHeight + offset.top
          }, {
            left: rect.width
          });
          _this3.hot._registerTimeout(function () {
            _this3.menu.selectFirstCell();
          });
        }
      };
      context.addShortcuts([{
        keys: [['Shift', 'Alt', 'ArrowDown'], ['Shift', 'Enter']],
        callback: callback,
        runOnlyIf: function runOnlyIf() {
          var _this3$hot$getSelecte3;
          return ((_this3$hot$getSelecte3 = _this3.hot.getSelectedRangeLast()) === null || _this3$hot$getSelecte3 === void 0 ? void 0 : _this3$hot$getSelecte3.highlight.isHeader()) && !_this3.menu.isOpened();
        },
        group: SHORTCUTS_GROUP
      }, {
        keys: [['Shift', 'Alt', 'ArrowDown']],
        callback: callback,
        runOnlyIf: function runOnlyIf() {
          var _this3$hot$getSelecte4;
          return ((_this3$hot$getSelecte4 = _this3.hot.getSelectedRangeLast()) === null || _this3$hot$getSelecte4 === void 0 ? void 0 : _this3$hot$getSelecte4.highlight.isCell()) && !_this3.menu.isOpened();
        },
        group: SHORTCUTS_GROUP
      }]);
    }

    /**
     * Unregister shortcuts responsible for toggling dropdown menu.
     *
     * @private
     */
  }, {
    key: "unregisterShortcuts",
    value: function unregisterShortcuts() {
      this.hot.getShortcutManager().getContext('grid').removeShortcutsByGroup(SHORTCUTS_GROUP);
    }

    /**
     * Registers the DOM listeners.
     *
     * @private
     */
  }, {
    key: "registerEvents",
    value: function registerEvents() {
      var _this4 = this;
      this.eventManager.addEventListener(this.hot.rootElement, 'click', function (event) {
        return _this4.onTableClick(event);
      });
    }

    /**
     * Opens menu and re-position it based on the passed coordinates.
     *
     * @param {{ top: number, left: number }|Event} position An object with `top` and `left` properties
     * which contains coordinates relative to the browsers viewport (without included scroll offsets).
     * Or if the native event is passed the menu will be positioned based on the `pageX` and `pageY`
     * coordinates.
     * @param {{ above: number, below: number, left: number, right: number }} offset An object allows applying
     * the offset to the menu position.
     * @fires Hooks#beforeDropdownMenuShow
     * @fires Hooks#afterDropdownMenuShow
     */
  }, {
    key: "open",
    value: function open(position) {
      var _this$menu,
        _this5 = this;
      var offset = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {
        above: 0,
        below: 0,
        left: 0,
        right: 0
      };
      if ((_this$menu = this.menu) !== null && _this$menu !== void 0 && _this$menu.isOpened()) {
        return;
      }
      this.menu.open();
      (0, _object.objectEach)(offset, function (value, key) {
        _this5.menu.setOffset(key, value);
      });
      this.menu.setPosition(position);
    }

    /**
     * Closes dropdown menu.
     */
  }, {
    key: "close",
    value: function close() {
      var _this$menu2;
      (_this$menu2 = this.menu) === null || _this$menu2 === void 0 ? void 0 : _this$menu2.close();
    }

    /**
     * Executes context menu command.
     *
     * The `executeCommand()` method works only for selected cells.
     *
     * When no cells are selected, `executeCommand()` doesn't do anything.
     *
     * You can execute all predefined commands:
     *  * `'row_above'` - Insert row above
     *  * `'row_below'` - Insert row below
     *  * `'col_left'` - Insert column left
     *  * `'col_right'` - Insert column right
     *  * `'clear_column'` - Clear selected column
     *  * `'remove_row'` - Remove row
     *  * `'remove_col'` - Remove column
     *  * `'undo'` - Undo last action
     *  * `'redo'` - Redo last action
     *  * `'make_read_only'` - Make cell read only
     *  * `'alignment:left'` - Alignment to the left
     *  * `'alignment:top'` - Alignment to the top
     *  * `'alignment:right'` - Alignment to the right
     *  * `'alignment:bottom'` - Alignment to the bottom
     *  * `'alignment:middle'` - Alignment to the middle
     *  * `'alignment:center'` - Alignment to the center (justify).
     *
     * Or you can execute command registered in settings where `key` is your command name.
     *
     * @param {string} commandName Command name to execute.
     * @param {*} params Additional parameters passed to the command executor.
     */
  }, {
    key: "executeCommand",
    value: function executeCommand(commandName) {
      var _this$commandExecutor;
      for (var _len2 = arguments.length, params = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
        params[_key2 - 1] = arguments[_key2];
      }
      (_this$commandExecutor = this.commandExecutor).execute.apply(_this$commandExecutor, [commandName].concat(params));
    }

    /**
     * Turns on / off listening on dropdown menu.
     *
     * @private
     * @param {boolean} listen Turn on listening when value is set to true, otherwise turn it off.
     */
  }, {
    key: "setListening",
    value: function setListening() {
      var listen = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true;
      if (this.menu.isOpened()) {
        if (listen) {
          this.menu.hotMenu.listen();
        } else {
          this.menu.hotMenu.unlisten();
        }
      }
    }

    /**
     * Table click listener.
     *
     * @private
     * @param {Event} event The mouse event object.
     */
  }, {
    key: "onTableClick",
    value: function onTableClick(event) {
      event.stopPropagation();
      if ((0, _element.hasClass)(event.target, BUTTON_CLASS_NAME)) {
        var offset = (0, _utils.getDocumentOffsetByElement)(this.menu.container, this.hot.rootDocument);
        var rect = event.target.getBoundingClientRect();
        this.open({
          left: rect.left + offset.left,
          top: rect.top + event.target.offsetHeight + 3 + offset.top
        }, {
          left: rect.width
        });
      }
    }

    /**
     * On after get column header listener.
     *
     * @private
     * @param {number} col Visual column index.
     * @param {HTMLTableCellElement} TH Header's TH element.
     */
  }, {
    key: "onAfterGetColHeader",
    value: function onAfterGetColHeader(col, TH) {
      // Corner or a higher-level header
      var headerRow = TH.parentNode;
      if (!headerRow) {
        return;
      }
      var headerRowList = headerRow.parentNode.childNodes;
      var level = Array.prototype.indexOf.call(headerRowList, headerRow);
      if (col < 0 || level !== headerRowList.length - 1) {
        return;
      }
      var existingButton = TH.querySelector(".".concat(BUTTON_CLASS_NAME));

      // Plugin enabled and buttons already exists, return.
      if (this.enabled && existingButton) {
        return;
      }
      // Plugin disabled and buttons still exists, so remove them.
      if (!this.enabled) {
        if (existingButton) {
          existingButton.parentNode.removeChild(existingButton);
        }
        return;
      }
      var button = this.hot.rootDocument.createElement('button');
      button.className = BUTTON_CLASS_NAME;
      button.type = 'button';

      // prevent page reload on button click
      button.onclick = function () {
        return false;
      };
      TH.firstChild.insertBefore(button, TH.firstChild.firstChild);
    }

    /**
     * On menu before open listener.
     *
     * @private
     * @fires Hooks#beforeDropdownMenuShow
     */
  }, {
    key: "onMenuBeforeOpen",
    value: function onMenuBeforeOpen() {
      this.hot.runHooks('beforeDropdownMenuShow', this);
    }

    /**
     * On menu after open listener.
     *
     * @private
     * @fires Hooks#afterDropdownMenuShow
     */
  }, {
    key: "onMenuAfterOpen",
    value: function onMenuAfterOpen() {
      this.hot.runHooks('afterDropdownMenuShow', this);
    }

    /**
     * On menu after close listener.
     *
     * @private
     * @fires Hooks#afterDropdownMenuHide
     */
  }, {
    key: "onMenuAfterClose",
    value: function onMenuAfterClose() {
      this.hot.listen();
      this.hot.runHooks('afterDropdownMenuHide', this);
    }

    /**
     * Destroys the plugin instance.
     */
  }, {
    key: "destroy",
    value: function destroy() {
      this.close();
      if (this.menu) {
        this.menu.destroy();
      }
      _get(_getPrototypeOf(DropdownMenu.prototype), "destroy", this).call(this);
    }
  }], [{
    key: "PLUGIN_KEY",
    get: function get() {
      return PLUGIN_KEY;
    }
  }, {
    key: "PLUGIN_PRIORITY",
    get: function get() {
      return PLUGIN_PRIORITY;
    }
  }, {
    key: "PLUGIN_DEPS",
    get: function get() {
      return ['plugin:AutoColumnSize'];
    }

    /**
     * Default menu items order when `dropdownMenu` is enabled by setting the config item to `true`.
     *
     * @returns {Array}
     */
  }, {
    key: "DEFAULT_ITEMS",
    get: function get() {
      return [_predefinedItems.COLUMN_LEFT, _predefinedItems.COLUMN_RIGHT, _predefinedItems.SEPARATOR, _predefinedItems.REMOVE_COLUMN, _predefinedItems.SEPARATOR, _predefinedItems.CLEAR_COLUMN, _predefinedItems.SEPARATOR, _predefinedItems.READ_ONLY, _predefinedItems.SEPARATOR, _predefinedItems.ALIGNMENT];
    }
  }]);
  return DropdownMenu;
}(_base.BasePlugin);
exports.DropdownMenu = DropdownMenu;
DropdownMenu.SEPARATOR = {
  name: _predefinedItems.SEPARATOR
};