"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.useEventHandlers = useEventHandlers;
var _dom = require("@wordpress/dom");
var _keycodes = require("@wordpress/keycodes");
var _data = require("@wordpress/data");
var _compose = require("@wordpress/compose");
var _store = require("../../../store");
var _lockUnlock = require("../../../lock-unlock");
/**
 * WordPress dependencies
 */

/**
 * Internal dependencies
 */

/**
 * Adds block behaviour:
 *   - Removes the block on BACKSPACE.
 *   - Inserts a default block on ENTER.
 *   - Disables dragging of block contents.
 *
 * @param {string} clientId Block client ID.
 */
function useEventHandlers({
  clientId,
  isSelected
}) {
  const {
    getBlockRootClientId,
    getBlockIndex,
    isZoomOut
  } = (0, _lockUnlock.unlock)((0, _data.useSelect)(_store.store));
  const {
    insertAfterBlock,
    removeBlock,
    resetZoomLevel
  } = (0, _lockUnlock.unlock)((0, _data.useDispatch)(_store.store));
  return (0, _compose.useRefEffect)(node => {
    if (!isSelected) {
      return;
    }

    /**
     * Interprets keydown event intent to remove or insert after block if
     * key event occurs on wrapper node. This can occur when the block has
     * no text fields of its own, particularly after initial insertion, to
     * allow for easy deletion and continuous writing flow to add additional
     * content.
     *
     * @param {KeyboardEvent} event Keydown event.
     */
    function onKeyDown(event) {
      const {
        keyCode,
        target
      } = event;
      if (keyCode !== _keycodes.ENTER && keyCode !== _keycodes.BACKSPACE && keyCode !== _keycodes.DELETE) {
        return;
      }
      if (target !== node || (0, _dom.isTextField)(target)) {
        return;
      }
      event.preventDefault();
      if (keyCode === _keycodes.ENTER && isZoomOut()) {
        resetZoomLevel();
      } else if (keyCode === _keycodes.ENTER) {
        insertAfterBlock(clientId);
      } else {
        removeBlock(clientId);
      }
    }

    /**
     * Prevents default dragging behavior within a block. To do: we must
     * handle this in the future and clean up the drag target.
     *
     * @param {DragEvent} event Drag event.
     */
    function onDragStart(event) {
      event.preventDefault();
    }
    node.addEventListener('keydown', onKeyDown);
    node.addEventListener('dragstart', onDragStart);
    return () => {
      node.removeEventListener('keydown', onKeyDown);
      node.removeEventListener('dragstart', onDragStart);
    };
  }, [clientId, isSelected, getBlockRootClientId, getBlockIndex, insertAfterBlock, removeBlock, isZoomOut, resetZoomLevel]);
}
//# sourceMappingURL=use-selected-block-event-handlers.js.map