"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.createWrapSelectionTransaction = createWrapSelectionTransaction;
var _transform = require("@atlaskit/editor-prosemirror/transform");
var _utils = require("@atlaskit/editor-prosemirror/utils");
var _editorCoreUtils = require("./editor-core-utils");
/**
 * This function creates a new transaction that wraps the current selection
 * in the specified node type if it results in a valid transaction.
 * If not valid, it performs a safe insert operation.
 *
 * Example of when wrapping might not be valid is when attempting to wrap
 * content that is already inside a panel with another panel
 */
function createWrapSelectionTransaction(_ref) {
  var state = _ref.state,
    type = _ref.type,
    nodeAttributes = _ref.nodeAttributes;
  var tr = state.tr;
  var _state$schema$marks = state.schema.marks,
    alignment = _state$schema$marks.alignment,
    indentation = _state$schema$marks.indentation;

  /** Alignment or Indentation is not valid inside block types */
  var removeAlignTr = (0, _editorCoreUtils.removeBlockMarks)(state, [alignment, indentation]);
  tr = removeAlignTr || tr;

  /**Get range and wrapping needed for the selection*/
  var _getWrappingOptions = getWrappingOptions(state, type, nodeAttributes),
    range = _getWrappingOptions.range,
    wrapping = _getWrappingOptions.wrapping;
  if (wrapping) {
    tr.wrap(range, wrapping).scrollIntoView();
  } else {
    /** We always want to append a block type */
    (0, _utils.safeInsert)(type.createAndFill(nodeAttributes))(tr).scrollIntoView();
  }
  return tr;
}
function getWrappingOptions(state, type, nodeAttributes) {
  var _state$selection = state.selection,
    $from = _state$selection.$from,
    $to = _state$selection.$to;
  var range = $from.blockRange($to);
  var isAllowedChild = true;
  /**
   * Added a check to avoid wrapping codeblock
   */
  if (state.selection.empty) {
    state.doc.nodesBetween($from.pos, $to.pos, function (node) {
      if (!isAllowedChild) {
        return false;
      }
      return isAllowedChild = node.type !== state.schema.nodes.codeBlock;
    });
  }
  var wrapping = isAllowedChild && range && (0, _transform.findWrapping)(range, type, nodeAttributes);
  return {
    range: range,
    wrapping: wrapping
  };
}