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); }
import "core-js/modules/es.array.concat.js";
import "core-js/modules/es.array.iterator.js";
import "core-js/modules/es.object.to-string.js";
import "core-js/modules/es.string.iterator.js";
import "core-js/modules/es.weak-map.js";
import "core-js/modules/web.dom-collections.iterator.js";
import "core-js/modules/es.symbol.to-primitive.js";
import "core-js/modules/es.date.to-primitive.js";
import "core-js/modules/es.symbol.js";
import "core-js/modules/es.symbol.description.js";
import "core-js/modules/es.number.constructor.js";
import "core-js/modules/es.object.set-prototype-of.js";
import "core-js/modules/es.object.get-prototype-of.js";
import "core-js/modules/es.reflect.construct.js";
import "core-js/modules/es.reflect.get.js";
import "core-js/modules/es.object.get-own-property-descriptor.js";
import "core-js/modules/es.symbol.iterator.js";
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 _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); }
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 _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; }
import { addClass, closest, isChildOf, hasClass, outerWidth, outerHeight } from "../../helpers/dom/element.mjs";
import { stopImmediatePropagation } from "../../helpers/dom/event.mjs";
import { deepClone, deepExtend, isObject } from "../../helpers/object.mjs";
import EventManager from "../../eventManager.mjs";
import { BasePlugin } from "../base/index.mjs";
import CommentEditor from "./commentEditor.mjs";
import DisplaySwitch from "./displaySwitch.mjs";
import { SEPARATOR } from "../contextMenu/predefinedItems.mjs";
import addEditCommentItem from "./contextMenuItem/addEditComment.mjs";
import removeCommentItem from "./contextMenuItem/removeComment.mjs";
import readOnlyCommentItem from "./contextMenuItem/readOnlyComment.mjs";
export var PLUGIN_KEY = 'comments';
export var PLUGIN_PRIORITY = 60;
export var META_COMMENT = 'comment';
export var META_COMMENT_VALUE = 'value';
export var META_STYLE = 'style';
export var META_READONLY = 'readOnly';
var SHORTCUTS_GROUP = PLUGIN_KEY;
var SHORTCUTS_CONTEXT_NAME = "plugin:".concat(PLUGIN_KEY);

/* eslint-disable jsdoc/require-description-complete-sentence */
/**
 * @plugin Comments
 * @class Comments
 *
 * @description
 * This plugin allows setting and managing cell comments by either an option in the context menu or with the use of
 * the API.
 *
 * To enable the plugin, you'll need to set the comments property of the config object to `true`:
 * ```js
 * comments: true
 * ```
 *
 * or an object with extra predefined plugin config:
 *
 * ```js
 * comments: {
 *   displayDelay: 1000,
 *   readOnly: true,
 *   style: {
 *     width: 300,
 *     height: 100
 *   }
 * }
 * ```
 *
 * To add comments at the table initialization, define the `comment` property in the `cell` config array as in an example below.
 *
 * @example
 * ::: only-for javascript
 * ```js
 * const hot = new Handsontable(document.getElementById('example'), {
 *   data: getData(),
 *   comments: true,
 *   cell: [
 *     {row: 1, col: 1, comment: {value: 'Foo'}},
 *     {row: 2, col: 2, comment: {value: 'Bar'}}
 *   ]
 * });
 *
 * // Access to the Comments plugin instance:
 * const commentsPlugin = hot.getPlugin('comments');
 *
 * // Manage comments programmatically:
 * commentsPlugin.setCommentAtCell(1, 6, 'Comment contents');
 * commentsPlugin.showAtCell(1, 6);
 * commentsPlugin.removeCommentAtCell(1, 6);
 *
 * // You can also set range once and use proper methods:
 * commentsPlugin.setRange({from: {row: 1, col: 6}});
 * commentsPlugin.setComment('Comment contents');
 * commentsPlugin.show();
 * commentsPlugin.removeComment();
 * ```
 * :::
 *
 * ::: only-for react
 * ```jsx
 * const hotRef = useRef(null);
 *
 * ...
 *
 * <HotTable
 *   ref={hotRef}
 *   data={getData()}
 *   comments={true}
 *   cell={[
 *     {row: 1, col: 1, comment: {value: 'Foo'}},
 *     {row: 2, col: 2, comment: {value: 'Bar'}}
 *   ]}
 * />
 *
 * // Access to the Comments plugin instance:
 * const hot = hotRef.current.hotInstance;
 * const commentsPlugin = hot.getPlugin('comments');
 *
 * // Manage comments programmatically:
 * commentsPlugin.setCommentAtCell(1, 6, 'Comment contents');
 * commentsPlugin.showAtCell(1, 6);
 * commentsPlugin.removeCommentAtCell(1, 6);
 *
 * // You can also set range once and use proper methods:
 * commentsPlugin.setRange({from: {row: 1, col: 6}});
 * commentsPlugin.setComment('Comment contents');
 * commentsPlugin.show();
 * commentsPlugin.removeComment();
 * ```
 * :::
 */
