"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 to_html_exports = {};
__export(to_html_exports, {
  ensureNodeType: () => ensureNodeType,
  toHtml: () => toHtml
});
module.exports = __toCommonJS(to_html_exports);
var A = __toESM(require("fp-ts-esm/Array"));
var E = __toESM(require("fp-ts-esm/Either"));
var import_function = require("fp-ts-esm/function");
var M = __toESM(require("fp-ts-esm/Monoid"));
var O = __toESM(require("fp-ts-esm/Option"));
var S = __toESM(require("fp-ts-esm/string"));
var import_html_entities = require("html-entities");
var import_lodash = __toESM(require("lodash"));
var import_v1 = require("./../../../../ricos-schema/legacy/wix/rich_content/v1/index.js");
var import_checkbox_list_style = require("./../../../../_shared/list-checkbox/checkbox-list-style.js");
var import_theme_color_token = require("./../../../../_shared/theme-color-token.js");
var import_uncreachable = require("./../../../../_shared/uncreachable.js");
var import_fp_utils = require("../../../fp-utils.js");
const toHtml = (content, interceptorFn = ({ result }) => result, separator = "\n", palette) => {
  const nodes = Array.isArray(content) ? content : content.nodes ?? [];
  return `${nodeArrayToHtml(nodes, interceptorFn, separator, palette)}`;
};
const ensureNodeType = (nodes) => nodes.map((node) => {
  node.type = node.type || import_v1.Node_Type.PARAGRAPH;
  ensureNodeType(node.nodes || []);
  return node;
});
const nodeArrayToHtml = (nodes, interceptorFn, separator = "", palette) => {
  const nodesWithTypes = ensureNodeType(nodes);
  return nodesWithTypes.flatMap((node) => {
    const result = nodeToHtml(node, interceptorFn, palette);
    return interceptorFn({ node, result });
  }).join(separator);
};
const nodeToHtml = (node, interceptorFn, palette) => {
  if (node.type === import_v1.Node_Type.TEXT && node.textData) {
    return decorateTextElement({ ...node.textData, text: (0, import_html_entities.encode)(node.textData.text) }, palette);
  }
  if (node.type === import_v1.Node_Type.PARAGRAPH && node.nodes?.length === 0) {
    return EMPTY_PARAGRAPH;
  }
  let tag = NODE_TO_HTML_TAG[node.type];
  if (node.type === import_v1.Node_Type.HEADING && node.headingData) {
    const { level } = node.headingData;
    tag = `h${level}`;
  }
  if (node.type === import_v1.Node_Type.PARAGRAPH && node.paragraphData) {
    const children = nodeArrayToHtml(node.nodes ?? [], interceptorFn, void 0, palette);
    const attrs = createTextStyleAttrs(node.paragraphData.textStyle);
    return createHtmlTag(tag, children, attrs);
  }
  if (node.type === import_v1.Node_Type.LAYOUT) {
    return nodeArrayToHtml(
      node.nodes?.map((cell) => cell.nodes)?.flat() ?? [],
      interceptorFn,
      void 0,
      palette
    );
  }
  if (tag) {
    const children = nodeArrayToHtml(node.nodes ?? [], interceptorFn, void 0, palette);
    return createHtmlTag(tag, children, createNodeAttrs(node));
  }
  return [];
};
const createLinkAttrs = (decoration) => {
  const rel = Object.entries(decoration.linkData?.link?.rel || {}).filter(([_, value]) => !!value).map(([key]) => key).join(" ");
  const targetRaw = decoration.linkData?.link?.target;
  const ignoreTarget = [void 0, import_v1.Link_Target.UNRECOGNIZED, import_v1.Link_Target.SELF].includes(targetRaw);
  const target = ignoreTarget ? "" : `_${targetRaw?.toLowerCase()}`;
  const anchor = decoration.linkData?.link?.anchor || "";
  const href = decoration.linkData?.link?.url || "";
  return import_lodash.default.pickBy({ href, rel, anchor, target }, import_lodash.default.identity);
};
const createAnchorAttrs = (decoration) => {
  const anchor = decoration.anchorData?.anchor || "";
  return { href: `#${anchor}`, rel: "noopener noreferrer" };
};
const createMentionAttrs = (decoration) => {
  const { name = "", slug = "", id = "" } = decoration.mentionData || {};
  if (!name && !slug && !id) {
    return {};
  }
  return import_lodash.default.pickBy(
    { role: "link", "data-mention-name": name, "data-mention-slug": slug, "data-mention-id": id },
    import_lodash.default.identity
  );
};
const createSpoilerAttrs = () => ({ "data-spoiler": "true" });
const createColorAttrs = (decoration, palette) => {
  const { foreground, background } = decoration.colorData || {};
  const resolveColor = (color) => palette ? (0, import_theme_color_token.resolveDocumentColorToHex)(color, palette) : (0, import_theme_color_token.resolveDocumentColorToCss)(color);
  const fg = resolveColor(foreground);
  const bg = resolveColor(background);
  const style = (0, import_function.pipe)(
    [fg && `color: ${fg};`, bg && `background-color: ${bg};`],
    import_lodash.default.compact,
    M.concatAll(S.Monoid)
  );
  return import_lodash.default.pickBy({ style }, import_lodash.default.identity);
};
const createTextStyleAttrs = (textStyle) => {
  const { textAlignment } = textStyle || {};
  const textAlign = normalizeTextAlignment(textAlignment);
  const style = (0, import_function.pipe)(
    [textAlign && `text-align: ${textAlign};`],
    import_lodash.default.compact,
    M.concatAll(S.Monoid)
  );
  return import_lodash.default.pickBy({ style }, import_lodash.default.identity);
};
const createNodeAttrs = (node) => {
  if (node.type === import_v1.Node_Type.CHECKBOX_LIST) {
    return { "data-list-style": import_checkbox_list_style.CHECKBOX_LIST_STYLE_ATTRIBUTE_VALUE };
  }
  if (node.type === import_v1.Node_Type.LIST_ITEM && node.listItemData?.checked !== void 0) {
    return { role: "checkbox", "aria-checked": node.listItemData.checked ? "true" : "false" };
  }
  return {};
};
const isType = (type) => (decoration) => decoration.type === type;
const createHtmlAttrs = (decoration, palette) => (0, import_fp_utils.firstRight)(decoration, {}, [
  [isType(import_v1.Decoration_Type.LINK), createLinkAttrs],
  [isType(import_v1.Decoration_Type.ANCHOR), createAnchorAttrs],
  [isType(import_v1.Decoration_Type.MENTION), createMentionAttrs],
  [isType(import_v1.Decoration_Type.SPOILER), createSpoilerAttrs],
  [isType(import_v1.Decoration_Type.COLOR), (decoration2) => createColorAttrs(decoration2, palette)]
]);
const createHtmlTag = (tag, child, attrs = {}) => {
  const isFragment = tag === "fragment";
  const prefix = tag === "li" ? "\n  " : "";
  const suffix = ["ul", "ol"].includes(tag) ? "\n" : "";
  return isFragment ? `${child}${suffix}` : `${prefix}<${tag}${attrsToString(attrs)}>${child}${suffix}</${tag}>`;
};
const attrsToString = (attrs) => Object.entries(attrs).map(([key, value]) => ` ${key}="${value}"`).join("");
const toForegroundDecoration = (d) => d.colorData?.foreground ? O.some({ type: import_v1.Decoration_Type.COLOR, colorData: { foreground: d.colorData.foreground } }) : O.none;
const toBackgroundDecoration = (d) => d.colorData?.background ? O.some({ type: import_v1.Decoration_Type.COLOR, colorData: { background: d.colorData.background } }) : O.none;
const expandColorDecoration = (decoration) => (0, import_function.pipe)([toBackgroundDecoration, toForegroundDecoration], A.ap(A.of(decoration)), A.compact);
const eitherColorDecoration = (d) => d.type === import_v1.Decoration_Type.COLOR ? E.right(d) : E.left(d);
const ensureDecorations = (decorations) => decorations || [];
const normalizeDecorations = (0, import_function.flow)(
  ensureDecorations,
  A.map((0, import_function.flow)(eitherColorDecoration, E.fold(A.of, expandColorDecoration))),
  A.flatten
);
const normalizeTextAlignment = (textAlignment) => {
  switch (textAlignment) {
    case import_v1.TextStyle_TextAlignment.CENTER:
    case import_v1.TextStyle_TextAlignment.JUSTIFY:
    case import_v1.TextStyle_TextAlignment.LEFT:
    case import_v1.TextStyle_TextAlignment.RIGHT:
      return textAlignment.toLowerCase();
    case import_v1.TextStyle_TextAlignment.AUTO:
    case import_v1.TextStyle_TextAlignment.UNRECOGNIZED:
    case void 0:
      return void 0;
    default:
      throw (0, import_uncreachable.unreachable)(textAlignment);
  }
};
const decorateTextElement = ({ text, decorations }, palette) => {
  const normalizedDecorations = normalizeDecorations(decorations);
  return normalizedDecorations.reduce((child, decoration) => {
    const tag = DECORATION_TO_HTML_TAG[decoration.type];
    return tag ? createHtmlTag(tag, child, createHtmlAttrs(decoration, palette)) : child;
  }, text);
};
const DECORATION_TO_HTML_TAG = {
  [import_v1.Decoration_Type.COLOR]: "span",
  [import_v1.Decoration_Type.MENTION]: "span",
  [import_v1.Decoration_Type.SPOILER]: "span",
  [import_v1.Decoration_Type.BOLD]: "strong",
  [import_v1.Decoration_Type.ITALIC]: "em",
  [import_v1.Decoration_Type.UNDERLINE]: "u",
  [import_v1.Decoration_Type.LINK]: "a",
  [import_v1.Decoration_Type.ANCHOR]: "a",
  [import_v1.Decoration_Type.STRIKETHROUGH]: "s"
};
const NODE_TO_HTML_TAG = {
  [import_v1.Node_Type.BULLETED_LIST]: "ul",
  [import_v1.Node_Type.CHECKBOX_LIST]: "ul",
  [import_v1.Node_Type.COLLAPSIBLE_LIST]: "ul",
  [import_v1.Node_Type.ORDERED_LIST]: "ol",
  [import_v1.Node_Type.LIST_ITEM]: "li",
  [import_v1.Node_Type.COLLAPSIBLE_ITEM]: "li",
  [import_v1.Node_Type.COLLAPSIBLE_ITEM_TITLE]: "fragment",
  [import_v1.Node_Type.COLLAPSIBLE_ITEM_BODY]: "fragment",
  [import_v1.Node_Type.PARAGRAPH]: "p"
};
const EMPTY_PARAGRAPH = "<p><br /></p>";
//# sourceMappingURL=to-html.js.map
