"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.flatmap = flatmap;
exports.getFragmentBackingArray = getFragmentBackingArray;
exports.mapChildren = mapChildren;
exports.mapFragment = mapFragment;
exports.mapSlice = mapSlice;
var _toConsumableArray2 = _interopRequireDefault(require("@babel/runtime/helpers/toConsumableArray"));
var _model = require("@atlaskit/editor-prosemirror/model");
/**
 * A helper to get the underlying array of a fragment.
 */
function getFragmentBackingArray(fragment) {
  return fragment.content;
}
function mapFragment(content, callback) {
  var parent = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;
  var children = [];
  for (var i = 0, size = content.childCount; i < size; i++) {
    var _node = content.child(i);
    var transformed = _node.isLeaf ? callback(_node, parent, i) : callback(_node.copy(mapFragment(_node.content, callback, _node)), parent, i);
    if (transformed) {
      if (transformed instanceof _model.Fragment) {
        children.push.apply(children, (0, _toConsumableArray2.default)(getFragmentBackingArray(transformed)));
      } else if (Array.isArray(transformed)) {
        children.push.apply(children, (0, _toConsumableArray2.default)(transformed));
      } else {
        children.push(transformed);
      }
    }
  }
  return _model.Fragment.fromArray(children);
}
function mapSlice(slice, callback) {
  var fragment = mapFragment(slice.content, callback);
  return new _model.Slice(fragment, slice.openStart, slice.openEnd);
}
function flatmap(fragment, callback) {
  var fragmentContent = [];
  for (var i = 0; i < fragment.childCount; i++) {
    var child = callback(fragment.child(i), i, fragment);
    if (Array.isArray(child)) {
      fragmentContent.push.apply(fragmentContent, (0, _toConsumableArray2.default)(child));
    } else {
      fragmentContent.push(child);
    }
  }
  return _model.Fragment.fromArray(fragmentContent);
}
function mapChildren(node, callback) {
  var array = [];
  for (var i = 0; i < node.childCount; i++) {
    array.push(callback(node.child(i), i, node instanceof _model.Fragment ? node : node.content));
  }
  return array;
}