"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.formatText = exports.extractImageMarkdown = void 0;
var _ui = require("@mirai/ui");
var _react = _interopRequireDefault(require("react"));
function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
const IMAGE_MARKDOWN_REGEX = /!\[[^\]]*]\((https?:\/\/[^\s)]+)\)/g;
const IMAGE_LIST_ITEM_REGEX = /^(?:(?:\d+\.|[-*])\s+)?(https?:\/\/[^\s)]+)\s*$/;
const IMAGE_URL_EXTENSION_REGEX = /\.(?:apng|avif|bmp|gif|jpe?g|png|svg|webp)(?:[?#][^\s)]*)?$/i;
const LIST_MARKER_ONLY_REGEX = /^(?:\d+[.)]|[-*])$/;
const LINK_TOKEN_REGEX = /\[([^\]]+)\]\((https?:\/\/[^\s)]+)\)|(https?:\/\/[^\s]+)/g;
const TRAILING_PUNCTUATION_REGEX = /[.,!?;:]$/;
const renderTextWithLineBreaks = (value, keyPrefix) => {
  const lines = value.split('\n');
  if (lines.length === 1) return value;
  return lines.flatMap((line, index) => {
    if (index === lines.length - 1) return line;
    return [line, /*#__PURE__*/_react.default.createElement("br", {
      key: "".concat(keyPrefix, "-br-").concat(index)
    })];
  });
};
const isImageUrl = function () {
  let value = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';
  return IMAGE_URL_EXTENSION_REGEX.test(value);
};
const getImageListLineUrl = function () {
  let line = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';
  const match = line.trim().match(IMAGE_LIST_ITEM_REGEX);
  if (!match) return undefined;
  const [, imageUrl] = match;
  return isImageUrl(imageUrl) ? imageUrl : undefined;
};
const normalizeTextAfterImageExtraction = function () {
  let value = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';
  const compactedLines = [];
  const lines = value.split('\n').map(line => line.replace(/[ \t]+$/g, ''));
  lines.forEach(line => {
    const isEmptyLine = line.trim() === '';
    if (!isEmptyLine) return compactedLines.push(line);
    if (!compactedLines.length || compactedLines[compactedLines.length - 1] === '') return undefined;
    return compactedLines.push('');
  });
  return compactedLines.join('\n').trim();
};
const isListMarkerOnlyLine = function () {
  let value = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';
  return LIST_MARKER_ONLY_REGEX.test(value.trim());
};
const extractImageMarkdown = text => {
  if (!text) return {
    imageUrls: [],
    text
  };
  const imageItems = [];
  const textWithoutMarkdownImages = text.replace(IMAGE_MARKDOWN_REGEX, (match, imageUrl, index) => {
    if (!isImageUrl(imageUrl)) return match;
    imageItems.push({
      imageUrl,
      index
    });
    return '';
  });
  let sourceOffset = 0;
  text.split('\n').forEach(line => {
    const imageUrl = getImageListLineUrl(line);
    if (imageUrl) imageItems.push({
      imageUrl,
      index: sourceOffset
    });
    sourceOffset += line.length + 1;
  });
  if (!imageItems.length) return {
    imageUrls: [],
    text
  };
  const textWithoutImageList = textWithoutMarkdownImages.split('\n').filter(line => !getImageListLineUrl(line) && !isListMarkerOnlyLine(line)).join('\n');
  const imageUrls = imageItems.sort((a, b) => a.index - b.index).map(_ref => {
    let {
      imageUrl
    } = _ref;
    return imageUrl;
  });
  const nextText = normalizeTextAfterImageExtraction(textWithoutImageList);
  return {
    imageUrls,
    text: nextText
  };
};
exports.extractImageMarkdown = extractImageMarkdown;
const formatText = text => {
  if (!text) return text;
  const hasNewlines = text.includes('\n');
  const hasLinks = LINK_TOKEN_REGEX.test(text);
  LINK_TOKEN_REGEX.lastIndex = 0;
  if (!hasLinks && !hasNewlines) return text;
  if (!hasLinks) return renderTextWithLineBreaks(text, 'text');
  const output = [];
  let lastIndex = 0;
  let match;
  while ((match = LINK_TOKEN_REGEX.exec(text)) !== null) {
    const [rawMatch, markdownLabel, markdownUrl, rawUrl] = match;
    const matchIndex = match.index;
    if (matchIndex > lastIndex) {
      const beforeText = text.slice(lastIndex, matchIndex);
      const renderedBefore = renderTextWithLineBreaks(beforeText, "text-".concat(matchIndex));
      if (Array.isArray(renderedBefore)) {
        output.push(...renderedBefore);
      } else {
        output.push(renderedBefore);
      }
    }
    const linkUrl = (markdownUrl || rawUrl).replace(TRAILING_PUNCTUATION_REGEX, '');
    const linkLabel = markdownLabel || linkUrl;
    output.push(/*#__PURE__*/_react.default.createElement(_ui.Action, {
      key: "link-".concat(matchIndex),
      href: linkUrl,
      paragraph: true,
      rel: "noopener noreferrer",
      target: "_blank",
      underline: true
    }, linkLabel));
    lastIndex = matchIndex + rawMatch.length;
  }
  if (lastIndex < text.length) {
    const remainingText = text.slice(lastIndex);
    const renderedRemaining = renderTextWithLineBreaks(remainingText, "text-".concat(lastIndex));
    if (Array.isArray(renderedRemaining)) {
      output.push(...renderedRemaining);
    } else {
      output.push(renderedRemaining);
    }
  }
  return output;
};
exports.formatText = formatText;
//# sourceMappingURL=formatText.js.map