"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var parser_exports = {};
__export(parser_exports, {
  fromCKEditorHtml: () => fromCKEditorHtml
});
module.exports = __toCommonJS(parser_exports);
var A = __toESM(require("fp-ts-esm/Array"));
var import_function = require("fp-ts-esm/function");
var O = __toESM(require("fp-ts-esm/Option"));
var import_Predicate = require("fp-ts-esm/Predicate");
var RONEA = __toESM(require("fp-ts-esm/ReadonlyNonEmptyArray"));
var R = __toESM(require("fp-ts-esm/Record"));
var S = __toESM(require("fp-ts-esm/string"));
var import_v1 = require("./../../../../../ricos-schema/legacy/wix/rich_content/v1/index.js");
var import_fp_utils = require("../../../../fp-utils.js");
var import_node_utils = require("../../../node-utils.js");
var import_parse5_utils = require("../core/parse5-utils.js");
var import_parser = require("../core/parser.js");
var import_rules = require("../core/rules.js");
var import_a_to_custom_link = require("./a-to-custom-link.js");
var import_iframe_to_video = require("./iframe-to-video.js");
var import_postprocess = require("./postprocess.js");
var import_preprocess = require("./preprocess.js");
const noEmptyLineText = [
  // @ts-ignore $TSFixMe
  (0, import_fp_utils.and)([import_parse5_utils.isText, (0, import_Predicate.not)(import_parse5_utils.isWhitespace), (0, import_Predicate.not)((0, import_parse5_utils.hasParent)(import_parse5_utils.isRoot))]),
  import_rules.textToText[1]
];
const rootTextToP = [
  // @ts-ignore $TSFixMe
  (0, import_fp_utils.and)([import_parse5_utils.isText, (0, import_parse5_utils.hasParent)(import_parse5_utils.isRoot)]),
  (ctx) => (el) => [(0, import_node_utils.createParagraphNode)(import_rules.textToText[1](ctx)(el))]
];
const traverseDiv = [(0, import_parse5_utils.hasTag)("div"), import_rules.identityRule[1]];
const traverseSpan = [
  (0, import_fp_utils.and)([
    // @ts-ignore $TSFixMe
    (0, import_parse5_utils.hasTag)("span"),
    // @ts-ignore $TSFixMe
    (0, import_Predicate.not)((0, import_parse5_utils.hasStyleFor)("font-weight")),
    // @ts-ignore $TSFixMe
    (0, import_Predicate.not)((0, import_parse5_utils.hasStyleFor)("font-style")),
    // @ts-ignore $TSFixMe
    (0, import_Predicate.not)((0, import_parse5_utils.hasStyleFor)("text-decoration")),
    // @ts-ignore $TSFixMe
    (0, import_Predicate.not)((0, import_parse5_utils.hasStyleFor)("color")),
    // @ts-ignore $TSFixMe
    (0, import_Predicate.not)((0, import_parse5_utils.hasStyleFor)("background-color")),
    // @ts-ignore $TSFixMe
    (0, import_Predicate.not)((0, import_parse5_utils.hasStyleFor)("vertical-align"))
  ]),
  // @ts-ignore $TSFixMe
  (context) => (element) => {
    const processedImageNodes = processImageNode(context, element);
    return processedImageNodes.length > 0 ? processedImageNodes : import_rules.identityRule[1](context)(element);
  }
];
const fontStyleToItalic = [
  // @ts-ignore $TSFixMe
  (0, import_fp_utils.or)([(0, import_parse5_utils.hasTag)("em"), (0, import_fp_utils.and)([(0, import_parse5_utils.hasTag)("span"), (0, import_parse5_utils.hasStyleRule)({ "font-style": "italic" })])]),
  ({ addDecoration }) => (
    // @ts-ignore $TSFixMe
    (el) => addDecoration(import_v1.Decoration_Type.ITALIC, {}, el)
  )
];
const boldToTextDecoration = [
  // @ts-ignore $TSFixMe
  (0, import_parse5_utils.oneOf)(["b", "strong"]),
  ({ addDecoration }) => (
    // @ts-ignore $TSFixMe
    (el) => addDecoration(import_v1.Decoration_Type.BOLD, {}, el)
  )
];
const fontWeightToDecoration = [
  // @ts-ignore $TSFixMe
  (0, import_fp_utils.and)([(0, import_parse5_utils.hasTag)("span"), (0, import_parse5_utils.hasStyleFor)("font-weight")]),
  ({ addDecoration, visit }) => (
    // @ts-ignore $TSFixMe
    (el) => {
      const fontWeight = (0, import_function.pipe)(
        (0, import_parse5_utils.getStyle)(el),
        O.chain(R.lookup("font-weight")),
        O.fold(() => "", import_function.identity)
      );
      if (fontWeight === "bold" || parseInt(fontWeight, 10) >= 700) {
        return addDecoration(import_v1.Decoration_Type.BOLD, {}, el);
      }
      return visit(el);
    }
  )
];
const textDecorationToUnderline = [
  // @ts-ignore $TSFixMe
  (0, import_fp_utils.or)([(0, import_parse5_utils.hasTag)("u"), (0, import_fp_utils.and)([(0, import_parse5_utils.hasTag)("span"), (0, import_parse5_utils.hasStyleRule)({ "text-decoration": "underline" })])]),
  ({ addDecoration }) => (
    // @ts-ignore $TSFixMe
    (el) => addDecoration(import_v1.Decoration_Type.UNDERLINE, {}, el)
  )
];
const linethroughToStrikethrough = [
  (0, import_fp_utils.or)([
    // @ts-ignore $TSFixMe
    (0, import_parse5_utils.oneOf)(["s", "del", "strike"]),
    // @ts-ignore $TSFixMe
    (0, import_fp_utils.and)([(0, import_parse5_utils.hasTag)("span"), (0, import_parse5_utils.hasStyleRule)({ "text-decoration": "line-through" })])
  ]),
  ({ addDecoration }) => (
    // @ts-ignore $TSFixMe
    (el) => addDecoration(import_v1.Decoration_Type.STRIKETHROUGH, {}, el)
  )
];
const textToSuperscript = [
  // @ts-ignore $TSFixMe
  (0, import_fp_utils.or)([(0, import_parse5_utils.oneOf)(["sup"]), (0, import_fp_utils.and)([(0, import_parse5_utils.hasTag)("span"), (0, import_parse5_utils.hasStyleRule)({ "vertical-align": "super" })])]),
  ({ addDecoration }) => (
    // @ts-ignore $TSFixMe
    (el) => addDecoration(import_v1.Decoration_Type.SUPERSCRIPT, { superscriptData: true }, el)
  )
];
const textToSubscript = [
  // @ts-ignore $TSFixMe
  (0, import_fp_utils.or)([(0, import_parse5_utils.oneOf)(["sub"]), (0, import_fp_utils.and)([(0, import_parse5_utils.hasTag)("span"), (0, import_parse5_utils.hasStyleRule)({ "vertical-align": "sub" })])]),
  ({ addDecoration }) => (
    // @ts-ignore $TSFixMe
    (el) => addDecoration(import_v1.Decoration_Type.SUBSCRIPT, { subscriptData: true }, el)
  )
];
const alignmentToTextStyle = (alignment) => ({
  textAlignment: alignment
});
const alignmentToContainerData = (align) => ({
  alignment: align
});
const getAlignment = (0, import_function.flow)(
  RONEA.filter((c) => ["align-left", "align-right", "align-center"].includes(c)),
  O.map(RONEA.head),
  O.map(S.replace("align-", "")),
  O.fold(() => "", S.toUpperCase)
);
const getAlignmentByClass = (0, import_function.flow)(import_parse5_utils.getClassNames, getAlignment);
const hasAlignmentClass = (0, import_function.flow)(getAlignmentByClass, Boolean);
const mergeWithTextStyle = (dataProp, textStyle) => (node) => ({
  ...node,
  [dataProp]: {
    ...node[dataProp],
    textStyle: { ...node[dataProp]?.textStyle, ...textStyle }
  }
});
const mergeWithContainerData = (dataProp, containerData) => (node) => ({
  ...node,
  [dataProp]: {
    ...node[dataProp],
    containerData: {
      ...node[dataProp]?.containerData,
      ...containerData
    }
  }
});
const lineHeightToTextStyle = (lineHeight) => ({ lineHeight });
const getLineHeight = (0, import_function.flow)(
  import_parse5_utils.getStyle,
  O.chain(R.lookup("line-height")),
  O.fold(() => "", import_function.identity)
);
const figureToMedia = [
  (0, import_parse5_utils.hasTag)("figure"),
  // @ts-ignore $TSFixMe
  (context) => (element) => {
    const result = context.visit(element);
    const mediaNode = result.find(
      (node) => [import_v1.Node_Type.IMAGE, import_v1.Node_Type.VIDEO, import_v1.Node_Type.GIF].includes(node.type)
    );
    const figCaptionNode = result.find((node) => node.type === import_v1.Node_Type.CAPTION);
    if (mediaNode) {
      return [
        {
          ...mediaNode,
          ...figCaptionNode ? { nodes: [...mediaNode.nodes, figCaptionNode] } : {}
        }
      ];
    } else {
      return [];
    }
  }
];
const figCaptionToCaption = [
  (0, import_parse5_utils.hasTag)("figcaption"),
  // @ts-ignore $TSFixMe
  (context) => (element) => {
    const node = context.visit(element);
    const findChildTextNode = (nodes) => {
      for (const n of nodes) {
        if (n.type === import_v1.Node_Type.TEXT) {
          return n;
        }
        if (n.nodes && n.nodes.length > 0) {
          const childTextNode = findChildTextNode(n.nodes);
          if (childTextNode) {
            return childTextNode;
          }
        }
      }
      return void 0;
    };
    const textNode = findChildTextNode(node);
    return textNode ? [(0, import_node_utils.createCaptionNode)([textNode])] : [];
  }
];
const pWitTextToStyledParagraph = [
  // @ts-ignore $TSFixMe
  (0, import_fp_utils.and)([import_rules.pToParagraph[0], (0, import_parse5_utils.hasChild)((0, import_Predicate.not)(import_parse5_utils.isWhitespace))]),
  // @ts-ignore $TSFixMe
  (context) => (element) => (0, import_function.pipe)(
    element,
    import_rules.pToParagraph[1](context),
    A.map(
      hasAlignmentClass(element) ? mergeWithTextStyle(
        "paragraphData",
        // @ts-ignore $TSFixMe
        (0, import_function.pipe)(element, getAlignmentByClass, alignmentToTextStyle)
      ) : import_function.identity
    ),
    A.map(
      (0, import_parse5_utils.hasStyleFor)("line-height")(element) ? mergeWithTextStyle("paragraphData", (0, import_function.pipe)(element, getLineHeight, lineHeightToTextStyle)) : import_function.identity
    )
  )
];
const hToStyledHeading = [
  import_rules.hToHeading[0],
  // @ts-ignore $TSFixMe
  (context) => (element) => (0, import_function.pipe)(
    element,
    import_rules.hToHeading[1](context),
    A.map(
      hasAlignmentClass(element) ? mergeWithTextStyle(
        "headingData",
        // @ts-ignore $TSFixMe
        (0, import_function.pipe)(element, getAlignmentByClass, alignmentToTextStyle)
      ) : import_function.identity
    ),
    A.map(
      (0, import_parse5_utils.hasStyleFor)("line-height")(element) ? mergeWithTextStyle("headingData", (0, import_function.pipe)(element, getLineHeight, lineHeightToTextStyle)) : import_function.identity
    )
  )
];
const iframeToAlignedVimeoVideo = [
  import_iframe_to_video.iframeToVimeoVideo[0],
  // @ts-ignore $TSFixMe
  (context) => (element) => {
    return (0, import_function.pipe)(
      element,
      import_iframe_to_video.iframeToVimeoVideo[1](context),
      A.map(
        hasAlignmentClass(element) ? mergeWithContainerData(
          "videoData",
          // @ts-ignore $TSFixMe
          (0, import_function.pipe)(element, getAlignmentByClass, alignmentToContainerData)
        ) : import_function.identity
      )
    );
  }
];
const iframeToAlignedYoutubeVideo = [
  import_iframe_to_video.iframeToYoutubeVideo[0],
  // @ts-ignore $TSFixMe
  (context) => (element) => {
    return (0, import_function.pipe)(
      element,
      import_iframe_to_video.iframeToYoutubeVideo[1](context),
      A.map(
        hasAlignmentClass(element) ? mergeWithContainerData(
          "videoData",
          // @ts-ignore $TSFixMe
          (0, import_function.pipe)(element, getAlignmentByClass, alignmentToContainerData)
        ) : import_function.identity
      )
    );
  }
];
const videoToVideo = [
  (0, import_parse5_utils.hasTag)("video"),
  // @ts-ignore $TSFixMe
  () => (element) => {
    const attrs = (0, import_parse5_utils.getAttributes)(element);
    return [
      (0, import_node_utils.createNode)(import_v1.Node_Type.VIDEO, {
        nodes: [],
        data: {
          video: {
            src: { url: attrs.src }
          }
        }
      })
    ];
  }
];
const imgToAlignedImage = [
  import_rules.imgToImage[0],
  // @ts-ignore $TSFixMe
  (context) => (element) => {
    return (0, import_function.pipe)(
      element,
      import_rules.imgToImage[1](context),
      A.map(
        hasAlignmentClass(element) ? mergeWithContainerData(
          "imageData",
          // @ts-ignore $TSFixMe
          (0, import_function.pipe)(element, getAlignmentByClass, alignmentToContainerData)
        ) : mergeWithContainerData("imageData", {
          alignment: import_v1.PluginContainerData_Alignment.CENTER
        })
      )
    );
  }
];
const KNOWN_TAGS = [
  "p",
  "div",
  "span",
  "figure",
  "img",
  "a",
  "s",
  "strike",
  "del",
  "iframe",
  "strong",
  "em",
  "u",
  "ol",
  "ul",
  "li",
  "b",
  "i",
  "h1",
  "h2",
  "h3",
  "h4",
  "h5",
  "h6",
  "table",
  "thead",
  "tbody",
  "tfoot",
  "tr",
  "th",
  "td",
  "sup",
  "sub",
  "figcaption"
];
const unwrapUnknownTag = [
  (node) => {
    return !KNOWN_TAGS.includes(node.nodeName.toLowerCase());
  },
  import_rules.identityRule[1]
];
const processImageNode = (context, element) => {
  const anchorNode = element.childNodes.find((node) => node.nodeName === "a");
  if (anchorNode) {
    const imageNode = anchorNode.childNodes.find((node) => node.nodeName === "img");
    if (imageNode) {
      const imageNodes = imgToAlignedImage[1](context)(imageNode);
      const linkAttrs = (0, import_parse5_utils.getAttributes)(anchorNode);
      const linkData = linkAttrs.href ? {
        link: (0, import_node_utils.createLink)({ ...linkAttrs, url: linkAttrs.href })
      } : void 0;
      return imageNodes.map((imgNode) => ({
        ...imgNode,
        imageData: {
          ...imgNode.imageData,
          link: linkData?.link
        }
      }));
    }
  }
  const directImageNode = element.childNodes.find((node) => node.nodeName === "img");
  if (directImageNode) {
    return import_rules.imgToImage[1](context)(directImageNode);
  }
  return [];
};
const tableToTable = [
  (0, import_parse5_utils.hasTag)("table"),
  // @ts-ignore $TSFixMe
  (context) => (element) => {
    const header = element.childNodes.find((node) => node.nodeName === "thead");
    const hasColumnHeader = (node) => {
      if (node.nodeName === "tr") {
        if (!node.childNodes || node.childNodes.length === 0 || node.childNodes[0].nodeName !== "th") {
          return false;
        }
      }
      if (node.childNodes && node.childNodes.length > 0) {
        for (const childNode of node.childNodes) {
          if (!hasColumnHeader(childNode)) {
            return false;
          }
        }
      }
      return true;
    };
    return [
      (0, import_node_utils.createTableNode)(context.visit(element), {
        rowHeader: !!header,
        columnHeader: hasColumnHeader(element),
        cellPadding: []
      })
    ];
  }
];
const omitTableWrappers = [
  // @ts-ignore $TSFixMe
  (0, import_fp_utils.or)([(0, import_parse5_utils.hasTag)("thead"), (0, import_parse5_utils.hasTag)("tbody"), (0, import_parse5_utils.hasTag)("tfoot")]),
  // @ts-ignore $TSFixMe
  (context) => (element) => context.visit(element)
];
const trToRow = [
  (0, import_parse5_utils.hasTag)("tr"),
  // @ts-ignore $TSFixMe
  (context) => (element) => [(0, import_node_utils.createTableRowNode)(context.visit(element))]
];
const tdToCell = [
  // @ts-ignore $TSFixMe
  (0, import_fp_utils.or)([(0, import_parse5_utils.hasTag)("td"), (0, import_parse5_utils.hasTag)("th")]),
  // @ts-ignore $TSFixMe
  (context) => (element) => {
    let childParagraph;
    if (element.childNodes.length === 0) {
      childParagraph = (0, import_node_utils.createParagraphNode)();
    } else {
      const textChild = element.childNodes.find(import_parse5_utils.isText);
      if (textChild) {
        childParagraph = (0, import_node_utils.createParagraphNode)([
          (0, import_node_utils.createTextNode)(textChild.value, context.decorations)
        ]);
      }
    }
    return [(0, import_node_utils.createTableCellNode)(childParagraph ? [childParagraph] : context.visit(element))];
  }
];
const fromCKEditorHtml = (s, interceptorFn = ({ result }) => result) => (0, import_function.flow)(
  () => (0, import_preprocess.preprocess)(s),
  (0, import_parser.parser)(
    [
      tableToTable,
      omitTableWrappers,
      tdToCell,
      trToRow,
      noEmptyLineText,
      rootTextToP,
      pWitTextToStyledParagraph,
      import_rules.lToList,
      hToStyledHeading,
      import_a_to_custom_link.aToCustomLink,
      boldToTextDecoration,
      fontWeightToDecoration,
      fontStyleToItalic,
      import_rules.colorStyleToTextColor,
      import_rules.backgroundStyleToTextHighlight,
      textDecorationToUnderline,
      iframeToAlignedYoutubeVideo,
      iframeToAlignedVimeoVideo,
      imgToAlignedImage,
      traverseDiv,
      traverseSpan,
      figureToMedia,
      unwrapUnknownTag,
      linethroughToStrikethrough,
      textToSuperscript,
      textToSubscript,
      videoToVideo,
      figCaptionToCaption
    ],
    interceptorFn
  ),
  import_postprocess.postprocess
)();
//# sourceMappingURL=parser.js.map