var _editor = /*#__PURE__*/new WeakMap();
var _displaySwitch = /*#__PURE__*/new WeakMap();
var _preventEditorAutoSwitch = /*#__PURE__*/new WeakMap();
var _preventEditorHiding = /*#__PURE__*/new WeakMap();
var _tempEditorDimensions = /*#__PURE__*/new WeakMap();
var _cellBelowCursor = /*#__PURE__*/new WeakMap();
var _commentValueBeforeSave = /*#__PURE__*/new WeakMap();
export var Comments = /*#__PURE__*/function (_BasePlugin) {
  _inherits(Comments, _BasePlugin);
  var _super = _createSuper(Comments);
  function Comments() {
    var _this;
    _classCallCheck(this, Comments);
    for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
      args[_key] = arguments[_key];
    }
    _this = _super.call.apply(_super, [this].concat(args));
    /**
     * Current cell range, an object with `from` property, with `row` and `col` properties (e.q. `{from: {row: 1, col: 6}}`).
     *
     * @type {object}
     */
    _defineProperty(_assertThisInitialized(_this), "range", {});
    /**
     * Instance of {@link EventManager}.
     *
     * @protected
     * @type {EventManager}
     */
    _defineProperty(_assertThisInitialized(_this), "eventManager", null);
    /**
     * Instance of {@link CommentEditor}.
     *
     * @private
     * @type {CommentEditor}
     */
    _classPrivateFieldInitSpec(_assertThisInitialized(_this), _editor, {
      writable: true,
      value: null
    });
    /**
     * Instance of {@link DisplaySwitch}.
     *
     * @private
     * @type {DisplaySwitch}
     */
    _classPrivateFieldInitSpec(_assertThisInitialized(_this), _displaySwitch, {
      writable: true,
      value: null
    });
    /**
     * Prevents showing/hiding editor that reacts on the logic triggered by the "mouseover" events.
     *
     * @private
     * @type {boolean}
     */
    _classPrivateFieldInitSpec(_assertThisInitialized(_this), _preventEditorAutoSwitch, {
      writable: true,
      value: false
    });
    /**
     * Prevents hiding editor when the table viewport is scrolled and that scroll is triggered by the
     * keyboard shortcut that insert or edits the comment.
     *
     * @private
     * @type {boolean}
     */
    _classPrivateFieldInitSpec(_assertThisInitialized(_this), _preventEditorHiding, {
      writable: true,
      value: false
    });
    /**
     * The property for holding editor dimensions for further processing.
     *
     * @private
     * @type {object}
     */
    _classPrivateFieldInitSpec(_assertThisInitialized(_this), _tempEditorDimensions, {
      writable: true,
      value: {}
    });
    /**
     * The flag that allows processing mousedown event correctly when comments editor is triggered.
     *
     * @private
     * @type {boolean}
     */
    _classPrivateFieldInitSpec(_assertThisInitialized(_this), _cellBelowCursor, {
      writable: true,
      value: null
    });
    /**
     * Holds the comment value before it's actually saved to the cell meta.
     *
     * @private
     * @type {string}
     */
    _classPrivateFieldInitSpec(_assertThisInitialized(_this), _commentValueBeforeSave, {
      writable: true,
      value: ''
    });
    return _this;
  }
  _createClass(Comments, [{
    key: "isEnabled",
    value:
    /**
     * 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 Comments#enablePlugin} method is called.
     *
     * @returns {boolean}
     */
    function isEnabled() {
      return !!this.hot.getSettings()[PLUGIN_KEY];
    }

    /**
     * Enables the plugin functionality for this Handsontable instance.
     */
  }, {
    key: "enablePlugin",
    value: function enablePlugin() {
      var _this2 = this;
      if (this.enabled) {
        return;
      }
      if (!_classPrivateFieldGet(this, _editor)) {
        _classPrivateFieldSet(this, _editor, new CommentEditor(this.hot.rootDocument, this.hot.isRtl()));
      }
      if (!this.eventManager) {
        this.eventManager = new EventManager(this);
      }
      if (!_classPrivateFieldGet(this, _displaySwitch)) {
        _classPrivateFieldSet(this, _displaySwitch, new DisplaySwitch(this.getDisplayDelaySetting()));
      }
      this.addHook('afterContextMenuDefaultOptions', function (options) {
        return _this2.addToContextMenu(options);
      });
      this.addHook('afterRenderer', function (TD, row, col, prop, value, cellProperties) {
        return _this2.onAfterRenderer(TD, cellProperties);
      });
      this.addHook('afterScroll', function () {
        return _this2.onAfterScroll();
      });
      this.addHook('afterBeginEditing', function () {
        return _this2.hide();
      });
      this.addHook('afterDocumentKeyDown', function (event) {
        return _this2.onAfterDocumentKeyDown(event);
      });
      _classPrivateFieldGet(this, _displaySwitch).addLocalHook('hide', function () {
        return _this2.hide();
      });
      _classPrivateFieldGet(this, _displaySwitch).addLocalHook('show', function (row, col) {
        return _this2.showAtCell(row, col);
      });
      this.registerShortcuts();
      this.registerListeners();
      _get(_getPrototypeOf(Comments.prototype), "enablePlugin", this).call(this);
    }

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

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

    /**
     * Register shortcuts responsible for toggling context menu.
     *
     * @private
     */
  }, {
    key: "registerShortcuts",
    value: function registerShortcuts() {
      var _this3 = this;
      var manager = this.hot.getShortcutManager();
      var gridContext = manager.getContext('grid');
      var pluginContext = manager.addContext(SHORTCUTS_CONTEXT_NAME);
      gridContext.addShortcut({
        keys: [['Control', 'Alt', 'M']],
        callback: function callback() {
          var range = _this3.hot.getSelectedRangeLast();
          _classPrivateFieldSet(_this3, _preventEditorHiding, true);
          _this3.hot.scrollToFocusedCell(function () {
            _this3.setRange(range);
            _this3.show();
            _this3.focusEditor();
            manager.setActiveContextName(SHORTCUTS_CONTEXT_NAME);
            _this3.hot._registerTimeout(function () {
              _classPrivateFieldSet(_this3, _preventEditorHiding, false);
            });
          });
        },
        stopPropagation: true,
        runOnlyIf: function runOnlyIf() {
          var _this3$hot$getSelecte;
          return ((_this3$hot$getSelecte = _this3.hot.getSelectedRangeLast()) === null || _this3$hot$getSelecte === void 0 ? void 0 : _this3$hot$getSelecte.highlight.isCell()) && !_classPrivateFieldGet(_this3, _editor).isVisible();
        },
        group: SHORTCUTS_GROUP
      });
      pluginContext.addShortcut({
        keys: [['Escape']],
        callback: function callback() {
          _classPrivateFieldGet(_this3, _editor).setValue(_classPrivateFieldGet(_this3, _commentValueBeforeSave));
          _this3.hide();
          manager.setActiveContextName('grid');
        },
        runOnlyIf: function runOnlyIf() {
          var _this3$hot$getSelecte2;
          return ((_this3$hot$getSelecte2 = _this3.hot.getSelectedRangeLast()) === null || _this3$hot$getSelecte2 === void 0 ? void 0 : _this3$hot$getSelecte2.highlight.isCell()) && _classPrivateFieldGet(_this3, _editor).isVisible();
        },
        group: SHORTCUTS_GROUP
      });
      pluginContext.addShortcut({
        keys: [['Control/Meta', 'Enter']],
        callback: function callback() {
          _this3.hide();
          manager.setActiveContextName('grid');
        },
        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.isCell()) && _classPrivateFieldGet(_this3, _editor).isVisible();
        },
        group: SHORTCUTS_GROUP
      });
    }

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

    /**
     * Registers all necessary DOM listeners.
     *
     * @private
     */
  }, {
    key: "registerListeners",
    value: function registerListeners() {
      var _this4 = this;
      var rootDocument = this.hot.rootDocument;
      var editorElement = this.getEditorInputElement();
      this.eventManager.addEventListener(rootDocument, 'mouseover', function (event) {
        return _this4.onMouseOver(event);
      });
      this.eventManager.addEventListener(rootDocument, 'mousedown', function (event) {
        return _this4.onMouseDown(event);
      });
      this.eventManager.addEventListener(rootDocument, 'mouseup', function () {
        return _this4.onMouseUp();
      });
      this.eventManager.addEventListener(editorElement, 'focus', function () {
        return _this4.onEditorFocus();
      });
      this.eventManager.addEventListener(editorElement, 'blur', function () {
        return _this4.onEditorBlur();
      });
      this.eventManager.addEventListener(editorElement, 'mousedown', function (event) {
        return _this4.onEditorMouseDown(event);
      });
      this.eventManager.addEventListener(editorElement, 'mouseup', function (event) {
        return _this4.onEditorMouseUp(event);
      });
    }

    /**
     * Sets the current cell range to be able to use general methods like {@link Comments#setComment}, {@link Comments#removeComment}, {@link Comments#show}.
     *
     * @param {object} range Object with `from` property, each with `row` and `col` properties.
     */
  }, {
    key: "setRange",
    value: function setRange(range) {
      this.range = range;
    }

    /**
     * Clears the currently selected cell.
     */
  }, {
    key: "clearRange",
    value: function clearRange() {
      this.range = {};
    }

    /**
     * Checks if the event target is a cell containing a comment.
     *
     * @private
     * @param {Event} event DOM event.
     * @returns {boolean}
     */
  }, {
    key: "targetIsCellWithComment",
    value: function targetIsCellWithComment(event) {
      var closestCell = closest(event.target, 'TD', 'TBODY');
      return !!(closestCell && hasClass(closestCell, 'htCommentCell') && closest(closestCell, [this.hot.rootElement]));
    }

    /**
     * Checks if the event target is a comment textarea.
     *
     * @private
     * @param {Event} event DOM event.
     * @returns {boolean}
     */
  }, {
    key: "targetIsCommentTextArea",
    value: function targetIsCommentTextArea(event) {
      return this.getEditorInputElement() === event.target;
    }

    /**
     * Sets a comment for a cell according to the previously set range (see {@link Comments#setRange}).
     *
     * @param {string} value Comment contents.
     */
  }, {
    key: "setComment",
    value: function setComment(value) {
      if (!this.range.from) {
        throw new Error('Before using this method, first set cell range (hot.getPlugin("comment").setRange())');
      }
      var editorValue = _classPrivateFieldGet(this, _editor).getValue();
      var comment = '';
      if (value !== null && value !== void 0) {
        comment = value;
      } else if (editorValue !== null && editorValue !== void 0) {
        comment = editorValue;
      }
      var row = this.range.from.row;
      var col = this.range.from.col;
      this.updateCommentMeta(row, col, _defineProperty({}, META_COMMENT_VALUE, comment));
      this.hot.render();
    }

    /**
     * Sets a comment for a specified cell.
     *
     * @param {number} row Visual row index.
     * @param {number} column Visual column index.
     * @param {string} value Comment contents.
     */
  }, {
    key: "setCommentAtCell",
    value: function setCommentAtCell(row, column, value) {
      this.setRange({
        from: this.hot._createCellCoords(row, column)
      });
      this.setComment(value);
    }

    /**
     * Removes a comment from a cell according to previously set range (see {@link Comments#setRange}).
     *
     * @param {boolean} [forceRender=true] If set to `true`, the table will be re-rendered at the end of the operation.
     */
  }, {
    key: "removeComment",
    value: function removeComment() {
      var forceRender = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true;
      if (!this.range.from) {
        throw new Error('Before using this method, first set cell range (hot.getPlugin("comment").setRange())');
      }
      this.hot.setCellMeta(this.range.from.row, this.range.from.col, META_COMMENT);
      if (forceRender) {
        this.hot.render();
      }
      this.hide();
    }

    /**
     * Removes a comment from a specified cell.
     *
     * @param {number} row Visual row index.
     * @param {number} column Visual column index.
     * @param {boolean} [forceRender=true] If `true`, the table will be re-rendered at the end of the operation.
     */
  }, {
    key: "removeCommentAtCell",
    value: function removeCommentAtCell(row, column) {
      var forceRender = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true;
      this.setRange({
        from: this.hot._createCellCoords(row, column)
      });
      this.removeComment(forceRender);
    }

    /**
     * Gets comment from a cell according to previously set range (see {@link Comments#setRange}).
     *
     * @returns {string|undefined} Returns a content of the comment.
     */
  }, {
    key: "getComment",
    value: function getComment() {
      var row = this.range.from.row;
      var column = this.range.from.col;
      return this.getCommentMeta(row, column, META_COMMENT_VALUE);
    }

    /**
     * Gets comment from a cell at the provided coordinates.
     *
     * @param {number} row Visual row index.
     * @param {number} column Visual column index.
     * @returns {string|undefined} Returns a content of the comment.
     */
  }, {
    key: "getCommentAtCell",
    value: function getCommentAtCell(row, column) {
      return this.getCommentMeta(row, column, META_COMMENT_VALUE);
    }

    /**
     * Shows the comment editor accordingly to the previously set range (see {@link Comments#setRange}).
     *
     * @returns {boolean} Returns `true` if comment editor was shown.
     */
  }, {
    key: "show",
    value: function show() {
      if (!this.range.from) {
        throw new Error('Before using this method, first set cell range (hot.getPlugin("comment").setRange())');
      }
      var _this$range$from = this.range.from,
        row = _this$range$from.row,
        col = _this$range$from.col;
      if (row < 0 || row > this.hot.countSourceRows() - 1 || col < 0 || col > this.hot.countSourceCols() - 1) {
        return false;
      }
      var meta = this.hot.getCellMeta(this.range.from.row, this.range.from.col);
      _classPrivateFieldGet(this, _displaySwitch).cancelHiding();
      _classPrivateFieldGet(this, _editor).setValue(meta[META_COMMENT] ? meta[META_COMMENT][META_COMMENT_VALUE] : null || '');
      _classPrivateFieldGet(this, _editor).show();
      this.refreshEditor(true);
      return true;
    }

    /**
     * Shows comment editor according to cell coordinates.
     *
     * @param {number} row Visual row index.
     * @param {number} column Visual column index.
     * @returns {boolean} Returns `true` if comment editor was shown.
     */
  }, {
    key: "showAtCell",
    value: function showAtCell(row, column) {
      this.setRange({
        from: this.hot._createCellCoords(row, column)
      });
      return this.show();
    }

    /**
     * Hides the comment editor.
     */
  }, {
    key: "hide",
    value: function hide() {
      _classPrivateFieldGet(this, _editor).hide();
    }

    /**
     * Refreshes comment editor position and styling.
     *
     * @param {boolean} [force=false] If `true` then recalculation will be forced.
     */
  }, {
    key: "refreshEditor",
    value: function refreshEditor() {
      var _renderableRow, _renderableColumn;
      var force = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
      if (!force && (!this.range.from || !_classPrivateFieldGet(this, _editor).isVisible())) {
        return;
      }
      var _this$hot = this.hot,
        rowIndexMapper = _this$hot.rowIndexMapper,
        columnIndexMapper = _this$hot.columnIndexMapper;
      var _this$range$from2 = this.range.from,
        visualRow = _this$range$from2.row,
        visualColumn = _this$range$from2.col;
      var renderableRow = rowIndexMapper.getRenderableFromVisualIndex(visualRow);
      var renderableColumn = columnIndexMapper.getRenderableFromVisualIndex(visualColumn);
      // Used when the requested row is hidden, and the editor needs to be positioned on the previous row's coords.
      var targetingPreviousRow = renderableRow === null;

      // Reset the editor position to (0, 0) so the opening direction calculation wouldn't be influenced by its
      // previous position
      _classPrivateFieldGet(this, _editor).setPosition(0, 0);
      if (renderableRow === null) {
        renderableRow = rowIndexMapper.getRenderableFromVisualIndex(rowIndexMapper.getNearestNotHiddenIndex(visualRow, -1));
      }
      if (renderableColumn === null) {
        renderableColumn = columnIndexMapper.getRenderableFromVisualIndex(columnIndexMapper.getNearestNotHiddenIndex(visualColumn, -1));
      }
      var isBeforeRenderedRows = renderableRow === null;
      var isBeforeRenderedColumns = renderableColumn === null;
      renderableRow = (_renderableRow = renderableRow) !== null && _renderableRow !== void 0 ? _renderableRow : 0;
      renderableColumn = (_renderableColumn = renderableColumn) !== null && _renderableColumn !== void 0 ? _renderableColumn : 0;
      var _this$hot2 = this.hot,
        rootWindow = _this$hot2.rootWindow,
        wt = _this$hot2.view._wt;
      var wtTable = wt.wtTable;
      // TODO: Probably using `hot.getCell` would be the best. However, case for showing comment editor for hidden cell
      // potentially should be removed with that change (currently a test for it is passing).
      var TD = wt.getCell({
        row: renderableRow,
        col: renderableColumn
      }, true);
      var commentStyle = this.getCommentMeta(visualRow, visualColumn, META_STYLE);
      if (commentStyle) {
        _classPrivateFieldGet(this, _editor).setSize(commentStyle.width, commentStyle.height);
      } else {
        _classPrivateFieldGet(this, _editor).resetSize();
      }
      var lastColWidth = isBeforeRenderedColumns ? 0 : wtTable.getStretchedColumnWidth(renderableColumn);
      var lastRowHeight = targetingPreviousRow && !isBeforeRenderedRows ? outerHeight(TD) : 0;
      var _TD$getBoundingClient = TD.getBoundingClientRect(),
        left = _TD$getBoundingClient.left,
        top = _TD$getBoundingClient.top,
        cellWidth = _TD$getBoundingClient.width,
        cellHeight = _TD$getBoundingClient.height;
      var _classPrivateFieldGet2 = _classPrivateFieldGet(this, _editor).getSize(),
        editorWidth = _classPrivateFieldGet2.width,
        editorHeight = _classPrivateFieldGet2.height;
      var _this$hot$rootWindow = this.hot.rootWindow,
        innerWidth = _this$hot$rootWindow.innerWidth,
        innerHeight = _this$hot$rootWindow.innerHeight;
      var documentElement = this.hot.rootDocument.documentElement;
      var x = left + rootWindow.scrollX + lastColWidth;
      var y = top + rootWindow.scrollY + lastRowHeight;
      if (this.hot.isRtl()) {
        x -= editorWidth + lastColWidth;
      }

      // flip to the right or left the comments editor position when it goes out of browser viewport
      if (this.hot.isLtr() && left + cellWidth + editorWidth > innerWidth) {
        x = left + rootWindow.scrollX - editorWidth - 1;
      } else if (this.hot.isRtl() && x < -(documentElement.scrollWidth - documentElement.clientWidth)) {
        x = left + rootWindow.scrollX + lastColWidth + 1;
      }
      if (top + editorHeight > innerHeight) {
        y -= editorHeight - cellHeight + 1;
      }
      _classPrivateFieldGet(this, _editor).setPosition(x, y);
      _classPrivateFieldGet(this, _editor).setReadOnlyState(this.getCommentMeta(visualRow, visualColumn, META_READONLY));
    }

    /**
     * Focuses the comments editor element.
     */
  }, {
    key: "focusEditor",
    value: function focusEditor() {
      _classPrivateFieldGet(this, _editor).focus();
    }

    /**
     * Sets or update the comment-related cell meta.
     *
     * @param {number} row Visual row index.
     * @param {number} column Visual column index.
     * @param {object} metaObject Object defining all the comment-related meta information.
     */
  }, {
    key: "updateCommentMeta",
    value: function updateCommentMeta(row, column, metaObject) {
      var oldComment = this.hot.getCellMeta(row, column)[META_COMMENT];
      var newComment;
      if (oldComment) {
        newComment = deepClone(oldComment);
        deepExtend(newComment, metaObject);
      } else {
        newComment = metaObject;
      }
      this.hot.setCellMeta(row, column, META_COMMENT, newComment);
    }

    /**
     * Gets the comment related meta information.
     *
     * @param {number} row Visual row index.
     * @param {number} column Visual column index.
     * @param {string} property Cell meta property.
     * @returns {Mixed}
     */
  }, {
    key: "getCommentMeta",
    value: function getCommentMeta(row, column, property) {
      var cellMeta = this.hot.getCellMeta(row, column);
      if (!cellMeta[META_COMMENT]) {
        return void 0;
      }
      return cellMeta[META_COMMENT][property];
    }

    /**
     * `mousedown` event callback.
     *
     * @private
     * @param {MouseEvent} event The `mousedown` event.
     */
  }, {
    key: "onMouseDown",
    value: function onMouseDown(event) {
      if (!this.hot.view || !this.hot.view._wt) {
        return;
      }
      if (!_classPrivateFieldGet(this, _preventEditorAutoSwitch) && !this.targetIsCommentTextArea(event)) {
        var eventCell = closest(event.target, 'TD', 'TBODY');
        var coordinates = null;
        if (eventCell) {
          coordinates = this.hot.getCoords(eventCell);
        }
        if (!eventCell || this.range.from && coordinates && (this.range.from.row !== coordinates.row || this.range.from.col !== coordinates.col)) {
          this.hide();
        }
      }
    }

    /**
     * `mouseover` event callback.
     *
     * @private
     * @param {MouseEvent} event The `mouseover` event.
     */
  }, {
    key: "onMouseOver",
    value: function onMouseOver(event) {
      var rootDocument = this.hot.rootDocument;
      if (_classPrivateFieldGet(this, _preventEditorAutoSwitch) || _classPrivateFieldGet(this, _editor).isFocused() || hasClass(event.target, 'wtBorder') || _classPrivateFieldGet(this, _cellBelowCursor) === event.target || !_classPrivateFieldGet(this, _editor)) {
        return;
      }
      _classPrivateFieldSet(this, _cellBelowCursor, rootDocument.elementFromPoint(event.clientX, event.clientY));
      if (this.targetIsCellWithComment(event)) {
        var range = this.hot._createCellRange(this.hot.getCoords(event.target));
        _classPrivateFieldGet(this, _displaySwitch).show(range);
      } else if (isChildOf(event.target, rootDocument) && !this.targetIsCommentTextArea(event)) {
        _classPrivateFieldGet(this, _displaySwitch).hide();
      }
    }

    /**
     * `mouseup` event callback.
     *
     * @private
     */
  }, {
    key: "onMouseUp",
    value: function onMouseUp() {
      _classPrivateFieldSet(this, _preventEditorAutoSwitch, false);
    }

    /**
     * The `afterRenderer` hook callback.
     *
     * @private
     * @param {HTMLTableCellElement} TD The rendered `TD` element.
     * @param {object} cellProperties The rendered cell's property object.
     */
  }, {
    key: "onAfterRenderer",
    value: function onAfterRenderer(TD, cellProperties) {
      if (cellProperties[META_COMMENT] && cellProperties[META_COMMENT][META_COMMENT_VALUE]) {
        addClass(TD, cellProperties.commentedCellClassName);
      }
    }

    /**
     * Hook observer the "blur" event from the comments editor element. The hook clears the
     * editor content and gives back the keyboard shortcuts control by switching to the "grid" context.
     *
     * @private
     */
  }, {
    key: "onEditorBlur",
    value: function onEditorBlur() {
      _classPrivateFieldSet(this, _commentValueBeforeSave, '');
      this.hot.getShortcutManager().setActiveContextName('grid');
      this.setComment();
    }

    /**
     * Hook observer the "focus" event from the comments editor element. The hook takes the control of
     * the keyboard shortcuts by switching the context to plugins one.
     *
     * @private
     */
  }, {
    key: "onEditorFocus",
    value: function onEditorFocus() {
      _classPrivateFieldSet(this, _commentValueBeforeSave, this.getComment());
      this.hot.listen();
      this.hot.getShortcutManager().setActiveContextName(SHORTCUTS_CONTEXT_NAME);
    }

    /**
     * `mousedown` hook. Along with `onEditorMouseUp` used to simulate the textarea resizing event.
     *
     * @private
     * @param {MouseEvent} event The `mousedown` event.
     */
  }, {
    key: "onEditorMouseDown",
    value: function onEditorMouseDown(event) {
      _classPrivateFieldSet(this, _tempEditorDimensions, {
        width: outerWidth(event.target),
        height: outerHeight(event.target)
      });
    }

    /**
     * `mouseup` hook. Along with `onEditorMouseDown` used to simulate the textarea resizing event.
     *
     * @private
     * @param {MouseEvent} event The `mouseup` event.
     */
  }, {
    key: "onEditorMouseUp",
    value: function onEditorMouseUp(event) {
      var currentWidth = outerWidth(event.target);
      var currentHeight = outerHeight(event.target);
      if (currentWidth !== _classPrivateFieldGet(this, _tempEditorDimensions).width + 1 || currentHeight !== _classPrivateFieldGet(this, _tempEditorDimensions).height + 2) {
        this.updateCommentMeta(this.range.from.row, this.range.from.col, _defineProperty({}, META_STYLE, {
          width: currentWidth,
          height: currentHeight
        }));
      }
    }

    /**
     * Observes the pressed keys and if there is already opened the comment editor prevents open
     * the table editor into the fast edit mode.
     *
     * @param {Event} event The keydown event.
     */
  }, {
    key: "onAfterDocumentKeyDown",
    value: function onAfterDocumentKeyDown(event) {
      if (_classPrivateFieldGet(this, _editor).isVisible()) {
        stopImmediatePropagation(event);
      }
    }

    /**
     * Observes the changes in the scroll position if triggered it hides the comment editor.
     */
  }, {
    key: "onAfterScroll",
    value: function onAfterScroll() {
      if (!_classPrivateFieldGet(this, _preventEditorHiding)) {
        this.hide();
      }
    }

    /**
     * Add Comments plugin options to the Context Menu.
     *
     * @private
     * @param {object} options The menu options.
     */
  }, {
    key: "addToContextMenu",
    value: function addToContextMenu(options) {
      options.items.push({
        name: SEPARATOR
      }, addEditCommentItem(this), removeCommentItem(this), readOnlyCommentItem(this));
    }

    /**
     * Get `displayDelay` setting of comment plugin.
     *
     * @private
     * @returns {number|undefined}
     */
  }, {
    key: "getDisplayDelaySetting",
    value: function getDisplayDelaySetting() {
      var commentSetting = this.hot.getSettings()[PLUGIN_KEY];
      if (isObject(commentSetting)) {
        return commentSetting.displayDelay;
      }
    }

    /**
     * Gets the editors input element.
     *
     * @private
     * @returns {HTMLTextAreaElement}
     */
  }, {
    key: "getEditorInputElement",
    value: function getEditorInputElement() {
      return _classPrivateFieldGet(this, _editor).getInputElement();
    }

    /**
     * Destroys the plugin instance.
     */
  }, {
    key: "destroy",
    value: function destroy() {
      if (_classPrivateFieldGet(this, _editor)) {
        _classPrivateFieldGet(this, _editor).destroy();
      }
      if (_classPrivateFieldGet(this, _displaySwitch)) {
        _classPrivateFieldGet(this, _displaySwitch).destroy();
      }
      _get(_getPrototypeOf(Comments.prototype), "destroy", this).call(this);
    }
  }], [{
    key: "PLUGIN_KEY",
    get: function get() {
      return PLUGIN_KEY;
    }
  }, {
    key: "PLUGIN_PRIORITY",
    get: function get() {
      return PLUGIN_PRIORITY;
    }
  }]);
  return Comments;
}(BasePlugin);