import { Fragment, Slice } from '@atlaskit/editor-prosemirror/model';
import { findParentNodeOfType, findSelectedNodeOfType } from '@atlaskit/editor-prosemirror/utils';
import { mapChildren } from '../utils/slice';
export var findExpand = function findExpand(state, selection) {
  var _state$schema$nodes = state.schema.nodes,
    expand = _state$schema$nodes.expand,
    nestedExpand = _state$schema$nodes.nestedExpand;
  return findSelectedNodeOfType([expand, nestedExpand])(selection || state.selection) || findParentNodeOfType([expand, nestedExpand])(selection || state.selection);
};

// If the top level is a single expand, and the expand is not
// a part of copied content, then return unwrap contents.
// This is needed for handling content copied from expand.
// https://product-fabric.atlassian.net/browse/ED-9146
export var transformSliceToRemoveOpenExpand = function transformSliceToRemoveOpenExpand(slice, schema) {
  if (slice.openStart > 1 && slice.openEnd > 1 && slice.content.childCount === 1 && slice.content.firstChild && slice.content.firstChild.type === schema.nodes.expand) {
    return new Slice(slice.content.firstChild.content, slice.openStart - 1, slice.openEnd - 1);
  }
  return slice;
};
export var transformSliceToRemoveOpenNestedExpand = function transformSliceToRemoveOpenNestedExpand(slice, schema) {
  if (slice.openStart > 1 && slice.openEnd > 1 && slice.content.childCount === 1 && slice.content.firstChild && slice.content.firstChild.type === schema.nodes.nestedExpand) {
    return new Slice(slice.content.firstChild.content, slice.openStart - 1, slice.openEnd - 1);
  }
  return slice;
};
export var transformSliceNestedExpandToExpand = function transformSliceNestedExpandToExpand(slice, schema) {
  var _schema$nodes = schema.nodes,
    expand = _schema$nodes.expand,
    nestedExpand = _schema$nodes.nestedExpand;
  var children = [];
  mapChildren(slice.content, function (node) {
    if (node.type === nestedExpand) {
      children.push(expand.createChecked(node.attrs, node.content, node.marks));
    } else {
      children.push(node);
    }
  });
  return new Slice(Fragment.fromArray(children), slice.openStart, slice.openEnd);
};