convertToMarkdown static method

ResultMarkdown convertToMarkdown(
  1. MarkdownType type,
  2. String data,
  3. int fromIndex,
  4. int toIndex, {
  5. int titleSize = 1,
  6. String? link,
  7. String selectedText = '',
})

Convert data part into ResultMarkdown from type. Use fromIndex and toIndex for converting part of data titleSize is used for markdown titles link is used for link conversion type

Implementation

static ResultMarkdown convertToMarkdown(MarkdownType type, String data, int fromIndex, int toIndex,
    {int titleSize = 1, String? link, String selectedText = ''}) {
  late String changedData;
  late int replaceCursorIndex;

  final lesserIndex = min(fromIndex, toIndex);
  final greaterIndex = max(fromIndex, toIndex);

  fromIndex = lesserIndex;
  toIndex = greaterIndex;

  switch (type) {
    case MarkdownType.bold:
      changedData = '**${data.substring(fromIndex, toIndex)}**';
      replaceCursorIndex = 2;
      break;
    case MarkdownType.italic:
      changedData = '_${data.substring(fromIndex, toIndex)}_';
      replaceCursorIndex = 1;
      break;
    case MarkdownType.strikethrough:
      changedData = '~~${data.substring(fromIndex, toIndex)}~~';
      replaceCursorIndex = 2;
      break;
    case MarkdownType.link:
      changedData = '[$selectedText](${link ?? selectedText})';
      replaceCursorIndex = 0;
      break;
    case MarkdownType.title:
      changedData = "${"#" * titleSize} ${data.substring(fromIndex, toIndex)}";
      replaceCursorIndex = 0;
      break;
    case MarkdownType.list:
      var index = 0;
      final splitedData = data.substring(fromIndex, toIndex).split('\n');
      changedData = splitedData.map((value) {
        index++;
        return index == splitedData.length ? '* $value' : '* $value\n';
      }).join();
      replaceCursorIndex = 0;
      break;
    case MarkdownType.code:
      changedData = '```${data.substring(fromIndex, toIndex)}```';
      replaceCursorIndex = 3;
      break;
    case MarkdownType.blockquote:
      var index = 0;
      final splitedData = data.substring(fromIndex, toIndex).split('\n');
      changedData = splitedData.map((value) {
        index++;
        return index == splitedData.length ? '> $value' : '> $value\n';
      }).join();
      replaceCursorIndex = 0;
      break;
    case MarkdownType.separator:
      changedData = '\n------\n${data.substring(fromIndex, toIndex)}';
      replaceCursorIndex = 0;
      break;
    case MarkdownType.image:
      changedData = '![${data.substring(fromIndex, toIndex)}](${data.substring(fromIndex, toIndex)})';
      replaceCursorIndex = 3;
      break;
  }

  final cursorIndex = changedData.length;

  return ResultMarkdown(data.substring(0, fromIndex) + changedData + data.substring(toIndex, data.length),
      cursorIndex, replaceCursorIndex);
}