import lodash from "lodash";
import * as Y from "yjs";
const isPmTextNode = (node) => node.type === "text";
const convertNormalizedPmContentToYType = (node) => node instanceof Array ? convertPmTextNodesToYText(node) : convertPmNodeToYElement(node);
const convertPmTextNodesToYText = (nodes) => {
  const yXmlText = new Y.XmlText();
  const delta = nodes.map((node) => ({
    insert: node.text,
    attributes: Object.fromEntries(node.marks?.map(({ type, attrs }) => [type, attrs]) ?? [])
  }));
  yXmlText.applyDelta(delta);
  return yXmlText;
};
const convertPmNodeToYElement = (node) => {
  const yXmlElement = new Y.XmlElement(node.type);
  if (node.attrs) {
    Object.entries(node.attrs).forEach(([key, value]) => {
      if (value !== null && key !== "ychange") {
        yXmlElement.setAttribute(key, value);
      }
    });
  }
  yXmlElement.insert(0, normalizePmNodeContent(node).map(convertNormalizedPmContentToYType));
  return yXmlElement;
};
const normalizePmNodeContent = (pmNodeJson) => {
  const content = pmNodeJson.content ?? [];
  const normalizedContent = [];
  for (let i = 0; i < content.length; i++) {
    const node = content[i];
    if (isPmTextNode(node)) {
      const lastNormalizedItem = normalizedContent.length > 0 ? normalizedContent[normalizedContent.length - 1] : void 0;
      if (lastNormalizedItem && Array.isArray(lastNormalizedItem)) {
        lastNormalizedItem.push(node);
      } else {
        normalizedContent.push([node]);
      }
    } else {
      normalizedContent.push(node);
    }
  }
  return normalizedContent;
};
const convertYTextAttrsToPmMarks = (attributes) => attributes ? Object.entries(attributes).map(([type, value]) => {
  const attrs = lodash.isObject(value) ? value : {};
  return { type, attrs };
}) : [];
const convertYTextToPmTextNodes = (yXmlText) => yXmlText.toDelta().map((op) => {
  return {
    type: "text",
    text: op.insert,
    marks: convertYTextAttrsToPmMarks(op.attributes)
  };
});
const convertYElementToPmNode = (yXmlElement) => {
  const type = yXmlElement.nodeName;
  const pmAttrs = Object.fromEntries(Object.entries(yXmlElement.getAttributes()));
  const pmContent = [];
  for (const yChild of yXmlElement.toArray()) {
    if (yChild instanceof Y.XmlText) {
      pmContent.push(...convertYTextToPmTextNodes(yChild));
    } else if (yChild instanceof Y.XmlElement) {
      pmContent.push(convertYElementToPmNode(yChild));
    } else {
      throw new Error("Y.XmlFragment should only contain Y.XmlText and Y.XmlElement children");
    }
  }
  return {
    type,
    ...Object.keys(pmAttrs).length > 0 ? { attrs: pmAttrs } : {},
    ...pmContent.length > 0 ? { content: pmContent } : {}
  };
};
export {
  convertPmNodeToYElement,
  convertPmTextNodesToYText,
  convertYElementToPmNode,
  convertYTextToPmTextNodes
};
//# sourceMappingURL=y-converters.js.map
