all repos — snow-editor @ da44ba535c2043b2be1afcd3798276c63ca7e677

small and cozy markdown, and orgmode editor

src/lib/parseOrgMode.js (view raw)

 1
 2
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
function escapeHtml(text) {
  return text
    .replace(/&/g, '&')
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;')
    .replace(/"/g, '&quot;');
}

function sanitizeHref(url) {
  const trimmed = url.trim();
  if (/^https?:\/\//i.test(trimmed)) {
    return escapeHtml(trimmed);
  }
  return null;
}

function sanitizeLanguage(language) {
  const trimmed = language.trim();
  if (!trimmed) return 'text';
  if (/^[a-zA-Z0-9#+.-]+$/.test(trimmed)) {
    return escapeHtml(trimmed);
  }
  return 'text';
}

function parseOrgInline(text) {
  const placeholders = [];
  let working = escapeHtml(text);

  const stash = (html) => {
    const key = `\x00ORG${placeholders.length}PH\x00`;
    placeholders.push(html);
    return key;
  };

  working = working.replace(
    /\[\[([^\]]+)\]\[([^\]]+)\]\]/g,
    (_, url, label) => {
      const href = sanitizeHref(url);
      if (!href) return escapeHtml(`[[${url}][${label}]]`);
      return stash(
        `<a href="${href}" rel="noopener noreferrer">${escapeHtml(label)}</a>`,
      );
    },
  );

  working = working.replace(/\[\[([^\]]+)\]\]/g, (_, url) => {
    const href = sanitizeHref(url);
    if (!href) return escapeHtml(`[[${url}]]`);
    return stash(`<a href="${href}" rel="noopener noreferrer">${href}</a>`);
  });

  working = working.replace(/~([^~]+)~/g, (_, code) => `<code>${code}</code>`);
  working = working.replace(/=([^=]+)=/g, (_, code) => `<code>${code}</code>`);
  working = working.replace(/\*([^*]+)\*/g, (_, bold) => `<strong>${bold}</strong>`);
  working = working.replace(/\/([^/]+)\//g, (_, italic) => `<em>${italic}</em>`);

  placeholders.forEach((html, index) => {
    working = working.replace(`\x00ORG${index}PH\x00`, html);
  });

  return working;
}

function parseHeading(line) {
  const match = line.match(/^(\*{1,4})\s+(?:(TODO|DONE)\s+)?(.+)$/);
  if (!match) return null;

  const level = Math.min(match[1].length, 4);
  const keyword = match[2];
  const title = match[3].trim();
  const tag = `h${level}`;

  let badge = '';
  if (keyword === 'TODO') {
    badge = '<span class="org-badge org-todo">TODO</span> ';
  } else if (keyword === 'DONE') {
    badge = '<span class="org-badge org-done">DONE</span> ';
  }

  return `<${tag}>${badge}${parseOrgInline(title)}</${tag}>`;
}

function parseListBlock(lines) {
  const items = lines
    .filter((line) => /^[-+]\s+/.test(line))
    .map((line) => `<li>${parseOrgInline(line.replace(/^[-+]\s+/, ''))}</li>`);

  if (items.length === 0) return '';
  return `<ul>${items.join('')}</ul>`;
}

function parseParagraphBlock(lines) {
  const html = lines.map((line) => parseOrgInline(line)).join('<br>');
  return `<p>${html}</p>`;
}

function extractSpecialBlocks(input) {
  const lines = input.replace(/\r\n/g, '\n').split('\n');
  const blocks = [];
  let i = 0;

  while (i < lines.length) {
    const srcMatch = lines[i].match(/^#\+BEGIN_SRC\s*(\S*)?\s*$/i);
    const quoteMatch = lines[i].match(/^#\+BEGIN_QUOTE\s*$/i);

    if (srcMatch) {
      const language = sanitizeLanguage((srcMatch[1] || '').trim());
      const codeLines = [];
      i += 1;
      while (i < lines.length && !/^#\+END_SRC\s*$/i.test(lines[i])) {
        codeLines.push(lines[i]);
        i += 1;
      }
      if (i < lines.length) i += 1;
      const langClass = ` class="language-${language}"`;
      blocks.push({
        type: 'html',
        html: `<pre><code${langClass}>${escapeHtml(codeLines.join('\n'))}</code></pre>`,
      });
      continue;
    }

    if (quoteMatch) {
      const quoteLines = [];
      i += 1;
      while (i < lines.length && !/^#\+END_QUOTE\s*$/i.test(lines[i])) {
        quoteLines.push(lines[i]);
        i += 1;
      }
      if (i < lines.length) i += 1;
      const inner =
        quoteLines.length === 0
          ? ''
          : quoteLines.map((l) => parseOrgInline(l)).join('<br>');
      blocks.push({
        type: 'html',
        html: `<blockquote>${inner}</blockquote>`,
      });
      continue;
    }

    const textLines = [];
    while (
      i < lines.length &&
      !/^#\+BEGIN_SRC/i.test(lines[i]) &&
      !/^#\+BEGIN_QUOTE/i.test(lines[i])
    ) {
      textLines.push(lines[i]);
      i += 1;
    }

    if (textLines.length > 0) {
      blocks.push({ type: 'text', lines: textLines });
    }
  }

  return blocks;
}

function parseTextBlock(lines) {
  const chunks = [];
  let current = [];

  const flush = () => {
    if (current.length === 0) return;
    chunks.push([...current]);
    current = [];
  };

  for (const line of lines) {
    if (line.trim() === '') {
      flush();
    } else {
      current.push(line);
    }
  }
  flush();

  return chunks
    .map((chunk) => {
      if (chunk.every((line) => /^[-+]\s+/.test(line))) {
        return parseListBlock(chunk);
      }
      if (chunk.length === 1) {
        const heading = parseHeading(chunk[0]);
        if (heading) return heading;
        if (/^[-+]\s+/.test(chunk[0])) return parseListBlock(chunk);
      }
      const heading = parseHeading(chunk[0]);
      if (heading) {
        return heading + (chunk.length > 1 ? parseParagraphBlock(chunk.slice(1)) : '');
      }
      return parseParagraphBlock(chunk);
    })
    .join('');
}

export function parseOrgMode(input) {
  if (!input || !input.trim()) {
    return '';
  }

  const blocks = extractSpecialBlocks(input);
  const htmlParts = [];

  for (const block of blocks) {
    if (block.type === 'html') {
      htmlParts.push(block.html);
    } else {
      htmlParts.push(parseTextBlock(block.lines));
    }
  }

  return htmlParts.join('');
}