import { Fragment } from '@atlaskit/editor-prosemirror/model';
import { mapSlice } from '../utils/slice';

/**
 * Ensures every `listItem` in a slice starts with a paragraph.
 *
 * @param slice - The slice to transform
 * @param schema - The editor schema, used to create new paragraph nodes
 * @returns A new slice with the transformation applied
 */
export var transformSliceEnsureListItemParagraphFirst = function transformSliceEnsureListItemParagraphFirst(slice, schema) {
  var _schema$nodes = schema.nodes,
    listItem = _schema$nodes.listItem,
    paragraph = _schema$nodes.paragraph;
  if (!listItem || !paragraph) {
    return slice;
  }
  return mapSlice(slice, function (node) {
    if (node.type === listItem) {
      var firstChild = node.firstChild;
      if (firstChild && firstChild.type !== paragraph) {
        var emptyParagraph = paragraph.createAndFill();
        if (emptyParagraph) {
          var children = [emptyParagraph];
          for (var i = 0; i < node.childCount; i++) {
            children.push(node.child(i));
          }
          return node.copy(Fragment.from(children));
        }
      }
    }
    return node;
  });
};