"use strict";

exports.__esModule = true;
require("core-js/modules/es.error.cause.js");
require("core-js/modules/es.array.push.js");
var _element = require("../../helpers/dom/element");
var _event = require("../../helpers/dom/event");
var _object = require("../../helpers/object");
var _eventManager = _interopRequireDefault(require("../../eventManager"));
var _base = require("../base");
var _commentEditor = _interopRequireDefault(require("./commentEditor"));
var _displaySwitch2 = _interopRequireDefault(require("./displaySwitch"));
var _predefinedItems = require("../contextMenu/predefinedItems");
var _addEditComment = _interopRequireDefault(require("./contextMenuItem/addEditComment"));
var _removeComment = _interopRequireDefault(require("./contextMenuItem/removeComment"));
var _readOnlyComment = _interopRequireDefault(require("./contextMenuItem/readOnlyComment"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classPrivateFieldInitSpec(obj, privateMap, value) { _checkPrivateRedeclaration(obj, privateMap); privateMap.set(obj, value); }
function _checkPrivateRedeclaration(obj, privateCollection) { if (privateCollection.has(obj)) { throw new TypeError("Cannot initialize the same private elements twice on an object"); } }
function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); }
function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
function _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; }
const PLUGIN_KEY = 'comments';
exports.PLUGIN_KEY = PLUGIN_KEY;
const PLUGIN_PRIORITY = 60;
exports.PLUGIN_PRIORITY = PLUGIN_PRIORITY;
const META_COMMENT = 'comment';
exports.META_COMMENT = META_COMMENT;
const META_COMMENT_VALUE = 'value';
exports.META_COMMENT_VALUE = META_COMMENT_VALUE;
const META_STYLE = 'style';
exports.META_STYLE = META_STYLE;
const META_READONLY = 'readOnly';
exports.META_READONLY = META_READONLY;
const SHORTCUTS_GROUP = PLUGIN_KEY;
const SHORTCUTS_CONTEXT_NAME = `plugin:${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();
class Comments extends _base.BasePlugin {
  constructor() {
    super(...arguments);
    /**
     * Current cell range, an object with `from` property, with `row` and `col` properties (e.q. `{from: {row: 1, col: 6}}`).
     *
     * @type {object}
     */
    _defineProperty(this, "range", {});
    /**
     * Instance of {@link EventManager}.
     *
     * @protected
     * @type {EventManager}
     */
    _defineProperty(this, "eventManager", null);
    /**
     * Instance of {@link CommentEditor}.
     *
     * @private
     * @type {CommentEditor}
     */
    _classPrivateFieldInitSpec(this, _editor, {
      writable: true,
      value: null
    });
    /**
     * Instance of {@link DisplaySwitch}.
     *
     * @private
     * @type {DisplaySwitch}
     */
    _classPrivateFieldInitSpec(this, _displaySwitch, {
      writable: true,
      value: null
    });
    /**
     * Prevents showing/hiding editor that reacts on the logic triggered by the "mouseover" events.
     *
     * @private
     * @type {boolean}
     */
    _classPrivateFieldInitSpec(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(this, _preventEditorHiding, {
      writable: true,
      value: false
    });
    /**
     * The property for holding editor dimensions for further processing.
     *
     * @private
     * @type {object}
     */
    _classPrivateFieldInitSpec(this, _tempEditorDimensions, {
      writable: true,
      value: {}
    });
    /**
     * The flag that allows processing mousedown event correctly when comments editor is triggered.
     *
     * @private
     * @type {boolean}
     */
    _classPrivateFieldInitSpec(this, _cellBelowCursor, {
      writable: true,
      value: null
    });
    /**
     * Holds the comment value before it's actually saved to the cell meta.
     *
     * @private
     * @type {string}
     */
    _classPrivateFieldInitSpec(this, _commentValueBeforeSave, {
      writable: true,
      value: ''
    });
  }
  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 Comments#enablePlugin} method is called.
   *
   * @returns {boolean}
   */
  isEnabled() {
    return !!this.hot.getSettings()[PLUGIN_KEY];
  }

  /**
   * Enables the plugin functionality for this Handsontable instance.
   */
  enablePlugin() {
    if (this.enabled) {
      return;
    }
    if (!_classPrivateFieldGet(this, _editor)) {
      _classPrivateFieldSet(this, _editor, new _commentEditor.default(this.hot.rootDocument, this.hot.isRtl()));
    }
    if (!this.eventManager) {
      this.eventManager = new _eventManager.default(this);
    }
    if (!_classPrivateFieldGet(this, _displaySwitch)) {
      _classPrivateFieldSet(this, _displaySwitch, new _displaySwitch2.default(this.getDisplayDelaySetting()));
    }
    this.addHook('afterContextMenuDefaultOptions', options => this.addToContextMenu(options));
    this.addHook('afterRenderer', (TD, row, col, prop, value, cellProperties) => this.onAfterRenderer(TD, cellProperties));
    this.addHook('afterScroll', () => this.onAfterScroll());
    this.addHook('afterBeginEditing', () => this.hide());
    this.addHook('afterDocumentKeyDown', event => this.onAfterDocumentKeyDown(event));
    _classPrivateFieldGet(this, _displaySwitch).addLocalHook('hide', () => this.hide());
    _classPrivateFieldGet(this, _displaySwitch).addLocalHook('show', (row, col) => this.showAtCell(row, col));
    this.registerShortcuts();
    this.registerListeners();
    super.enablePlugin();
  }

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

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

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

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

  /**
   * Registers all necessary DOM listeners.
   *
   * @private
   */
  registerListeners() {
    const {
      rootDocument
    } = this.hot;
    const editorElement = this.getEditorInputElement();
    this.eventManager.addEventListener(rootDocument, 'mouseover', event => this.onMouseOver(event));
    this.eventManager.addEventListener(rootDocument, 'mousedown', event => this.onMouseDown(event));
    this.eventManager.addEventListener(rootDocument, 'mouseup', () => this.onMouseUp());
    this.eventManager.addEventListener(editorElement, 'focus', () => this.onEditorFocus());
    this.eventManager.addEventListener(editorElement, 'blur', () => this.onEditorBlur());
    this.eventManager.addEventListener(editorElement, 'mousedown', event => this.onEditorMouseDown(event));
    this.eventManager.addEventListener(editorElement, 'mouseup', event => this.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.
   */
  setRange(range) {
    this.range = range;
  }

  /**
   * Clears the currently selected cell.
   */
  clearRange() {
    this.range = {};
  }

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

  /**
   * Checks if the event target is a comment textarea.
   *
   * @private
   * @param {Event} event DOM event.
   * @returns {boolean}
   */
  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.
   */
  setComment(value) {
    if (!this.range.from) {
      throw new Error('Before using this method, first set cell range (hot.getPlugin("comment").setRange())');
    }
    const editorValue = _classPrivateFieldGet(this, _editor).getValue();
    let comment = '';
    if (value !== null && value !== void 0) {
      comment = value;
    } else if (editorValue !== null && editorValue !== void 0) {
      comment = editorValue;
    }
    const row = this.range.from.row;
    const col = this.range.from.col;
    this.updateCommentMeta(row, col, {
      [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.
   */
  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.
   */
  removeComment() {
    let 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.
   */
  removeCommentAtCell(row, column) {
    let 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.
   */
  getComment() {
    const row = this.range.from.row;
    const 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.
   */
  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.
   */
  show() {
    var _ref;
    if (!this.range.from) {
      throw new Error('Before using this method, first set cell range (hot.getPlugin("comment").setRange())');
    }
    const {
      from: {
        row,
        col
      }
    } = this.range;
    if (row < 0 || row > this.hot.countSourceRows() - 1 || col < 0 || col > this.hot.countSourceCols() - 1) {
      return false;
    }
    const meta = this.hot.getCellMeta(this.range.from.row, this.range.from.col);
    _classPrivateFieldGet(this, _displaySwitch).cancelHiding();
    _classPrivateFieldGet(this, _editor).setValue((_ref = meta[META_COMMENT] ? meta[META_COMMENT][META_COMMENT_VALUE] : null) !== null && _ref !== void 0 ? _ref : '');
    _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.
   */
  showAtCell(row, column) {
    this.setRange({
      from: this.hot._createCellCoords(row, column)
    });
    return this.show();
  }

  /**
   * Hides the comment editor.
   */
  hide() {
    _classPrivateFieldGet(this, _editor).hide();
  }

  /**
   * Refreshes comment editor position and styling.
   *
   * @param {boolean} [force=false] If `true` then recalculation will be forced.
   */
  refreshEditor() {
    var _renderableRow, _renderableColumn;
    let force = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
    if (!force && (!this.range.from || !_classPrivateFieldGet(this, _editor).isVisible())) {
      return;
    }
    const {
      rowIndexMapper,
      columnIndexMapper
    } = this.hot;
    const {
      row: visualRow,
      col: visualColumn
    } = this.range.from;
    let renderableRow = rowIndexMapper.getRenderableFromVisualIndex(visualRow);
    let renderableColumn = columnIndexMapper.getRenderableFromVisualIndex(visualColumn);
    // Used when the requested row is hidden, and the editor needs to be positioned on the previous row's coords.
    const 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));
    }
    const isBeforeRenderedRows = renderableRow === null;
    const isBeforeRenderedColumns = renderableColumn === null;
    renderableRow = (_renderableRow = renderableRow) !== null && _renderableRow !== void 0 ? _renderableRow : 0;
    renderableColumn = (_renderableColumn = renderableColumn) !== null && _renderableColumn !== void 0 ? _renderableColumn : 0;
    const {
      rootWindow,
      view: {
        _wt: wt
      }
    } = this.hot;
    const {
      wtTable
    } = wt;
    // 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).
    const TD = wt.getCell({
      row: renderableRow,
      col: renderableColumn
    }, true);
    const commentStyle = this.getCommentMeta(visualRow, visualColumn, META_STYLE);
    if (commentStyle) {
      _classPrivateFieldGet(this, _editor).setSize(commentStyle.width, commentStyle.height);
    } else {
      _classPrivateFieldGet(this, _editor).resetSize();
    }
    const lastColWidth = isBeforeRenderedColumns ? 0 : wtTable.getStretchedColumnWidth(renderableColumn);
    const lastRowHeight = targetingPreviousRow && !isBeforeRenderedRows ? (0, _element.outerHeight)(TD) : 0;
    const {
      left,
      top,
      width: cellWidth,
      height: cellHeight
    } = TD.getBoundingClientRect();
    const {
      width: editorWidth,
      height: editorHeight
    } = _classPrivateFieldGet(this, _editor).getSize();
    const {
      innerWidth,
      innerHeight
    } = this.hot.rootWindow;
    const documentElement = this.hot.rootDocument.documentElement;
    let x = left + rootWindow.scrollX + lastColWidth;
    let 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.
   */
  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.
   */
  updateCommentMeta(row, column, metaObject) {
    const oldComment = this.hot.getCellMeta(row, column)[META_COMMENT];
    let newComment;
    if (oldComment) {
      newComment = (0, _object.deepClone)(oldComment);
      (0, _object.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}
   */
  getCommentMeta(row, column, property) {
    const 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.
   */
  onMouseDown(event) {
    if (!this.hot.view || !this.hot.view._wt) {
      return;
    }
    if (!_classPrivateFieldGet(this, _preventEditorAutoSwitch) && !this.targetIsCommentTextArea(event)) {
      const eventCell = (0, _element.closest)(event.target, 'TD', 'TBODY');
      let 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.
   */
  onMouseOver(event) {
    const {
      rootDocument
    } = this.hot;
    if (_classPrivateFieldGet(this, _preventEditorAutoSwitch) || _classPrivateFieldGet(this, _editor).isFocused() || (0, _element.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)) {
      const range = this.hot._createCellRange(this.hot.getCoords(event.target));
      _classPrivateFieldGet(this, _displaySwitch).show(range);
    } else if ((0, _element.isChildOf)(event.target, rootDocument) && !this.targetIsCommentTextArea(event)) {
      _classPrivateFieldGet(this, _displaySwitch).hide();
    }
  }

  /**
   * `mouseup` event callback.
   *
   * @private
   */
  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.
   */
  onAfterRenderer(TD, cellProperties) {
    if (cellProperties[META_COMMENT] && cellProperties[META_COMMENT][META_COMMENT_VALUE]) {
      (0, _element.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
   */
  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
   */
  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.
   */
  onEditorMouseDown(event) {
    _classPrivateFieldSet(this, _tempEditorDimensions, {
      width: (0, _element.outerWidth)(event.target),
      height: (0, _element.outerHeight)(event.target)
    });
  }

  /**
   * `mouseup` hook. Along with `onEditorMouseDown` used to simulate the textarea resizing event.
   *
   * @private
   * @param {MouseEvent} event The `mouseup` event.
   */
  onEditorMouseUp(event) {
    const currentWidth = (0, _element.outerWidth)(event.target);
    const currentHeight = (0, _element.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, {
        [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.
   */
  onAfterDocumentKeyDown(event) {
    if (_classPrivateFieldGet(this, _editor).isVisible()) {
      (0, _event.stopImmediatePropagation)(event);
    }
  }

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

  /**
   * Add Comments plugin options to the Context Menu.
   *
   * @private
   * @param {object} options The menu options.
   */
  addToContextMenu(options) {
    options.items.push({
      name: _predefinedItems.SEPARATOR
    }, (0, _addEditComment.default)(this), (0, _removeComment.default)(this), (0, _readOnlyComment.default)(this));
  }

  /**
   * Get `displayDelay` setting of comment plugin.
   *
   * @private
   * @returns {number|undefined}
   */
  getDisplayDelaySetting() {
    const commentSetting = this.hot.getSettings()[PLUGIN_KEY];
    if ((0, _object.isObject)(commentSetting)) {
      return commentSetting.displayDelay;
    }
  }

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

  /**
   * Destroys the plugin instance.
   */
  destroy() {
    if (_classPrivateFieldGet(this, _editor)) {
      _classPrivateFieldGet(this, _editor).destroy();
    }
    if (_classPrivateFieldGet(this, _displaySwitch)) {
      _classPrivateFieldGet(this, _displaySwitch).destroy();
    }
    super.destroy();
  }
}
exports.Comments = Comments;