import _toConsumableArray from "@babel/runtime/helpers/toConsumableArray";
import { Fragment, Slice } from '@atlaskit/editor-prosemirror/model';
import { getFragmentBackingArray } from './getFragmentBackingArray';
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);
}

// eslint-disable-next-line @atlaskit/volt-strict-mode/no-multiple-exports
export function mapSlice(slice, callback) {
  var fragment = mapFragment(slice.content, callback);
  return new Slice(fragment, slice.openStart, slice.openEnd);
}
// eslint-disable-next-line @atlaskit/volt-strict-mode/no-multiple-exports
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);
}
// eslint-disable-next-line @atlaskit/volt-strict-mode/no-multiple-exports
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;
}
var findNode = function findNode(predicate) {
  return function (slice) {
    var foundNode = null;
    slice.content.nodesBetween(0, slice.content.size, function (node) {
      if (predicate(node)) {
        foundNode = node;
        return false;
      }
      return true;
    });
    return foundNode;
  };
};

// eslint-disable-next-line @atlaskit/volt-strict-mode/no-multiple-exports
export var hasNode = function hasNode(predicate) {
  return function (slice) {
    return !!findNode(predicate)(slice);
  };
};
// eslint-disable-next-line @atlaskit/editor/no-re-export
export { getFragmentBackingArray } from './getFragmentBackingArray';