import _toConsumableArray from "@babel/runtime/helpers/toConsumableArray";
import { Fragment, Slice } from '@atlaskit/editor-prosemirror/model';

/**
 * A helper to get the underlying array of a fragment.
 */
export function getFragmentBackingArray(fragment) {
  return fragment.content;
}
export 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 Fragment) {
        children.push.apply(children, _toConsumableArray(getFragmentBackingArray(transformed)));
      } else if (Array.isArray(transformed)) {
        children.push.apply(children, _toConsumableArray(transformed));
      } else {
        children.push(transformed);
      }
    }
  }
  return Fragment.fromArray(children);
}
export function mapSlice(slice, callback) {
  var fragment = mapFragment(slice.content, callback);
  return new Slice(fragment, slice.openStart, slice.openEnd);
}
export 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, _toConsumableArray(child));
    } else {
      fragmentContent.push(child);
    }
  }
  return Fragment.fromArray(fragmentContent);
}
export function mapChildren(node, callback) {
  var array = [];
  for (var i = 0; i < node.childCount; i++) {
    array.push(callback(node.child(i), i, node instanceof Fragment ? node : node.content));
  }
  return array;
}