'use strict';

var React = require('react');
var common$1 = require('./chunk-JCA39oKB.cjs.js');
var neetoCist = require('@bigbinary/neeto-cist');
var ramda = require('ramda');
var ReactDOM = require('react-dom/server');
var common = require('./chunk-De3nCFAF.cjs.js');

function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike) { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it["return"] != null) it["return"](); } finally { if (didErr) throw err; } } }; }
function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }
var transformCode = function transformCode(code) {
  return code.replace(/&gt;/g, ">").replace(/&lt;/g, "<").replace(/&amp;/g, "&");
};
var buildReactElementFromAST = function buildReactElementFromAST(element) {
  if (element.tagName) {
    var children = element.children ? element.children.map(buildReactElementFromAST) : null;
    return /*#__PURE__*/React.createElement(element.tagName, element.properties, children);
  }
  return element.value;
};
var splitCodeBlockIntoLines = function splitCodeBlockIntoLines(codeBlock) {
  codeBlock.innerHTML = codeBlock.innerHTML.replace(/([ \S]*\n|[ \S]*$)/gm, function (match) {
    return "<div class=\"highlight-line\">".concat(match, "</div>");
  });
};
var highlightLinesCode = function highlightLinesCode(code, options) {
  if (options === undefined) {
    return;
  }
  var paddingLeft = parseInt(window.getComputedStyle(code).paddingLeft);
  var paddingRight = parseInt(window.getComputedStyle(code).paddingRight);
  var lines = code.getElementsByClassName("highlight-line");
  var scroll_width = code.scrollWidth;
  // eslint-disable-next-line @bigbinary/neeto/use-array-methods
  var _iterator = _createForOfIteratorHelper(options),
    _step;
  try {
    for (_iterator.s(); !(_step = _iterator.n()).done;) {
      var option = _step.value;
      for (var j = option.start; j <= option.end; ++j) {
        if (j >= lines.length) return;
        lines[j].style.backgroundColor = option.color;
        lines[j].style.minWidth = "".concat(scroll_width - paddingLeft - paddingRight, "px");
      }
    }
  } catch (err) {
    _iterator.e(err);
  } finally {
    _iterator.f();
  }
};
var highlightLinesElement = function highlightLinesElement(code, options) {
  // eslint-disable-next-line @bigbinary/neeto/use-array-methods
  var _iterator2 = _createForOfIteratorHelper(options),
    _step2;
  try {
    for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
      var option = _step2.value;
      --option.start;
      --option.end;
    }
  } catch (err) {
    _iterator2.e(err);
  } finally {
    _iterator2.f();
  }
  highlightLinesCode(code, options);
};
var applySyntaxHighlightingAndLineNumbers = function applySyntaxHighlightingAndLineNumbers(content) {
  common.lowlight.highlightAuto("");
  var highlightedAST = {};
  return content.replace(common.CODE_BLOCK_REGEX, function (_, language, code) {
    var _highlightMatch$;
    var highlightRegex = /data-highlighted-lines="([^"]*)"/;
    var linenumbersRegex = /data-linenumbers/;
    var highlightMatch = content.match(highlightRegex);
    if (language && common.LANGUAGE_LIST.includes(language)) {
      highlightedAST = common.lowlight.highlight(language, transformCode(code));
    } else {
      highlightedAST = common$1.HighlightJS.highlightAuto(transformCode(code))._emitter.root;
      if (ramda.isEmpty(highlightedAST.children)) {
        highlightedAST = common.lowlight.highlight("javascript", transformCode(code));
      }
    }
    var highlightedNode = highlightedAST.children.map(buildReactElementFromAST);
    var dataHighlight = "data-highlighted-lines=".concat((_highlightMatch$ = highlightMatch === null || highlightMatch === void 0 ? void 0 : highlightMatch[1]) !== null && _highlightMatch$ !== void 0 ? _highlightMatch$ : "");
    var dataLinenumbers = content.match(linenumbersRegex) ? "data-linenumbers=\"true\"" : "";
    return "<pre ".concat(dataLinenumbers, " ").concat(dataHighlight, "><code>").concat(ReactDOM.renderToString(highlightedNode), "</code></pre>");
  });
};
var applyLineHighlighting = function applyLineHighlighting(editorContent) {
  var codeTags = editorContent === null || editorContent === void 0 ? void 0 : editorContent.querySelectorAll("pre code");
  codeTags.forEach(function (codeTag) {
    splitCodeBlockIntoLines(codeTag);
    var highlightedLines = codeTag.closest("pre").getAttribute("data-highlighted-lines");
    if (highlightedLines) {
      var linesToHighlight = highlightedLines.split(",").map(Number).filter(Boolean);
      var highlightLinesOptions = linesToHighlight.map(function (line) {
        return {
          start: line,
          end: line,
          color: "rgba(255, 255, 0, 0.2)"
        };
      });
      highlightLinesElement(codeTag, highlightLinesOptions);
    }
  });
};
var substituteVariables = function substituteVariables(highlightedContent, variables) {
  return highlightedContent.replace(common.VARIABLE_SPAN_REGEX, function (matchedSpan, _, key) {
    var keySplitted = key.split(".");
    if (keySplitted.length > 1) {
      var category = neetoCist.findBy({
        category: keySplitted[0]
      }, variables);
      var _variable = neetoCist.findBy({
        key: keySplitted[1]
      }, (category === null || category === void 0 ? void 0 : category.variables) || []);
      return _variable !== null && _variable !== void 0 && _variable.value ? _variable.value : matchedSpan;
    }
    var variable = neetoCist.findBy({
      key: keySplitted[0]
    }, variables);
    return variable !== null && variable !== void 0 && variable.value ? variable.value : matchedSpan;
  });
};
var convertPlainTextToHtml = function convertPlainTextToHtml(htmlString) {
  if (/^<[a-z].*>/i.test(htmlString.trim())) return htmlString;
  return htmlString.split("\n").reduce(function (html, str) {
    return "".concat(html, "<p>").concat(str, "</p>");
  }, "");
};

exports.applyLineHighlighting = applyLineHighlighting;
exports.applySyntaxHighlightingAndLineNumbers = applySyntaxHighlightingAndLineNumbers;
exports.convertPlainTextToHtml = convertPlainTextToHtml;
exports.substituteVariables = substituteVariables;
//# sourceMappingURL=chunk-TrGAGew5.cjs.js.map
